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(
41 Option<PaletteY>,41 Option<PaletteY>,
42 Option<PaletteUv>,42 Option<PaletteUv>,
43 )> {43 )> {
44- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
45 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."44 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
46 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints45 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
47 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for46 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
48 // line against the instrumented aomdec, not just `tell()`.47 // 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- }
61 macro_rules! istep {48 macro_rules! istep {
62- ($name:literal, $val:expr) => {49+ ($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- };
71 }50 }
72 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single51 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
73 // point every square caller routes through (see `read_intra_mode_rect`).52 // point every square caller routes through (see `read_intra_mode_rect`).
74- let cfl = if cfl && side > 32 {53+ let cfl = if cfl && side > 32 { false } else { cfl };
75- false
76- } else {
77- cfl
78- };
79 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE54 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
80 // `skip` when `SegIdPreSkip`, and after it otherwise.55 // `skip` when `SegIdPreSkip`, and after it otherwise.
81 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);56 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
@@ -83,13 +58,6 @@ pub(super) fn read_intra_mode(
83 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);58 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
84 }59 }
85 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;60 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- }
93 istep!("skip", skip as i32);61 istep!("skip", skip as i32);
94 if !seg_id_pre_skip(fctx) {62 if !seg_id_pre_skip(fctx) {
95 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);63 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(
116 // that merely allows (but never uses) intrabc.84 // that merely allows (but never uses) intrabc.
117 if allow_intrabc {85 if allow_intrabc {
118 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;86 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- }
129 if use_intrabc {87 if use_intrabc {
130 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);88 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- }
134 fctx.intrabc_dv.with(|c| c.set(Some(dv)));89 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
135 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the90 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
136 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,91 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
@@ -143,21 +98,9 @@ pub(super) fn read_intra_mode(
143 let above_ctx = INTRA_MODE_CTX[above_mode];98 let above_ctx = INTRA_MODE_CTX[above_mode];
144 let left_ctx = INTRA_MODE_CTX[left_mode];99 let left_ctx = INTRA_MODE_CTX[left_mode];
145 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);100 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- }
152 istep!("mode", mode as i32);101 istep!("mode", mode as i32);
153 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {102 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
154 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);103 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- }
161 delta104 delta
162 } else {105 } else {
163 0106 0
@@ -172,18 +115,10 @@ pub(super) fn read_intra_mode(
172 let uv_mode = if !has_chroma {115 let uv_mode = if !has_chroma {
173 DC_PRED116 DC_PRED
174 } else if cfl {117 } else if cfl {
175- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
176 dec.symbol(&mut cdfs.uv_mode_cfl[mode])118 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
177 } else {119 } else {
178- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
179 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])120 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
180 };121 };
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- }
187 istep!("uv_mode", uv_mode as i32);122 istep!("uv_mode", uv_mode as i32);
188 let alpha = if cfl && uv_mode == UV_CFL_PRED {123 let alpha = if cfl && uv_mode == UV_CFL_PRED {
189 Some(read_cfl_alphas(dec, cdfs))124 Some(read_cfl_alphas(dec, cdfs))
@@ -235,32 +170,11 @@ pub(super) fn read_intra_mode(
235 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;170 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
236 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {171 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
237 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));172 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- }
244 let use_palette_y =173 let use_palette_y =
245 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;174 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- }
253 if use_palette_y {175 if use_palette_y {
254 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);176 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- }
259 let colors = read_palette_colors_y(dec, n, cache, fctx);177 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- }
264 palette_y_pending = Some((n, colors));178 palette_y_pending = Some((n, colors));
265 }179 }
266 // `read_palette_mode_info`'s UV half (decodemv.c:588): read180 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
@@ -304,19 +218,9 @@ pub(super) fn read_intra_mode(
304 && let Some(class) = filter_intra_size_class(side)218 && let Some(class) = filter_intra_size_class(side)
305 {219 {
306 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;220 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- }
314 istep!("use_filter_intra", use_filter_intra as i32);221 istep!("use_filter_intra", use_filter_intra as i32);
315 if use_filter_intra {222 if use_filter_intra {
316 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);223 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
317- if trace {
318- eprintln!("TRACE filter_intra_mode value={fi_mode}");
319- }
320 istep!("filter_intra_mode", fi_mode as i32);224 istep!("filter_intra_mode", fi_mode as i32);
321 filter_intra = Some(fi_mode);225 filter_intra = Some(fi_mode);
322 }226 }
@@ -332,9 +236,6 @@ pub(super) fn read_intra_mode(
332 palette_onscreen(mi_r, mi_c, side, side, fctx),236 palette_onscreen(mi_r, mi_c, side, side, fctx),
333 false,237 false,
334 );238 );
335- if trace {
336- eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
337- }
338 PaletteY {239 PaletteY {
339 size: n,240 size: n,
340 colors,241 colors,
@@ -361,13 +262,6 @@ pub(super) fn read_intra_mode(
361 on,262 on,
362 true,263 true,
363 );264 );
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- }
371 PaletteUv {265 PaletteUv {
372 size: n,266 size: n,
373 u_colors,267 u_colors,
@@ -493,9 +387,6 @@ pub(crate) fn cfl_ac_q3_at(
493 bh: usize,387 bh: usize,
494 sample: impl Fn(usize, usize) -> i32,388 sample: impl Fn(usize, usize) -> i32,
495 ) -> Vec<i32> {389 ) -> 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- }
499 let (cw, ch) = (bw / 2, bh / 2);390 let (cw, ch) = (bw / 2, bh / 2);
500 let mut ac = vec![0i32; cw * ch];391 let mut ac = vec![0i32; cw * ch];
501 let mut sum = 0i32;392 let mut sum = 0i32;
@@ -600,12 +491,6 @@ pub fn take_pad_unwritten_samples() -> usize {
600 PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)491 PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
601 }492 }
602 493
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-
609 /// The value [`fresh_plane`] fills with when the sentinel is on.494 /// The value [`fresh_plane`] fills with when the sentinel is on.
610 ///495 ///
611 /// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in496 /// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in
@@ -623,24 +508,7 @@ pub(super) const MAX_LEGAL_SAMPLE: u16 = 4095;
623 /// [`census_unwritten_grained`] counts the same value. The fill and the census508 /// [`census_unwritten_grained`] counts the same value. The fill and the census
624 /// must agree on both the value and the predicate, or a "0" means nothing.509 /// must agree on both the value and the predicate, or a "0" means nothing.
625 pub(crate) fn plane_poison() -> u16 {510 pub(crate) fn plane_poison() -> u16 {
626- static V: std::sync::LazyLock<u16> = std::sync::LazyLock::new(|| {511+ PLANE_SENTINEL
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
644 }512 }
645 513
646 thread_local! {514 thread_local! {
@@ -652,8 +520,7 @@ thread_local! {
652 /// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled.520 /// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled.
653 /// `pub(crate)` for the same reason as [`plane_poison`].521 /// `pub(crate)` for the same reason as [`plane_poison`].
654 pub(crate) fn plane_sentinel_on() -> bool {522 pub(crate) fn plane_sentinel_on() -> bool {
655- crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL")523+ PLANE_SENTINEL_ON.with(std::cell::Cell::get)
656- || PLANE_SENTINEL_ON.with(std::cell::Cell::get)
657 }524 }
658 525
659 /// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this526 /// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this
@@ -834,19 +701,6 @@ pub(super) fn refuse_invalid_subsize(
834 // records, per CALL SITE and per partition value, how often the guard was701 // records, per CALL SITE and per partition value, how often the guard was
835 // reached and how often it fired, so a site that never sees an offending702 // reached and how often it fired, so a site that never sees an offending
836 // value is visible instead of assumed covered.703 // 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- }
850 let (bw, bh) = partition_subsize_dims(bsize, part);704 let (bw, bh) = partition_subsize_dims(bsize, part);
851 if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) {705 if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) {
852 Ok(())706 Ok(())
@@ -864,21 +718,6 @@ pub(super) static SUBSIZE_ARM: std::sync::LazyLock<
864 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize), usize>>,718 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize), usize>>,
865 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));719 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
866 720
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-
882 /// Prints and clears the [`note_subsize_arm`] table.721 /// Prints and clears the [`note_subsize_arm`] table.
883 pub fn dump_subsize_arm_scan() {722 pub fn dump_subsize_arm_scan() {
884 let Ok(mut m) = SUBSIZE_ARM.lock() else {723 let Ok(mut m) = SUBSIZE_ARM.lock() else {
@@ -901,23 +740,6 @@ pub(super) static SUBSIZE_GUARD: std::sync::LazyLock<
901 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize, usize, bool), usize>>,740 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize, usize, bool), usize>>,
902 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));741 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
903 742
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-
921 /// Prints and clears the [`refuse_invalid_subsize`] table: one line per743 /// Prints and clears the [`refuse_invalid_subsize`] table: one line per
922 /// (site, block, partition value) with the times reached and whether the guard744 /// (site, block, partition value) with the times reached and whether the guard
923 /// fired. `decode_probe` calls this at exit.745 /// fired. `decode_probe` calls this at exit.
@@ -1064,52 +886,6 @@ pub(super) struct PlaneBuf<'a> {
1064 pub(super) plane: u8,886 pub(super) plane: u8,
1065 }887 }
1066 888
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-
1113 impl PlaneBuf<'_> {889 impl PlaneBuf<'_> {
1114 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/890 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
1115 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`891 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
@@ -1229,18 +1005,6 @@ impl PlaneBuf<'_> {
1229 buf1005 buf
1230 } else {1006 } else {
1231 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);1007 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- }
1244 let mut prediction = vec![0u16; bw * bh];1008 let mut prediction = vec![0u16; bw * bh];
1245 if let Some(fi_mode) = filter_intra {1009 if let Some(fi_mode) = filter_intra {
1246 crate::intra::predict_filter_intra(1010 crate::intra::predict_filter_intra(
@@ -1273,25 +1037,7 @@ impl PlaneBuf<'_> {
1273 };1037 };
1274 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's1038 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
1275 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).1039 // 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- }
1287 let residual = dense_residual(residual, bw * bh);1040 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- }
1295 for row in 0..bh {1041 for row in 0..bh {
1296 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s1042 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
1297 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame1043 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
@@ -1312,16 +1058,6 @@ impl PlaneBuf<'_> {
1312 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));1058 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
1313 }1059 }
1314 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;1060 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- );
1325 self.data.to_mut()[(y + row) * self.width + x + col] = sample;1061 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
1326 }1062 }
1327 }1063 }
@@ -1329,15 +1065,6 @@ impl PlaneBuf<'_> {
1329 // -- a block whose prediction matches the oracle's but whose written1065 // -- a block whose prediction matches the oracle's but whose written
1330 // samples do not is either a residual defect or a later overwrite, and1066 // samples do not is either a residual defect or a later overwrite, and
1331 // only this print separates the two.1067 // 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- }
1341 }1068 }
1342 1069
1343 /// Predicts under `mode` then adds `residual` (side*side, raster),1070 /// Predicts under `mode` then adds `residual` (side*side, raster),
@@ -1384,13 +1111,6 @@ impl PlaneBuf<'_> {
1384 buf1111 buf
1385 } else {1112 } else {
1386 let (above, left, corner) = self.edges(x, y, side, reach);1113 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- }
1394 let mut prediction = vec![0u16; side * side];1114 let mut prediction = vec![0u16; side * side];
1395 if let Some(fi_mode) = filter_intra {1115 if let Some(fi_mode) = filter_intra {
1396 crate::intra::predict_filter_intra(1116 crate::intra::predict_filter_intra(
@@ -1430,26 +1150,7 @@ impl PlaneBuf<'_> {
1430 };1150 };
1431 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's1151 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
1432 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).1152 // 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- }
1444 let residual = dense_residual(residual, side * side);1153 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- }
1453 for row in 0..side {1154 for row in 0..side {
1454 // lane-sb128c r8: libaom's frame buffer is superblock1155 // lane-sb128c r8: libaom's frame buffer is superblock
1455 // aligned; ours is padded to 32 (`block_grid`), so a 64x641156 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
@@ -1475,16 +1176,6 @@ impl PlaneBuf<'_> {
1475 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));1176 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
1476 }1177 }
1477 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;1178 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- );
1488 self.data.to_mut()[(y + row) * self.width + x + col] = sample;1179 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
1489 }1180 }
1490 }1181 }
@@ -1501,9 +1192,6 @@ pub(super) fn read_plane(
1501 scan: &[u16],1192 scan: &[u16],
1502 plane_idx: usize,1193 plane_idx: usize,
1503 around: (bool, bool, i32),1194 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.
1507 tx_mode: usize,1195 tx_mode: usize,
1508 predict_mode: usize,1196 predict_mode: usize,
1509 angle_delta: i32,1197 angle_delta: i32,
@@ -1515,17 +1203,9 @@ pub(super) fn read_plane(
1515 cy: usize,1203 cy: usize,
1516 side: usize,1204 side: usize,
1517 tx_side: usize,1205 tx_side: usize,
1518- base_q_idx: u8,
1519 cfl: Option<(i32, CflSrc)>,1206 cfl: Option<(i32, CflSrc)>,
1520 filter_intra: Option<usize>,1207 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.
1527 luma_skip_ctx: Option<usize>,1208 luma_skip_ctx: Option<usize>,
1528- // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
1529 smooth_neighbor: bool,1209 smooth_neighbor: bool,
1530 fctx: &crate::decode::FrameCtx,1210 fctx: &crate::decode::FrameCtx,
1531 ) -> Result<Grid> {1211 ) -> Result<Grid> {
@@ -1562,12 +1242,6 @@ pub(super) fn read_plane(
1562 // labelling its unit `plane=0`, and a sweep reading a second-luma-unit1242 // labelling its unit `plane=0`, and a sweep reading a second-luma-unit
1563 // phantom out of that label (class `rung-mislabels-plane`). Diagnostic1243 // phantom out of that label (class `rung-mislabels-plane`). Diagnostic
1564 // only: no gate asserts decode behaviour off this line.1244 // 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- }
1571 let tx_mode = if plane_idx == 0 {1245 let tx_mode = if plane_idx == 0 {
1572 fi_tx_row(tx_mode, filter_intra)1246 fi_tx_row(tx_mode, filter_intra)
1573 } else {1247 } else {
@@ -1642,7 +1316,6 @@ pub(super) fn read_plane(
1642 default_tx_type,1316 default_tx_type,
1643 None,1317 None,
1644 )?;1318 )?;
1645- note_chroma_class1(plane_idx, tx_type);
1646 if plane_idx == 0 {1319 if plane_idx == 0 {
1647 fctx.luma_tx_type.with(|c| c.set(tx_type));1320 fctx.luma_tx_type.with(|c| c.set(tx_type));
1648 }1321 }
@@ -1669,13 +1342,6 @@ pub(super) fn read_plane(
1669 stride: 0,1342 stride: 0,
1670 lossless: lossless(fctx),1343 lossless: lossless(fctx),
1671 };1344 };
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- }
1679 push_intra_tx(1345 push_intra_tx(
1680 y,1346 y,
1681 u,1347 u,
@@ -1842,7 +1508,6 @@ pub(super) fn read_rect_chroma_unit(
1842 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),1508 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
1843 dc_sign_ctx(around.2),1509 dc_sign_ctx(around.2),
1844 default_tx,1510 default_tx,
1845- plane_idx,
1846 )?;1511 )?;
1847 let residual = dequant_and_inverse_typed_wh(1512 let residual = dequant_and_inverse_typed_wh(
1848 &levels,1513 &levels,
@@ -1912,7 +1577,6 @@ pub(super) fn decode_block(
1912 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);1577 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
1913 let palette_uv_cache = neighbours.palette_uv_cache(at);1578 let palette_uv_cache = neighbours.palette_uv_cache(at);
1914 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);1579 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);
1916 let (1580 let (
1917 skip,1581 skip,
1918 mode,1582 mode,
@@ -2010,12 +1674,6 @@ pub(super) fn decode_block(
2010 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);1674 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
2011 let smooth_neighbor_uv =1675 let smooth_neighbor_uv =
2012 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);1676 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- }
2019 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));1677 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2020 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra1678 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
2021 // block, skipped or not. `logical_tx` is what the loop filter's edge1679 // block, skipped or not. `logical_tx` is what the loop filter's edge
@@ -2085,14 +1743,7 @@ pub(super) fn decode_block(
2085 .iter()1743 .iter()
2086 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)1744 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
2087 });1745 });
2088- if !uniform {1746+ 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- }
2096 Some(leaves)1747 Some(leaves)
2097 } else {1748 } else {
2098 None1749 None
@@ -2280,11 +1931,6 @@ pub(super) fn decode_block(
2280 tu_row * logical_tx,1931 tu_row * logical_tx,
2281 logical_tx,1932 logical_tx,
2282 reach,1933 reach,
2283- px,
2284- py,
2285- y.width,
2286- y.height,
2287- fctx,
2288 );1934 );
2289 push_intra(1935 push_intra(
2290 y,1936 y,
@@ -2349,11 +1995,6 @@ pub(super) fn decode_block(
2349 luma_span_x,1995 luma_span_x,
2350 luma_span_y,1996 luma_span_y,
2351 reach,1997 reach,
2352- px,
2353- py,
2354- y.width,
2355- y.height,
2356- fctx,
2357 )1998 )
2358 };1999 };
2359 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);2000 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(
2451 // side`, so only 4:2:2 changes.2092 // side`, so only 4:2:2 changes.
2452 let u_grid = vec![0i32; chroma_side * chroma_height];2093 let u_grid = vec![0i32; chroma_side * chroma_height];
2453 let v_grid = vec![0i32; chroma_side * chroma_height];2094 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());
2462 neighbours.record(2095 neighbours.record(
2463 at,2096 at,
2464 side,2097 side,
@@ -2494,7 +2127,6 @@ pub(super) fn decode_block(
2494 py,2127 py,
2495 side,2128 side,
2496 coeff_tx_side,2129 coeff_tx_side,
2497- base_q_idx,
2498 None,2130 None,
2499 filter_intra,2131 filter_intra,
2500 None,2132 None,
@@ -2547,19 +2179,12 @@ pub(super) fn decode_block(
2547 cpy,2179 cpy,
2548 chroma_side,2180 chroma_side,
2549 chroma_tx,2181 chroma_tx,
2550- base_q_idx,
2551 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),2182 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
2552 None,2183 None,
2553 None,2184 None,
2554 smooth_neighbor_uv,2185 smooth_neighbor_uv,
2555 fctx,2186 fctx,
2556 )?;2187 )?;
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- }
2563 if let Some((_, vb)) = &palette_uv_bufs {2188 if let Some((_, vb)) = &palette_uv_bufs {
2564 set_palette_pred(vb.clone(), fctx);2189 set_palette_pred(vb.clone(), fctx);
2565 }2190 }
@@ -2581,7 +2206,6 @@ pub(super) fn decode_block(
2581 cpy,2206 cpy,
2582 chroma_side,2207 chroma_side,
2583 chroma_tx,2208 chroma_tx,
2584- base_q_idx,
2585 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),2209 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
2586 None,2210 None,
2587 None,2211 None,
@@ -2679,11 +2303,6 @@ pub(super) fn decode_block(
2679 luma_span_x,2303 luma_span_x,
2680 luma_span_y,2304 luma_span_y,
2681 reach,2305 reach,
2682- px,
2683- py,
2684- y.width,
2685- y.height,
2686- fctx,
2687 );2306 );
2688 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);2307 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
2689 if let Some((ub, vb)) = &palette_uv_bufs {2308 if let Some((ub, vb)) = &palette_uv_bufs {
@@ -2718,7 +2337,6 @@ pub(super) fn decode_block(
2718 cu_y,2337 cu_y,
2719 chroma_tx,2338 chroma_tx,
2720 chroma_tx,2339 chroma_tx,
2721- base_q_idx,
2722 alpha2340 alpha
2723 .zip(ac)2341 .zip(ac)
2724 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),2342 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
@@ -2852,10 +2470,7 @@ pub(super) fn decode_block(
2852 // top-right 8x8 unit of a 16x16 D203 block bottom-left2470 // top-right 8x8 unit of a 16x16 D203 block bottom-left
2853 // pixels libaom refuses outright (`col_off > 0`), which is2471 // pixels libaom refuses outright (`col_off > 0`), which is
2854 // the diagonal wedge seed 46 reconstructed wrong.2472 // the diagonal wedge seed 46 reconstructed wrong.
2855- let tu_reach = tu_reach(2473+ let tu_reach = tu_reach(side, side, tu_off_x, tu_off_y, tu_tx, reach);
2856- side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
2857- fctx,
2858- );
2859 // This transform unit's own bsize (`tu_tx`) is smaller2474 // This transform unit's own bsize (`tu_tx`) is smaller
2860 // than the block it sits in (`side`), so `txb_skip_ctx` is2475 // than the block it sits in (`side`), so `txb_skip_ctx` is
2861 // the neighbour-magnitude table, not the lone-TU 0 (spec2476 // the neighbour-magnitude table, not the lone-TU 0 (spec
@@ -2905,26 +2520,13 @@ pub(super) fn decode_block(
2905 tu_px,2520 tu_px,
2906 tu_py,2521 tu_py,
2907 tu_tx,2522 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).
2912 if tu_tx == 64 { 32 } else { tu_tx },2523 if tu_tx == 64 { 32 } else { tu_tx },
2913- base_q_idx,
2914 None,2524 None,
2915 filter_intra,2525 filter_intra,
2916 Some(tu_skip_ctx),2526 Some(tu_skip_ctx),
2917 smooth_neighbor,2527 smooth_neighbor,
2918 fctx,2528 fctx,
2919 )?;2529 )?;
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- }
2928 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);2530 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
2929 if first_leaf_tx.is_none() {2531 if first_leaf_tx.is_none() {
2930 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));2532 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
@@ -3036,11 +2638,6 @@ pub(super) fn decode_block(
3036 luma_span_x,2638 luma_span_x,
3037 luma_span_y,2639 luma_span_y,
3038 reach,2640 reach,
3039- px,
3040- py,
3041- y.width,
3042- y.height,
3043- fctx,
3044 )2641 )
3045 };2642 };
3046 let (cu_x, cu_y) =2643 let (cu_x, cu_y) =
@@ -3078,7 +2675,6 @@ pub(super) fn decode_block(
3078 cu_y,2675 cu_y,
3079 chroma_tx,2676 chroma_tx,
3080 chroma_tx,2677 chroma_tx,
3081- base_q_idx,
3082 alpha.zip(ac).map(|((au, av), ac)| {2678 alpha.zip(ac).map(|((au, av), ac)| {
3083 (if plane_pass == 1 { au } else { av }, ac)2679 (if plane_pass == 1 { au } else { av }, ac)
3084 }),2680 }),
crates/ec-av1/src/decode/coeffs.rsmodified+74 -541
@@ -2,70 +2,6 @@
2 2
3 use super::*;3 use super::*;
4 4
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-
69 // lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.5 // lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
70 #[track_caller]6 #[track_caller]
71 pub(super) fn read_coeffs(7 pub(super) fn read_coeffs(
@@ -88,65 +24,11 @@ pub(super) fn read_coeffs(
88 // caller's block genuinely is `side` x `side`.24 // caller's block genuinely is `side` x `side`.
89 rect_shape: Option<(usize, usize)>,25 rect_shape: Option<(usize, usize)>,
90 ) -> Result<(Grid, TxType)> {26 ) -> Result<(Grid, TxType)> {
91- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
92 let side = coding.side;27 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- };
115 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;28 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
116 // lane-ibc444c: this reader logs an `all_zero` step even for a read that29 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
117 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --30 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
118 // filter on it before pairing anything against the oracle.31 // 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- }
150 if all_zero {32 if all_zero {
151 return Ok((Grid::Zero(side * side), TxType::DctDct));33 return Ok((Grid::Zero(side * side), TxType::DctDct));
152 }34 }
@@ -162,22 +44,7 @@ pub(super) fn read_coeffs(
162 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two44 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
163 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).45 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
164 let len = tx_type_cdf.len();46 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");
169 let t = dec.symbol(tx_type_cdf);47 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- }
181 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {48 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
182 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))49 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
183 })?;50 })?;
@@ -185,19 +52,6 @@ pub(super) fn read_coeffs(
185 52
186 let class = TxClass::of(tx_type);53 let class = TxClass::of(tx_type);
187 let eob = read_eob(dec, coding, class);54 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- }
201 let class_scan;55 let class_scan;
202 let scan: &[u16] = if class == TxClass::TwoD {56 let scan: &[u16] = if class == TxClass::TwoD {
203 scan57 scan
@@ -238,9 +92,6 @@ pub(super) fn read_coeffs(
238 let level = if scan_idx == eob - 1 {92 let level = if scan_idx == eob - 1 {
239 let ctx = eob_coeff_ctx(scan_idx, side * side);93 let ctx = eob_coeff_ctx(scan_idx, side * side);
240 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;94 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- }
244 v95 v
245 } else {96 } else {
246 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {97 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
@@ -254,14 +105,6 @@ pub(super) fn read_coeffs(
254 base_ctx(levels, stride, row, col, class, rect_shape)105 base_ctx(levels, stride, row, col, class, rect_shape)
255 };106 };
256 let v = dec.symbol(&mut coding.base[ctx]) as i32;107 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- }
265 v108 v
266 };109 };
267 let level = if level > NUM_BASE_LEVELS {110 let level = if level > NUM_BASE_LEVELS {
@@ -282,16 +125,6 @@ pub(super) fn read_coeffs(
282 let mut sent = 0;125 let mut sent = 0;
283 loop {126 loop {
284 let k = dec.symbol(&mut coding.br[ctx]) as i32;127 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- }
295 level += k;128 level += k;
296 sent += BR_STEP;129 sent += BR_STEP;
297 if k < BR_STEP || sent >= COEFF_BASE_RANGE {130 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
@@ -302,9 +135,6 @@ pub(super) fn read_coeffs(
302 } else {135 } else {
303 level136 level
304 };137 };
305- if ec_trace_coeff && scan_idx == eob - 1 {
306- coeff_step_base_eob_level(dec, level);
307- }
308 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus138 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
309 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is139 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
310 // added in the sign pass below, straight into `grid`), so the context140 // added in the sign pass below, straight into `grid`), so the context
@@ -317,10 +147,6 @@ pub(super) fn read_coeffs(
317 nz_n += 1;147 nz_n += 1;
318 }148 }
319 }149 }
320- if ec_trace_coeff {
321- let (rng, _) = dec.debug_state();
322- eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
323- }
324 150
325 for &packed in nz_buf[..nz_n].iter().rev() {151 for &packed in nz_buf[..nz_n].iter().rev() {
326 let c = (packed >> 4) as usize;152 let c = (packed >> 4) as usize;
@@ -328,28 +154,16 @@ pub(super) fn read_coeffs(
328 let level = (packed & 15) as i32;154 let level = (packed & 15) as i32;
329 let negative = if pos == 0 {155 let negative = if pos == 0 {
330 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;156 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- }
334 v157 v
335 } else {158 } else {
336 dec.literal(1) == 1159 dec.literal(1) == 1
337 };160 };
338- if ec_trace_coeff {
339- coeff_step_sign(dec, c, negative);
340- }
341 let level = if level > MAX_BR_LEVEL {161 let level = if level > MAX_BR_LEVEL {
342 let g = read_golomb(dec)?;162 let g = read_golomb(dec)?;
343- if trace {
344- eprintln!("TRACE golomb pos={pos} value={g}");
345- }
346 level + g as i32163 level + g as i32
347 } else {164 } else {
348 level165 level
349 };166 };
350- if ec_trace_coeff {
351- coeff_step_post_golomb(dec, c, level);
352- }
353 grid[pos] = if negative { -level } else { level };167 grid[pos] = if negative { -level } else { level };
354 }168 }
355 Ok((Grid::Own(grid), tx_type))169 Ok((Grid::Own(grid), tx_type))
@@ -379,38 +193,8 @@ pub(super) fn read_coeffs_rect(
379 skip_ctx: usize,193 skip_ctx: usize,
380 sign_ctx: usize,194 sign_ctx: usize,
381 default_tx_type: TxType,195 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,
387 ) -> Result<(Grid, TxType)> {196 ) -> 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;
392 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;197 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- }
414 if all_zero {198 if all_zero {
415 return Ok((Grid::Zero(w * h), TxType::DctDct));199 return Ok((Grid::Zero(w * h), TxType::DctDct));
416 }200 }
@@ -428,21 +212,9 @@ pub(super) fn read_coeffs_rect(
428 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {212 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
429 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))213 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
430 })?;214 })?;
431- if rect_trace {
432- eprintln!(
433- "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
434- dec.debug_state().0
435- );
436- }
437 }215 }
438 let class = TxClass::of(tx_type);216 let class = TxClass::of(tx_type);
439 let eob = read_eob(dec, coding, class);217 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- }
446 let class_scan;218 let class_scan;
447 let scan: &[u16] = if class == TxClass::TwoD {219 let scan: &[u16] = if class == TxClass::TwoD {
448 scan220 scan
@@ -514,12 +286,6 @@ pub(super) fn read_coeffs_rect(
514 base_ctx_rect(levels, stride, w, h, row, col, class)286 base_ctx_rect(levels, stride, w, h, row, col, class)
515 };287 };
516 let v = dec.symbol(&mut coding.base[ctx]) as i32;288 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- }
523 v289 v
524 };290 };
525 let level = if level > NUM_BASE_LEVELS {291 let level = if level > NUM_BASE_LEVELS {
@@ -540,12 +306,6 @@ pub(super) fn read_coeffs_rect(
540 let mut sent = 0;306 let mut sent = 0;
541 loop {307 loop {
542 let k = dec.symbol(&mut coding.br[ctx]) as i32;308 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- }
549 level += k;309 level += k;
550 sent += BR_STEP;310 sent += BR_STEP;
551 if k < BR_STEP || sent >= COEFF_BASE_RANGE {311 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
@@ -562,19 +322,6 @@ pub(super) fn read_coeffs_rect(
562 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;322 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
563 nz_n += 1;323 nz_n += 1;
564 }324 }
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}");
578 }325 }
579 for &packed in nz_buf[..nz_n].iter().rev() {326 for &packed in nz_buf[..nz_n].iter().rev() {
580 let pos = scan[(packed >> 4) as usize] as usize;327 let pos = scan[(packed >> 4) as usize] as usize;
@@ -584,51 +331,18 @@ pub(super) fn read_coeffs_rect(
584 } else {331 } else {
585 dec.literal(1) == 1332 dec.literal(1) == 1
586 };333 };
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- }
594 let level = if level > MAX_BR_LEVEL {334 let level = if level > MAX_BR_LEVEL {
595 let g = read_golomb(dec)?;335 let g = read_golomb(dec)?;
596 level + g as i32336 level + g as i32
597 } else {337 } else {
598 level338 level
599 };339 };
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- }
614 grid[pos] = if negative { -level } else { level };340 grid[pos] = if negative { -level } else { level };
615 }341 }
616 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the342 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
617 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose343 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
618 // grids differ is a reader defect, one whose grids agree is a transform344 // grids differ is a reader defect, one whose grids agree is a transform
619 // defect.345 // 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- }
632 Ok((Grid::Own(grid), tx_type))346 Ok((Grid::Own(grid), tx_type))
633 }347 }
634 348
@@ -660,25 +374,11 @@ pub(super) fn read_chroma_coeffs_rect(
660 sign_ctx: usize,374 sign_ctx: usize,
661 default_tx_type: TxType,375 default_tx_type: TxType,
662 fctx: &crate::decode::FrameCtx,376 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,
667 ) -> Result<(Grid, TxType)> {377 ) -> Result<(Grid, TxType)> {
668 if mono(fctx) {378 if mono(fctx) {
669 return Ok((Grid::Zero(w * h), TxType::DctDct));379 return Ok((Grid::Zero(w * h), TxType::DctDct));
670 }380 }
671- read_coeffs_rect(381+ read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
672- dec,
673- coding,
674- scan,
675- w,
676- h,
677- skip_ctx,
678- sign_ctx,
679- default_tx_type,
680- plane,
681- )
682 }382 }
683 383
684 /// What one coded block leaves behind for the blocks that read it as a384 /// What one coded block leaves behind for the blocks that read it as a
@@ -1175,7 +875,13 @@ impl Neighbours {
1175 /// [`SUB`]-grid cell it covers on both the above and left edges --875 /// [`SUB`]-grid cell it covers on both the above and left edges --
1176 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's876 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1177 /// call sites are all square blocks).877 /// 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+ ) {
1179 self.record_palette_y_rect(885 self.record_palette_y_rect(
1180 (at.0 * (SUB / MI), at.1 * (SUB / MI)),886 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
1181 side,887 side,
@@ -1198,9 +904,6 @@ impl Neighbours {
1198 colors: [u16; 8],904 colors: [u16; 8],
1199 ) {905 ) {
1200 let (r, c) = mi;906 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- }
1204 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`907 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
1205 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi908 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
1206 // cell immediately left of the block, not its 16px [`SUB`] cell. The909 // cell immediately left of the block, not its 16px [`SUB`] cell. The
@@ -1575,11 +1278,6 @@ impl Neighbours {
1575 // TX_32X32 -- independent of this block's luma `tx_depth`.1278 // TX_32X32 -- independent of this block's luma `tx_depth`.
1576 let uv_tx_w = ((w_mi * MI) >> ss_x(fctx)).clamp(4, 32) as u8;1279 let uv_tx_w = ((w_mi * MI) >> ss_x(fctx)).clamp(4, 32) as u8;
1577 let uv_tx_h = ((h_mi * MI) >> ss_y(fctx)).clamp(4, 32) as u8;1280 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- }
1583 let cur = fctx.current_delta_lf.with(|c| c.get());1281 let cur = fctx.current_delta_lf.with(|c| c.get());
1584 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {1282 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
1585 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)1283 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
@@ -1668,11 +1366,6 @@ impl Neighbours {
1668 tx_h_px: u8,1366 tx_h_px: u8,
1669 ) {1367 ) {
1670 let (mi_r, mi_c) = at_mi;1368 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- }
1676 for rr in 0..h_mi {1369 for rr in 0..h_mi {
1677 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;1370 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
1678 fill_span(&mut self.tx_grid, start, w_mi, tx_px);1371 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
@@ -1689,7 +1382,13 @@ impl Neighbours {
1689 }1382 }
1690 1383
1691 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).1384 /// [`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+ ) {
1693 let (mi_r, mi_c) = at_mi;1392 let (mi_r, mi_c) = at_mi;
1694 for rr in 0..h_mi {1393 for rr in 0..h_mi {
1695 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;1394 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
@@ -1842,7 +1541,8 @@ impl Neighbours {
1842 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the1541 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1843 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs1542 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1844 /// the real value, not just `is_inter`).1543 /// the real value, not just `is_inter`).
1845- #[allow(dead_code)] // read only from the `#[cfg(test)]` gates1544+ #[allow(dead_code)]
1545+ // read only from the `#[cfg(test)]` gates
1846 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.1546 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1847 #[allow(clippy::too_many_arguments)]1547 #[allow(clippy::too_many_arguments)]
1848 pub(super) fn record_inter(1548 pub(super) fn record_inter(
@@ -2051,7 +1751,11 @@ impl Neighbours {
2051 1751
2052 /// [`Self::around`] taking the block's position directly in 4x4 mode-info1752 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
2053 /// units, for the same reason [`Self::record_mi`] does.1753 /// 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] {
2055 let side_mi = side / MI;1759 let side_mi = side / MI;
2056 // One pass over the cells accumulating all three planes, not one pass1760 // One pass over the cells accumulating all three planes, not one pass
2057 // per plane: the three planes of a cell live in the same1761 // per plane: the three planes of a cell live in the same
@@ -2116,45 +1820,18 @@ impl Neighbours {
2116 o.2 += dc_vote(left[plane].dc);1820 o.2 += dc_vote(left[plane].dc);
2117 }1821 }
2118 }1822 }
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- }
2151 out1823 out
2152 }1824 }
2153 1825
2154 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in1826 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
2155 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric1827 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
2156 /// extent pattern for a true rectangular strip's own coefficient context.1828 /// 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] {
2158 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)1835 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
2159 }1836 }
2160 1837
@@ -2185,34 +1862,6 @@ impl Neighbours {
2185 o.2 += dc_vote(left[plane].dc);1862 o.2 += dc_vote(left[plane].dc);
2186 }1863 }
2187 }1864 }
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- }
2216 out1865 out
2217 }1866 }
2218 1867
@@ -2230,8 +1879,12 @@ impl Neighbours {
2230 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi1879 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
2231 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above1880 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
2232 /// context over `tx_size_wide` and the left one over `tx_size_high`.1881 /// 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 {1882+ pub(super) fn luma_skip_ctx_rect(
2234- let side_mi = w_mi;1883+ &self,
1884+ (mi_r, mi_c): (usize, usize),
1885+ w_mi: usize,
1886+ h_mi: usize,
1887+ ) -> usize {
2235 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));1888 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
2236 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));1889 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
2237 let mut top = 0u8;1890 let mut top = 0u8;
@@ -2243,12 +1896,6 @@ impl Neighbours {
2243 left |= self.left[mi_r + cell][0].level;1896 left |= self.left[mi_r + cell][0].level;
2244 }1897 }
2245 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];1898 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- }
2252 ctx1899 ctx
2253 }1900 }
2254 1901
@@ -2283,7 +1930,14 @@ impl Neighbours {
2283 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves1930 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
2284 /// read these back, and only when the recorded position is exactly their1931 /// read these back, and only when the recorded position is exactly their
2285 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.1932 /// 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+ ) {
2287 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);1941 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
2288 let mode = mode as u8;1942 let mode = mode as u8;
2289 for cell in 0..mi_w {1943 for cell in 0..mi_w {
@@ -2361,9 +2015,6 @@ impl Neighbours {
2361 for row in mi_r..=last_r {2015 for row in mi_r..=last_r {
2362 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);2016 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
2363 }2017 }
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- }
2367 }2018 }
2368 2019
2369 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`2020 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
@@ -2457,8 +2108,7 @@ impl Neighbours {
2457 let have_left = mi_c > self.tile_col0_mi;2108 let have_left = mi_c > self.tile_col0_mi;
2458 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED2109 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
2459 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED2110 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
2460- {2111+ {}
2461- }
2462 // The mi grid is libaom's own read; the two maps below stay as the2112 // The mi grid is libaom's own read; the two maps below stay as the
2463 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).2113 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
2464 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {2114 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
@@ -2550,7 +2200,6 @@ impl Neighbours {
2550 // The pre-lane read, kept as the counter's own-row arm: it is what2200 // The pre-lane read, kept as the counter's own-row arm: it is what
2551 // this decoder answered before the `+ss_y` term landed, and2201 // this decoder answered before the `+ss_y` term landed, and
2552 // comparing against it is what proves the term is load-bearing.2202 // comparing against it is what proves the term is load-bearing.
2553- let own_row = read_left(mi_r);
2554 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two2203 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
2555 // cells are one left mi column apart, so they are two different2204 // cells are one left mi column apart, so they are two different
2556 // blocks exactly when the left neighbour is 1 mi tall or shorter.2205 // blocks exactly when the left neighbour is 1 mi tall or shorter.
@@ -2567,19 +2216,7 @@ impl Neighbours {
2567 .copied()2216 .copied()
2568 .filter(|o| o & 0xff00_0000 == epoch)2217 .filter(|o| o & 0xff00_0000 == epoch)
2569 .unwrap_or(0);2218 .unwrap_or(0);
2570- if own != 0 && down != 0 && own != down {2219+ 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- }
2583 }2220 }
2584 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {2221 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
2585 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)2222 !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 {
2592 // have been filtered at the wrong strength by the coarse map alone.2229 // have been filtered at the wrong strength by the coarse map alone.
2593 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))2230 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
2594 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))2231 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
2595- {2232+ {}
2596- }
2597 is_smooth_mode(above) || is_smooth_mode(left)2233 is_smooth_mode(above) || is_smooth_mode(left)
2598 }2234 }
2599 2235
@@ -2648,14 +2284,12 @@ impl Neighbours {
2648 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));2284 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
2649 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))2285 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
2650 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))2286 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
2651- {2287+ {}
2652- }
2653 // A neighbour the coarse band offered where the tile edge makes it2288 // A neighbour the coarse band offered where the tile edge makes it
2654 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).2289 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
2655 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)2290 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
2656 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)2291 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
2657- {2292+ {}
2658- }
2659 (above, left)2293 (above, left)
2660 }2294 }
2661 2295
@@ -2755,16 +2389,16 @@ impl Neighbours {
2755 2389
2756 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,2390 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
2757 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).2391 /// 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+ ) {
2759 let (mi_r, mi_c) = at_mi;2399 let (mi_r, mi_c) = at_mi;
2760 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));2400 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
2761 let (w_mi, h_mi) = (w / MI, h / MI);2401 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- }
2768 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);2402 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
2769 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);2403 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
2770 // A chroma 4x4 unit straddling the true luma edge is still whole in2404 // A chroma 4x4 unit straddling the true luma edge is still whole in
@@ -2856,19 +2490,11 @@ impl Neighbours {
2856 let (step_x, step_y) = (w_px / MI, h_px / MI);2490 let (step_x, step_y) = (w_px / MI, h_px / MI);
2857 // the flags read the CALLER's origin, before the shadowing align below2491 // the flags read the CALLER's origin, before the shadowing align below
2858 let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0);2492 let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0);
2859- if row_mid || col_mid {2493+ if row_mid || col_mid {}
2860- }
2861 let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1));2494 let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1));
2862 let round_up_even = |n: usize| n.div_ceil(2) * 2;2495 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2863 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));2496 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2864 let state = neighbour_state(grid);2497 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- }
2872 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {2498 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
2873 self.left[mi_r + cell][plane] = state;2499 self.left[mi_r + cell][plane] = state;
2874 }2500 }
@@ -2888,12 +2514,6 @@ impl Neighbours {
2888 grid: &[i32],2514 grid: &[i32],
2889 ) {2515 ) {
2890 let state = neighbour_state(grid);2516 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- }
2897 for cell in 0..h_px / MI {2517 for cell in 0..h_px / MI {
2898 if mi_r + cell < self.mi_rows {2518 if mi_r + cell < self.mi_rows {
2899 self.left[mi_r + cell][0] = state;2519 self.left[mi_r + cell][0] = state;
@@ -3484,18 +3104,9 @@ pub(super) fn decode_color_index_map_wh(
3484 on: (usize, usize),3104 on: (usize, usize),
3485 uv: bool,3105 uv: bool,
3486 ) -> Vec<u8> {3106 ) -> Vec<u8> {
3487- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
3488 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));3107 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
3489 let mut map = vec![0u8; bw * bh];3108 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- }
3494 map[0] = read_uniform(dec, n) as u8;3109 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- }
3499 for i in 1..(on_bw + on_bh - 1) {3110 for i in 1..(on_bw + on_bh - 1) {
3500 let j_hi = i.min(on_bw - 1);3111 let j_hi = i.min(on_bw - 1);
3501 let j_lo = i.saturating_sub(on_bh - 1);3112 let j_lo = i.saturating_sub(on_bh - 1);
@@ -3503,28 +3114,12 @@ pub(super) fn decode_color_index_map_wh(
3503 let row = i - j;3114 let row = i - j;
3504 let col = j;3115 let col = j;
3505 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);3116 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- }
3518 let symbol = if uv {3117 let symbol = if uv {
3519 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])3118 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
3520 } else {3119 } else {
3521 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])3120 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
3522 };3121 };
3523 map[row * bw + col] = color_order[symbol];3122 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- }
3528 }3123 }
3529 }3124 }
3530 palette_replicate(&mut map, bw, bh, on);3125 palette_replicate(&mut map, bw, bh, on);
@@ -3592,9 +3187,6 @@ pub(super) fn apply_deblock(
3592 ) {3187 ) {
3593 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel3188 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
3594 // mismatch between the raw reconstruction and post-filter output.3189 // mismatch between the raw reconstruction and post-filter output.
3595- if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
3596- return;
3597- }
3598 if lf.level[0] != 0 || lf.level[1] != 0 {3190 if lf.level[0] != 0 || lf.level[1] != 0 {
3599 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);3191 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
3600 }3192 }
@@ -3684,7 +3276,6 @@ pub(super) fn tx_size_context_txfm_rect(
3684 (mi_r, mi_c): (usize, usize),3276 (mi_r, mi_c): (usize, usize),
3685 own_w: usize,3277 own_w: usize,
3686 own_h: usize,3278 own_h: usize,
3687- fctx: &crate::decode::FrameCtx,
3688 ) -> usize {3279 ) -> usize {
3689 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is3280 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is
3690 // wider or taller than 64, so a block with a 128 side resolves against 643281 // 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(
3734 };3325 };
3735 if band_above != (has_above && usize::from(above) != 0)3326 if band_above != (has_above && usize::from(above) != 0)
3736 || band_left != (has_left && usize::from(left) != 0)3327 || band_left != (has_left && usize::from(left) != 0)
3737- {3328+ {}
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- );
3761 }3329 }
3762 let ctx = match (has_above, has_left) {3330 let ctx = match (has_above, has_left) {
3763 (true, true) => usize::from(above) + usize::from(left),3331 (true, true) => usize::from(above) + usize::from(left),
@@ -3765,10 +3333,6 @@ pub(super) fn tx_size_context_txfm_rect(
3765 (false, true) => usize::from(left),3333 (false, true) => usize::from(left),
3766 (false, false) => 0,3334 (false, false) => 0,
3767 };3335 };
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- }
3772 ctx3336 ctx
3773 }3337 }
3774 3338
@@ -3778,7 +3342,11 @@ pub(super) fn tx_size_context_txfm_rect(
3778 /// override above fired on the wrong neighbour -- the first divergence of the3342 /// override above fired on the wrong neighbour -- the first divergence of the
3779 /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,3343 /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
3780 /// at the intra block right of an inter one).3344 /// 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 {
3782 let has_above = mi_r > n.tile_row0_mi;3350 let has_above = mi_r > n.tile_row0_mi;
3783 let has_left = mi_c > n.tile_col0_mi;3351 let has_left = mi_c > n.tile_col0_mi;
3784 let mut above = usize::from(n.above_txfm[mi_c]) >= side;3352 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),
3821 };3389 };
3822 if band_above != (has_above && usize::from(above) != 0)3390 if band_above != (has_above && usize::from(above) != 0)
3823 || band_left != (has_left && usize::from(left) != 0)3391 || band_left != (has_left && usize::from(left) != 0)
3824- {3392+ {}
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- );
3843 }3393 }
3844 match (has_above, has_left) {3394 match (has_above, has_left) {
3845 (true, true) => usize::from(above) + usize::from(left),3395 (true, true) => usize::from(above) + usize::from(left),
@@ -3886,13 +3436,6 @@ pub(super) fn read_tx_size(
3886 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),3436 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
3887 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),3437 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
3888 };3438 };
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- }
3896 max_tx >> depth3439 max_tx >> depth
3897 }3440 }
3898 3441
@@ -3902,7 +3445,12 @@ pub(super) fn read_tx_size(
3902 /// the two neighbour terms (whether the transform last written above/left of3445 /// the two neighbour terms (whether the transform last written above/left of
3903 /// this unit is narrower/shorter than the unit itself).3446 /// this unit is narrower/shorter than the unit itself).
3904 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates3447 #[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 {
3906 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)3454 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
3907 }3455 }
3908 3456
@@ -3935,7 +3483,12 @@ pub(crate) fn txfm_partition_ctx_rect(
3935 /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the3483 /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
3936 /// resolved transform's own size.3484 /// resolved transform's own size.
3937 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates3485 #[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+) {
3939 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));3492 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
3940 }3493 }
3941 3494
@@ -4005,12 +3558,6 @@ pub(super) fn txfm_partition_update_rect(
4005 (tx_w, tx_h): (usize, usize),3558 (tx_w, tx_h): (usize, usize),
4006 (txb_w, txb_h): (usize, usize),3559 (txb_w, txb_h): (usize, usize),
4007 ) {3560 ) {
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- }
4014 for i in 0..txb_h / MI {3561 for i in 0..txb_h / MI {
4015 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {3562 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
4016 *cell = tx_h as u8;3563 *cell = tx_h as u8;
@@ -4034,11 +3581,6 @@ pub(super) fn set_txfm_ctxs(
4034 h_mi: usize,3581 h_mi: usize,
4035 skip_inter: bool,3582 skip_inter: bool,
4036 ) {3583 ) {
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- }
4042 let bw = if skip_inter { w_mi * MI } else { tx_px };3584 let bw = if skip_inter { w_mi * MI } else { tx_px };
4043 let bh = if skip_inter { h_mi * MI } else { tx_px };3585 let bh = if skip_inter { h_mi * MI } else { tx_px };
4044 for i in 0..w_mi {3586 for i in 0..w_mi {
@@ -4308,15 +3850,6 @@ pub(super) fn read_var_tx_size(
4308 tx_h,3850 tx_h,
4309 );3851 );
4310 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;3852 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- }
4320 if !split {3853 if !split {
4321 out.push((blk_row, blk_col, tx_w, tx_h));3854 out.push((blk_row, blk_col, tx_w, tx_h));
4322 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));3855 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 @@
1 //! 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.1 //! 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.
2 2
3-use archmage::SimdToken;
4 use super::*;3 use super::*;
4+use archmage::SimdToken;
5 5
6 /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.6 /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
7 fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {7 fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
@@ -463,12 +463,6 @@ pub(super) fn deblock_plane_span(
463 plane.true_height.min(ch),463 plane.true_height.min(ch),
464 plane.width,464 plane.width,
465 );465 );
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- }
472 // lane-perf8: both passes iterate the edge's OWN direction innermost, so466 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
473 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2467 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
474 // kernel. The swap is order-preserving: a filtered group overlaps only468 // kernel. The swap is order-preserving: a filtered group overlaps only
@@ -523,20 +517,20 @@ pub(super) fn deblock_plane_span(
523 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));517 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
524 if let Some((len, level)) = ps[0]518 if let Some((len, level)) = ps[0]
525 && ps.iter().all(|p| *p == ps[0])519 && ps.iter().all(|p| *p == ps[0])
526- && filter_edge16(520+ && filter_edge16(
527- mine,521+ mine,
528- (y0 - y_lo) * stride + x0,522+ (y0 - y_lo) * stride + x0,
529- stride,523+ stride,
530- true,524+ true,
531- len,525+ len,
532- level,526+ level,
533- lf.sharpness,527+ lf.sharpness,
534- fctx,528+ fctx,
535- )529+ )
536- {530+ {
537- y0 += 16;531+ y0 += 16;
538- continue;532+ continue;
539- }533+ }
540 for (k, p) in ps.iter().enumerate() {534 for (k, p) in ps.iter().enumerate() {
541 if let Some((len, level)) = *p {535 if let Some((len, level)) = *p {
542 filter_edge(536 filter_edge(
@@ -555,9 +549,6 @@ pub(super) fn deblock_plane_span(
555 continue;549 continue;
556 }550 }
557 if let Some((len, level)) = edge_params(&vctx, x0, y0) {551 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- }
561 filter_edge(552 filter_edge(
562 mine,553 mine,
563 (y0 - y_lo) * stride + x0,554 (y0 - y_lo) * stride + x0,
@@ -637,20 +628,20 @@ pub(super) fn deblock_plane_span(
637 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));628 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
638 if let Some((len, level)) = ps[0]629 if let Some((len, level)) = ps[0]
639 && ps.iter().all(|p| *p == ps[0])630 && ps.iter().all(|p| *p == ps[0])
640- && filter_edge16(631+ && filter_edge16(
641- px,632+ px,
642- (y0 - r_lo) * w + (x0 - x_lo),633+ (y0 - r_lo) * w + (x0 - x_lo),
643- w,634+ w,
644- false,635+ false,
645- len,636+ len,
646- level,637+ level,
647- lf.sharpness,638+ lf.sharpness,
648- fctx,639+ fctx,
649- )640+ )
650- {641+ {
651- x0 += 16;642+ x0 += 16;
652- continue;643+ continue;
653- }644+ }
654 for (k, p) in ps.iter().enumerate() {645 for (k, p) in ps.iter().enumerate() {
655 if let Some((len, level)) = *p {646 if let Some((len, level)) = *p {
656 filter_edge(647 filter_edge(
@@ -669,15 +660,6 @@ pub(super) fn deblock_plane_span(
669 continue;660 continue;
670 }661 }
671 if let Some((len, level)) = edge_params(&hctx, x0, y0) {662 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- }
681 filter_edge(663 filter_edge(
682 px,664 px,
683 (y0 - r_lo) * w + (x0 - x_lo),665 (y0 - r_lo) * w + (x0 - x_lo),
@@ -716,7 +698,8 @@ pub(super) fn deblock_plane_span(
716 /// every pool thread the decode ever created. One shared pool with a hard698 /// every pool thread the decode ever created. One shared pool with a hard
717 /// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how699 /// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
718 /// many threads cycle through it; anything over the cap is freed.700 /// 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());
720 703
721 /// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K704 /// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
722 /// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in705 /// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
@@ -877,7 +860,8 @@ pub(crate) fn arm_filter_replay() {
877 /// can hold the replay against the decode it stands in for860 /// can hold the replay against the decode it stands in for
878 /// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).861 /// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
879 #[cfg(test)]862 #[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);
881 865
882 #[cfg(test)]866 #[cfg(test)]
883 pub(crate) fn set_filter_replay_disabled(off: bool) {867 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(
435 plane: 0,435 plane: 0,
436 };436 };
437 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));437 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)));
439 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));438 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
440 let mut u = PlaneBuf {439 let mut u = PlaneBuf {
441 data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),440 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(
545 // lane-comppin r9: tile-entry range, the earliest point comparable544 // lane-comppin r9: tile-entry range, the earliest point comparable
546 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the545 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
547 // first ladder rung before any symbol (partition or otherwise) is read.546 // 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- }
555 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);547 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
556 y.set_tile_origin(548 y.set_tile_origin(
557 mi_col0 as usize * 4,549 mi_col0 as usize * 4,
@@ -1071,16 +1063,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1071 // instead of silently decoding as SPLIT and desyncing.1063 // instead of silently decoding as SPLIT and desyncing.
1072 let part64 = match (has_cols, has_rows) {1064 let part64 = match (has_cols, has_rows) {
1073 (true, true) => {1065 (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- }
1084 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);1066 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
1085 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be1067 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
1086 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`1068 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -1089,33 +1071,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1089 // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings1071 // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings
1090 // keep decoding because the helper is exact, not a heuristic. inter-frame 64x64 level; `p` is the symbol.1072 // keep decoding because the helper is exact, not a heuristic. inter-frame 64x64 level; `p` is the symbol.
1091 1073
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- }
1099 p1074 p
1100 }1075 }
1101 (true, false) => {1076 (true, false) => {
1102 // lane-golomb r1 (class `parsed-then-discarded`): the gathered1077 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
1103 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT1078 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
1104 // (libaom `ec_read_partition_impl`).1079 // (libaom `ec_read_partition_impl`).
1105- if crate::envflags::env_flag!("EC_TRACE_PART") {1080+ if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)) == 1 {
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- {
1119 PARTITION_SPLIT1081 PARTITION_SPLIT
1120 } else {1082 } else {
1121 PARTITION_HORZ1083 PARTITION_HORZ
@@ -1125,20 +1087,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1125 // lane-golomb r1 (class `parsed-then-discarded`): the gathered1087 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
1126 // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT1088 // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT
1127 // (libaom `ec_read_partition_impl`).1089 // (libaom `ec_read_partition_impl`).
1128- if bump_edge32_bit(1090+ if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)) == 1 {
1129- 4,
1130- dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)),
1131- ) == 1
1132- {
1133 PARTITION_SPLIT1091 PARTITION_SPLIT
1134 } else {1092 } else {
1135 PARTITION_VERT1093 PARTITION_VERT
1136 }1094 }
1137 }1095 }
1138- (false, false) => {1096+ (false, false) => PARTITION_SPLIT,
1139- bump_edge_both_cut(2);
1140- PARTITION_SPLIT
1141- }
1142 };1097 };
1143 // lane-av1unwritten r7: the symbol is RESOLVED (a full CDF1098 // lane-av1unwritten r7: the symbol is RESOLVED (a full CDF
1144 // read or an edge `gather`) and about to be dispatched, so the1099 // 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(
1205 PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_41160 PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4
1206 ) {1161 ) {
1207 // lane-av1unwritten r6: arm census.1162 // 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- );
1217 // lane-inter4 r1: the superblock-level rect + 1:4 pairs as1163 // lane-inter4 r1: the superblock-level rect + 1:4 pairs as
1218 // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 /1164 // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 /
1219 // 16x64 ones. Each piece keeps `side = SB` for every1165 // 16x64 ones. Each piece keeps `side = SB` for every
@@ -1267,9 +1213,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1267 bw,1213 bw,
1268 bh1214 bh
1269 );1215 );
1270- if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) {1216+ if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) {}
1271- bump_inter_edge_strip(if horz { 0 } else { 1 });
1272- }
1273 }1217 }
1274 continue;1218 continue;
1275 }1219 }
@@ -1402,14 +1346,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1402 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),1346 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
1403 );1347 );
1404 let part32 = if has_cols32 && has_rows32 {1348 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- }
1413 // lane-av1tilerows: this rung printed the RAW 32-grid1349 // lane-av1tilerows: this rung printed the RAW 32-grid
1414 // index (`r32`, `c32`) into its `mi_row=`/`mi_col=`1350 // index (`r32`, `c32`) into its `mi_row=`/`mi_col=`
1415 // fields — a factor of `BLOCK_MI` (8) off — while the1351 // fields — a factor of `BLOCK_MI` (8) off — while the
@@ -1420,23 +1356,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1420 // against libaom's per-level `EC_PART_VAL` dump, which1356 // against libaom's per-level `EC_PART_VAL` dump, which
1421 // is the only way to locate a partition-walk1357 // is the only way to locate a partition-walk
1422 // divergence. Behaviour-free: env-gated print only.1358 // 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- }
1432 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);1359 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- }
1440 p1360 p
1441 } else {1361 } else {
1442 match (has_cols32, has_rows32) {1362 match (has_cols32, has_rows32) {
@@ -1444,21 +1364,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1444 // lane-golomb r1 (class `parsed-then-discarded`): the gathered1364 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
1445 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT1365 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
1446 // (libaom `ec_read_partition_impl`).1366 // (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- }
1456 if {1367 if {
1457 let b = dec.symbol_fixed(&gather(1368 let b = dec.symbol_fixed(&gather(
1458 &cdfs.partition_w32[ctx32],1369 &cdfs.partition_w32[ctx32],
1459 VERT_ALIKE,1370 VERT_ALIKE,
1460 ));1371 ));
1461- bump_edge32(b.min(1));
1462 b1372 b
1463 } == 11373 } == 1
1464 {1374 {
@@ -1476,7 +1386,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1476 &cdfs.partition_w32[ctx32],1386 &cdfs.partition_w32[ctx32],
1477 HORZ_ALIKE,1387 HORZ_ALIKE,
1478 ));1388 ));
1479- bump_edge32(b.min(1));
1480 b1389 b
1481 } == 11390 } == 1
1482 {1391 {
@@ -1485,10 +1394,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1485 PARTITION_VERT1394 PARTITION_VERT
1486 }1395 }
1487 }1396 }
1488- _ => {1397+ _ => PARTITION_SPLIT,
1489- bump_edge_both_cut(1);
1490- PARTITION_SPLIT
1491- }
1492 }1398 }
1493 };1399 };
1494 // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or1400 // 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(
1571 // inter leaves through the very same loop the1477 // inter leaves through the very same loop the
1572 // straddling case has always used.1478 // straddling case has always used.
1573 let part16 = if has_cols16 && has_rows16 {1479 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- }
1583 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);1480 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- }
1592 p1481 p
1593 } else if !has_cols16 && !has_rows16 {1482 } else if !has_cols16 && !has_rows16 {
1594 // lane-edgeboth r1: both axes cut by the true1483 // lane-edgeboth r1: both axes cut by the true
@@ -1596,22 +1485,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1596 // forces PARTITION_SPLIT and reads NO symbol;1485 // forces PARTITION_SPLIT and reads NO symbol;
1597 // the leaf loop below already drops the1486 // the leaf loop below already drops the
1598 // out-of-frame quadrants.1487 // out-of-frame quadrants.
1599- bump_edge_both_cut(0);
1600 PARTITION_SPLIT1488 PARTITION_SPLIT
1601 } else {1489 } else {
1602 if has_cols16 {1490 if has_cols16 {
1603 // lane-golomb r1 (class `parsed-then-discarded`): the gathered1491 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
1604 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT1492 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
1605 // (libaom `ec_read_partition_impl`).1493 // (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- }
1615 if dec.symbol_fixed(&gather(1494 if dec.symbol_fixed(&gather(
1616 &cdfs.partition_w16[ctx16],1495 &cdfs.partition_w16[ctx16],
1617 VERT_ALIKE,1496 VERT_ALIKE,
@@ -1726,7 +1605,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1726 && (piece_mi.0 >= mi_rows as usize1605 && (piece_mi.0 >= mi_rows as usize
1727 || piece_mi.1 >= mi_cols as usize)1606 || piece_mi.1 >= mi_cols as usize)
1728 {1607 {
1729- bump_inter_edge_strip(if horz { 4 } else { 5 });
1730 break;1608 break;
1731 }1609 }
1732 decode_inter_block(1610 decode_inter_block(
@@ -1819,7 +1697,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
1819 // block_size_high >= 16, blockd.h) both hold1697 // block_size_high >= 16, blockd.h) both hold
1820 // and the leaf/strip decoders' own gates1698 // and the leaf/strip decoders' own gates
1821 // apply unchanged.1699 // apply unchanged.
1822- bump_ab16_inter(part16 - PARTITION_HORZ_A);
1823 let _vert_guard = if part16 == PARTITION_VERT_A1700 let _vert_guard = if part16 == PARTITION_VERT_A
1824 || part16 == PARTITION_VERT_B1701 || part16 == PARTITION_VERT_B
1825 {1702 {
@@ -2019,8 +1896,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2019 refpix1896 refpix
2020 .dims(rf)1897 .dims(rf)
2021 .is_some_and(|(w, _)| w != frame_width as usize)1898 .is_some_and(|(w, _)| w != frame_width as usize)
2022- }) {1899+ }) {}
2023- }
2024 let mut prev_leaves: Vec<(1900 let mut prev_leaves: Vec<(
2025 (usize, usize),1901 (usize, usize),
2026 bool,1902 bool,
@@ -2031,16 +1907,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2031 for (mr, mc) in leaf_positions {1907 for (mr, mc) in leaf_positions {
2032 let leaf_mi = (mr as usize, mc as usize);1908 let leaf_mi = (mr as usize, mc as usize);
2033 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);1909 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;
2044 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);1910 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
2045 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be1911 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
2046 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`1912 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -2050,13 +1916,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2050 // keep decoding because the helper is exact, not a heuristic. inter-frame 8x8 level.1916 // keep decoding because the helper is exact, not a heuristic. inter-frame 8x8 level.
2051 refuse_invalid_subsize((8, 8), part8, fctx)?;1917 refuse_invalid_subsize((8, 8), part8, fctx)?;
2052 1918
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- }
2060 if part8 == PARTITION_SPLIT {1919 if part8 == PARTITION_SPLIT {
2061 // lane-intersub8: four BLOCK_4X4 inter1920 // lane-intersub8: four BLOCK_4X4 inter
2062 // sub-blocks, chroma once per 8x8.1921 // sub-blocks, chroma once per 8x8.
@@ -2090,15 +1949,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2090 // lane-av1unwritten r6: arm census -- an1949 // lane-av1unwritten r6: arm census -- an
2091 // 8x8-level VERT selects BLOCK_4X8, which1950 // 8x8-level VERT selects BLOCK_4X8, which
2092 // is INVALID at 4:2:2.1951 // 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- );
2102 if part8 == PARTITION_VERT || part8 == PARTITION_HORZ {1952 if part8 == PARTITION_VERT || part8 == PARTITION_HORZ {
2103 // lane-intersub8 r3/r4/r5: two1953 // lane-intersub8 r3/r4/r5: two
2104 // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT)1954 // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT)
@@ -2440,9 +2290,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2440 (frame_width as usize, frame_height as usize),2290 (frame_width as usize, frame_height as usize),
2441 fctx,2291 fctx,
2442 )?;2292 )?;
2443- if !has_rows32 {2293+ if !has_rows32 {}
2444- bump_edge32(2);
2445- }
2446 // lane-golomb r2: at the frame edge only the first half of the2294 // lane-golomb r2: at the frame edge only the first half of the
2447 // strip is coded (libaom `decode_partition` guards the second2295 // strip is coded (libaom `decode_partition` guards the second
2448 // with the same has_rows32 test that made this partition non-square).2296 // 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(
2495 fctx,2343 fctx,
2496 )?;2344 )?;
2497 } else {2345 } else {
2498- bump_inter_edge_strip(2);
2499 }2346 }
2500 }2347 }
2501 PARTITION_VERT => {2348 PARTITION_VERT => {
@@ -2546,9 +2393,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
2546 (frame_width as usize, frame_height as usize),2393 (frame_width as usize, frame_height as usize),
2547 fctx,2394 fctx,
2548 )?;2395 )?;
2549- if !has_cols32 {2396+ if !has_cols32 {}
2550- bump_edge32(3);
2551- }
2552 // lane-golomb r2: at the frame edge only the first half of the2397 // lane-golomb r2: at the frame edge only the first half of the
2553 // strip is coded (libaom `decode_partition` guards the second2398 // strip is coded (libaom `decode_partition` guards the second
2554 // with the same has_cols32 test that made this partition non-square).2399 // 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(
2601 fctx,2446 fctx,
2602 )?;2447 )?;
2603 } else {2448 } else {
2604- bump_inter_edge_strip(3);
2605 }2449 }
2606 }2450 }
2607 PARTITION_HORZ_A => {2451 PARTITION_HORZ_A => {
@@ -3144,16 +2988,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3144 );2988 );
3145 }2989 }
3146 2990
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- }
3157 // lane-av1fwd: the encoder scores ~25 filter candidates against this2991 // lane-av1fwd: the encoder scores ~25 filter candidates against this
3158 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,2992 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
3159 // before either filter has touched it -- but only on the shape whose2993 // 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(
123 // Round 27: the per-read trace is the only instrument that reaches the inter123 // Round 27: the per-read trace is the only instrument that reaches the inter
124 // path (the coefficient rungs stop well before the frame-3 divergence),124 // path (the coefficient rungs stop well before the frame-3 divergence),
125 // so publish the phase and the block's mi for every read it makes.125 // 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);
128 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can126 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
129 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the127 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
130 // few 16-px-granular uses below.128 // few 16-px-granular uses below.
@@ -232,30 +230,12 @@ pub(super) fn decode_inter_block(
232 // bails per PLANE at `block_width < 8 || block_height < 8` -- on the230 // bails per PLANE at `block_width < 8 || block_height < 8` -- on the
233 // block's own dims, never on the square prediction buffer this reader231 // block's own dims, never on the square prediction buffer this reader
234 // allocates.232 // 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- }
238 233
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- }
248 let skip_mode_ctx =234 let skip_mode_ctx =
249 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);235 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
250 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read236 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
251 // MSAC tell so it can be diffed against an equivalent hook in libaom's237 // MSAC tell so it can be diffed against an equivalent hook in libaom's
252 // own `read_skip_mode`/`av1_get_skip_mode_context`.238 // 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- }
259 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before239 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
260 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.240 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
261 let (seg_mi_r, seg_mi_c) = (rmi, cmi);241 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
@@ -269,12 +249,6 @@ pub(super) fn decode_inter_block(
269 let comp_allowed = write_w.min(write_h) >= 8;249 let comp_allowed = write_w.min(write_h) >= 8;
270 let skip_mode =250 let skip_mode =
271 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;251 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- }
278 252
279 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);253 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
280 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;254 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
@@ -299,16 +273,6 @@ pub(super) fn decode_inter_block(
299 // chunk). An INTRA block at that size inside an inter frame takes the273 // chunk). An INTRA block at that size inside an inter frame takes the
300 // intra tail below, which still codes one whole-block chroma unit and one274 // intra tail below, which still codes one whole-block chroma unit and one
301 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.275 // `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- }
312 // lane-warp r5: see `reject_residual` -- a square-block decode of a276 // lane-warp r5: see `reject_residual` -- a square-block decode of a
313 // HORZ_B strip is symbol-exact only for `skip` (no residual, no277 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
314 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just278 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
@@ -328,26 +292,10 @@ pub(super) fn decode_inter_block(
328 && !rect_inter_residual_supported(write_w, write_h)292 && !rect_inter_residual_supported(write_w, write_h)
329 && (is_inter || (write_w == side && write_h == side))293 && (is_inter || (write_w == side && write_h == side))
330 {294 {
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- }
338 return Err(unsupported(295 return Err(unsupported(
339 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",296 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
340 ));297 ));
341 }298 }
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- }
351 299
352 let mode_for_tx;300 let mode_for_tx;
353 let uv_predict_mode;301 let uv_predict_mode;
@@ -407,12 +355,6 @@ pub(super) fn decode_inter_block(
407 uni: neighbours.left_ref1[rmi]355 uni: neighbours.left_ref1[rmi]
408 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),356 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
409 });357 });
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- }
416 let is_compound = skip_mode358 let is_compound = skip_mode
417 || (reference_select359 || (reference_select
418 // `is_comp_ref_allowed` (blockd.h:65) gates the360 // `is_comp_ref_allowed` (blockd.h:65) gates the
@@ -494,22 +436,6 @@ pub(super) fn decode_inter_block(
494 ),436 ),
495 fctx,437 fctx,
496 );438 );
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- }
513 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV439 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
514 // be non-TRANSLATION (IDENTITY counts) for the compound block's440 // be non-TRANSLATION (IDENTITY counts) for the compound block's
515 // interp-filter read to be suppressed.441 // interp-filter read to be suppressed.
@@ -545,10 +471,8 @@ pub(super) fn decode_inter_block(
545 // all, so its number was an upper bound dressed up as an471 // all, so its number was an upper bound dressed up as an
546 // engagement figure.472 // engagement figure.
547 if mi_row < mi_rows as usize / 2 {473 if mi_row < mi_rows as usize / 2 {
548- if is_globalmv {474+ if is_globalmv {}
549- }475+ if is_global_mv0 || is_global_mv1 {}
550- if is_global_mv0 || is_global_mv1 {
551- }
552 }476 }
553 // libaom `av1_init_warp_params` + `allow_warp`'s477 // libaom `av1_init_warp_params` + `allow_warp`'s
554 // `global_warp_allowed` branch, run once per reference for a478 // `global_warp_allowed` branch, run once per reference for a
@@ -658,17 +582,10 @@ pub(super) fn decode_inter_block(
658 && enable_masked_compound582 && enable_masked_compound
659 && is_any_masked_compound_used_here(write_w, write_h)583 && is_any_masked_compound_used_here(write_w, write_h)
660 {584 {
661- crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx");
662 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])585 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
663 } else {586 } else {
664 0587 0
665 };588 };
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- }
672 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a589 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
673 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)590 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
674 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set591 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
@@ -932,14 +849,7 @@ pub(super) fn decode_inter_block(
932 ref_order_hints[(ref0 - LAST_FRAME) as usize],849 ref_order_hints[(ref0 - LAST_FRAME) as usize],
933 ref_order_hints[(ref1 - LAST_FRAME) as usize],850 ref_order_hints[(ref1 - LAST_FRAME) as usize],
934 );851 );
935- crate::msac::SymbolDecoder::set_symr_cdf("compound_idx");
936 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);852 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- }
943 if idx == 1 {853 if idx == 1 {
944 (8, 8, 1u8)854 (8, 8, 1u8)
945 } else {855 } else {
@@ -955,16 +865,6 @@ pub(super) fn decode_inter_block(
955 (8, 8, 1u8)865 (8, 8, 1u8)
956 };866 };
957 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));867 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- }
968 868
969 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`869 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
970 // comes AFTER `read_compound_type` (the `comp_group_idx`/870 // comes AFTER `read_compound_type` (the `comp_group_idx`/
@@ -1377,7 +1277,23 @@ pub(super) fn decode_inter_block(
1377 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);1277 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
1378 let (sy, su, sv) = if pred_deferred(refpix) {1278 let (sy, su, sv) = if pred_deferred(refpix) {
1379 push_pred(build);1279 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+ )
1381 } else {1297 } else {
1382 let mut built: [Vec<u16>; 3] = Default::default();1298 let mut built: [Vec<u16>; 3] = Default::default();
1383 build(y, u, v, refpix, fctx, &mut built);1299 build(y, u, v, refpix, fctx, &mut built);
@@ -2120,14 +2036,6 @@ pub(super) fn decode_inter_block(
2120 neighbours.left_ref1[rmi],2036 neighbours.left_ref1[rmi],
2121 );2037 );
2122 ref_frame_for_lf = ref_frame;2038 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- }
2131 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own2039 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
2132 // stacked defects (lf_level ref/mode-delta forwarding, the2040 // stacked defects (lf_level ref/mode-delta forwarding, the
2133 // switchable_interp ref-frame ctx gate, and a film-grain synthesis2041 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
@@ -2192,7 +2100,6 @@ pub(super) fn decode_inter_block(
2192 // lane-interbis r1: which single-ref mode this block resolved to,2100 // lane-interbis r1: which single-ref mode this block resolved to,
2193 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for2101 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
2194 // the `EC_MODE_VAL` value ladder below.2102 // the `EC_MODE_VAL` value ladder below.
2195- let mut dbg_mode = 16u32;
2196 let (mv, is_new_mv) = if !not_new {2103 let (mv, is_new_mv) = if !not_new {
2197 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):2104 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
2198 // read at most two `drl_mode` bits, one per stack entry past the2105 // read at most two `drl_mode` bits, one per stack entry past the
@@ -2226,11 +2133,9 @@ pub(super) fn decode_inter_block(
2226 let mv = if !not_zero {2133 let mv = if !not_zero {
2227 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already2134 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
2228 // computed at this block's own position in `gm_table`.2135 // computed at this block's own position in `gm_table`.
2229- dbg_mode = 15;
2230 gm_table[(ref_frame - LAST_FRAME) as usize]2136 gm_table[(ref_frame - LAST_FRAME) as usize]
2231 } else {2137 } else {
2232 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;2138 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
2233- dbg_mode = if nearest { 13 } else { 14 };
2234 if nearest {2139 if nearest {
2235 stack.nearest_mv2140 stack.nearest_mv
2236 } else {2141 } else {
@@ -2252,21 +2157,6 @@ pub(super) fn decode_inter_block(
2252 };2157 };
2253 (mv, false)2158 (mv, false)
2254 };2159 };
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- }
2270 // lane-gm r2: the two libaom predicates single-ref GLOBALMV2160 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
2271 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode2161 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
2272 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating2162 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
@@ -2279,13 +2169,6 @@ pub(super) fn decode_inter_block(
2279 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;2169 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
2280 let gm_nontrans =2170 let gm_nontrans =
2281 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;2171 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- }
2289 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom2172 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
2290 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed2173 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
2291 // right after `assign_mv` and before `read_motion_mode` below --2174 // right after `assign_mv` and before `read_motion_mode` below --
@@ -2315,7 +2198,6 @@ pub(super) fn decode_inter_block(
2315 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip2198 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip
2316 // group 2, not their square `side`'s 2/3.2199 // group 2, not their square `side`'s 2/3.
2317 let bsize_group = size_group_wh(write_w, write_h);2200 let bsize_group = size_group_wh(write_w, write_h);
2318- crate::msac::SymbolDecoder::set_symr_cdf("interintra");
2319 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;2201 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
2320 if interintra {2202 if interintra {
2321 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,2203 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
@@ -2354,13 +2236,6 @@ pub(super) fn decode_inter_block(
2354 super::wave::finish_tile(fctx, refpix, [&mut *y, &mut *u, &mut *v]);2236 super::wave::finish_tile(fctx, refpix, [&mut *y, &mut *u, &mut *v]);
2355 }2237 }
2356 }2238 }
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- }
2364 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;2239 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
2365 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),2240 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
2366 // placed right after MV assignment and before the switchable2241 // placed right after MV assignment and before the switchable
@@ -2403,20 +2278,6 @@ pub(super) fn decode_inter_block(
2403 // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility2278 // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility
2404 // mismatch is otherwise invisible (a skipped symbol prints2279 // mismatch is otherwise invisible (a skipped symbol prints
2405 // nothing).2280 // 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- }
2420 let mut obmc_selected = false;2281 let mut obmc_selected = false;
2421 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL2282 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
2422 // *and* the local warp estimate is valid (`!wm_params.invalid`,2283 // *and* the local warp estimate is valid (`!wm_params.invalid`,
@@ -2485,7 +2346,6 @@ pub(super) fn decode_inter_block(
2485 let warp_eligible =2346 let warp_eligible =
2486 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;2347 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
2487 if warp_eligible {2348 if warp_eligible {
2488- crate::msac::SymbolDecoder::set_symr_cdf("motion_mode");
2489 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);2349 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
2490 match mode {2350 match mode {
2491 0 => {}2351 0 => {}
@@ -2505,18 +2365,6 @@ pub(super) fn decode_inter_block(
2505 ref_frame,2365 ref_frame,
2506 fctx,2366 fctx,
2507 );2367 );
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- }
2520 if samples.len() > 1 {2368 if samples.len() > 1 {
2521 crate::warp::select_samples(2369 crate::warp::select_samples(
2522 mv,2370 mv,
@@ -2537,21 +2385,6 @@ pub(super) fn decode_inter_block(
2537 mi_row as i32,2385 mi_row as i32,
2538 mi_col as i32,2386 mi_col as i32,
2539 );2387 );
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- }
2555 }2388 }
2556 }2389 }
2557 } else {2390 } else {
@@ -2561,18 +2394,6 @@ pub(super) fn decode_inter_block(
2561 // motion_mode vs 2-symbol obmc) and the range after -- the2394 // motion_mode vs 2-symbol obmc) and the range after -- the
2562 // two give the same value with a different narrowing (class2395 // two give the same value with a different narrowing (class
2563 // wrong-alphabet-same-value).2396 // 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- }
2576 }2397 }
2577 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch2398 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
2578 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --2399 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
@@ -2604,14 +2425,6 @@ pub(super) fn decode_inter_block(
2604 // (`warp::warp_round_0`, 5 at 12 bits) and the six-frame 12-bit2425 // (`warp::warp_round_0`, 5 at 12 bits) and the six-frame 12-bit
2605 // warp stream decodes byte-exact vs ffmpeg2426 // warp stream decodes byte-exact vs ffmpeg
2606 // (`a_12bit_warped_motion_stream_decodes_pixel_exact`).2427 // (`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- }
2615 // spec `get_ref_filter_type`: a neighbour's own filter only feeds2428 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
2616 // this block's switchable_interp context when that neighbour coded2429 // this block's switchable_interp context when that neighbour coded
2617 // the SAME reference frame this block is about to read -- a2430 // the SAME reference frame this block is about to read -- a
@@ -2649,26 +2462,6 @@ pub(super) fn decode_inter_block(
2649 );2462 );
2650 block_filter = resolved_filter;2463 block_filter = resolved_filter;
2651 globalmv_for_lf = is_globalmv;2464 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- }
2672 // lane-rect r2: see the compound path's matching comment above --2465 // lane-rect r2: see the compound path's matching comment above --
2673 // `grid` must be stamped with the block's true bh4/bw4 span, not2466 // `grid` must be stamped with the block's true bh4/bw4 span, not
2674 // a square `bw4`x`bw4` guess.2467 // a square `bw4`x`bw4` guess.
@@ -3076,7 +2869,23 @@ pub(super) fn decode_inter_block(
3076 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);2869 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
3077 let (sy, su, sv) = if pred_deferred(refpix) {2870 let (sy, su, sv) = if pred_deferred(refpix) {
3078 push_pred(build);2871 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+ )
3080 } else {2889 } else {
3081 let mut built: [Vec<u16>; 3] = Default::default();2890 let mut built: [Vec<u16>; 3] = Default::default();
3082 build(y, u, v, refpix, fctx, &mut built);2891 build(y, u, v, refpix, fctx, &mut built);
@@ -3241,9 +3050,7 @@ pub(super) fn decode_inter_block(
3241 // extent is the strip's own. Counted so a 4:4:4 1:4-strip3050 // extent is the strip's own. Counted so a 4:4:4 1:4-strip
3242 // gate can prove it exercised this route (a 4:2:0 stream3051 // gate can prove it exercised this route (a 4:2:0 stream
3243 // of the same content reads 0).3052 // of the same content reads 0).
3244- Some(_) if ss_x(fctx) == 0 => {3053+ Some(_) if ss_x(fctx) == 0 => around,
3245- around
3246- }
3247 Some(s) if s.has_chroma => {3054 Some(s) if s.has_chroma => {
3248 let (pw, ph) = if s.horz {3055 let (pw, ph) = if s.horz {
3249 if ss_y(fctx) == 0 { (16, 4) } else { (16, 8) }3056 if ss_y(fctx) == 0 { (16, 4) } else { (16, 8) }
@@ -3945,15 +3752,6 @@ pub(super) fn decode_inter_block(
3945 // equivalent post-content point (added at the matching call site)3752 // equivalent post-content point (added at the matching call site)
3946 // narrows the ladder to this block's own tail instead of the next3753 // narrows the ladder to this block's own tail instead of the next
3947 // block's partition read.3754 // 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- }
3957 // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH3755 // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH
3958 // strips (mirroring the intra `decode_rect4_16` path), and the even3756 // strips (mirroring the intra `decode_rect4_16` path), and the even
3959 // strip's own record wrote empty chroma state over those cells -- this3757 // 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(
160 // entry sets the same label from ITS `at`, which is a different block --160 // entry sets the same label from ITS `at`, which is a different block --
161 // publishing from here is what makes the EC_SYMR mi trustworthy on the161 // publishing from here is what makes the EC_SYMR mi trustworthy on the
162 // inter path, which is what round 22 got wrong by assuming it was not.162 // 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);
165 const LAST_FRAME: i8 = 1;163 const LAST_FRAME: i8 = 1;
166 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back164 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
167 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`165 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
@@ -261,14 +259,6 @@ pub(super) fn decode_inter_block8(
261 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,259 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
262 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder260 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
263 // diffs line for line against a real aomdec.261 // 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- }
272 262
273 let mode_for_tx;263 let mode_for_tx;
274 // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the264 // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the
@@ -379,18 +369,6 @@ pub(super) fn decode_inter_block8(
379 comp_stack.ref_mv_ctx,369 comp_stack.ref_mv_ctx,
380 )370 )
381 };371 };
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- }
394 let (mv0, mv1) = assign_compound_mv(372 let (mv0, mv1) = assign_compound_mv(
395 dec,373 dec,
396 cdfs,374 cdfs,
@@ -409,19 +387,6 @@ pub(super) fn decode_inter_block8(
409 // lane-inter8 r3: byte-format-identical to the oracle's387 // lane-inter8 r3: byte-format-identical to the oracle's
410 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder388 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
411 // diffs line for line against a real aomdec.389 // 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- }
425 390
426 // spec 5.11.25: same gating [`decode_inter_block`]'s own391 // spec 5.11.25: same gating [`decode_inter_block`]'s own
427 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid392 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
@@ -432,7 +397,6 @@ pub(super) fn decode_inter_block8(
432 && enable_masked_compound397 && enable_masked_compound
433 && is_any_masked_compound_used_here(SIDE, SIDE)398 && is_any_masked_compound_used_here(SIDE, SIDE)
434 {399 {
435- crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx");
436 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])400 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
437 } else {401 } else {
438 0402 0
@@ -485,7 +449,6 @@ pub(super) fn decode_inter_block8(
485 ref_order_hints[(ref0 - LAST_FRAME) as usize],449 ref_order_hints[(ref0 - LAST_FRAME) as usize],
486 ref_order_hints[(ref1 - LAST_FRAME) as usize],450 ref_order_hints[(ref1 - LAST_FRAME) as usize],
487 );451 );
488- crate::msac::SymbolDecoder::set_symr_cdf("compound_idx");
489 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);452 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
490 if idx == 1 {453 if idx == 1 {
491 (8, 8, 1u8)454 (8, 8, 1u8)
@@ -502,16 +465,6 @@ pub(super) fn decode_inter_block8(
502 (8, 8, 1u8)465 (8, 8, 1u8)
503 };466 };
504 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));467 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- }
515 468
516 // lane-interp3 r1: `read_mb_interp_filter` (libaom469 // lane-interp3 r1: `read_mb_interp_filter` (libaom
517 // `decodemv.c` 1575, the tail of470 // `decodemv.c` 1575, the tail of
@@ -981,7 +934,23 @@ pub(super) fn decode_inter_block8(
981 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);934 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
982 let (sy, su, sv) = if pred_deferred(refpix) {935 let (sy, su, sv) = if pred_deferred(refpix) {
983 push_pred(build);936 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+ )
985 } else {954 } else {
986 let mut built: [Vec<u16>; 3] = Default::default();955 let mut built: [Vec<u16>; 3] = Default::default();
987 build(y, u, v, refpix, fctx, &mut built);956 build(y, u, v, refpix, fctx, &mut built);
@@ -1380,14 +1349,6 @@ pub(super) fn decode_inter_block8(
1380 // lane-interp3 r2: same per-entry EC_STACK ladder1349 // lane-interp3 r2: same per-entry EC_STACK ladder
1381 // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack1350 // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack
1382 // diffs line for line against the oracle's.1351 // 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- }
1391 1352
1392 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;1353 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
1393 let mut is_globalmv = false;1354 let mut is_globalmv = false;
@@ -1448,7 +1409,6 @@ pub(super) fn decode_inter_block8(
1448 let mut interintra_mode: Option<u8> = None;1409 let mut interintra_mode: Option<u8> = None;
1449 let mut wedge_mask: Option<(&'static [u8], usize)> = None;1410 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
1450 if enable_interintra_compound && !skip_mode {1411 if enable_interintra_compound && !skip_mode {
1451- crate::msac::SymbolDecoder::set_symr_cdf("interintra");
1452 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;1412 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
1453 if interintra {1413 if interintra {
1454 // lane-interintra r1: same read pair as the 16/32 site;1414 // lane-interintra r1: same read pair as the 16/32 site;
@@ -1543,14 +1503,7 @@ pub(super) fn decode_inter_block8(
1543 let ref_is_scaled = !scale_of((ref_width, ref_height), frame_size).is_unscaled();1503 let ref_is_scaled = !scale_of((ref_width, ref_height), frame_size).is_unscaled();
1544 let warp_eligible =1504 let warp_eligible =
1545 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;1505 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- }
1552 if warp_eligible {1506 if warp_eligible {
1553- crate::msac::SymbolDecoder::set_symr_cdf("motion_mode");
1554 let mode = dec.symbol(&mut cdfs.motion_mode[0]);1507 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
1555 match mode {1508 match mode {
1556 0 => {}1509 0 => {}
@@ -1630,17 +1583,6 @@ pub(super) fn decode_inter_block8(
1630 false,1583 false,
1631 );1584 );
1632 leaf_filter_syms = resolved_filter;1585 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- }
1644 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch1586 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
1645 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --1587 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
1646 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model1588 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
@@ -1654,14 +1596,6 @@ pub(super) fn decode_inter_block8(
1654 // `warp_params` set here; the 12-bit refusal that stood here is1596 // `warp_params` set here; the 12-bit refusal that stood here is
1655 // lifted with the same witness (`warp::warp_round_0` moved the1597 // lifted with the same witness (`warp::warp_round_0` moved the
1656 // filter's shifts; the same stream decodes byte-exact vs ffmpeg).1598 // 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- }
1665 grid.fill_rect(1599 grid.fill_rect(
1666 mi_row,1600 mi_row,
1667 mi_col,1601 mi_col,
@@ -1901,7 +1835,23 @@ pub(super) fn decode_inter_block8(
1901 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);1835 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
1902 let (sy, su, sv) = if pred_deferred(refpix) {1836 let (sy, su, sv) = if pred_deferred(refpix) {
1903 push_pred(build);1837 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+ )
1905 } else {1855 } else {
1906 // The interintra predictor reads this block's own above/left1856 // The interintra predictor reads this block's own above/left
1907 // edges, which are already written at this point.1857 // edges, which are already written at this point.
@@ -2123,7 +2073,6 @@ pub(super) fn decode_inter_block8(
2123 }2073 }
2124 }2074 }
2125 } else {2075 } else {
2126- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
2127 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);2076 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
2128 if mode >= 13 {2077 if mode >= 13 {
2129 return Err(unsupported(2078 return Err(unsupported(
@@ -2172,21 +2121,10 @@ pub(super) fn decode_inter_block8(
2172 let uv_mode = if !has_chroma {2121 let uv_mode = if !has_chroma {
2173 DC_PRED2122 DC_PRED
2174 } else if cfl_allowed_px(SIDE, SIDE, fctx) {2123 } else if cfl_allowed_px(SIDE, SIDE, fctx) {
2175- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2176 dec.symbol(&mut cdfs.uv_mode_cfl[mode])2124 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2177 } else {2125 } else {
2178- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2179 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])2126 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2180 };2127 };
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- }
2190 let alpha = if has_chroma && uv_mode == UV_CFL_PRED {2128 let alpha = if has_chroma && uv_mode == UV_CFL_PRED {
2191 Some(read_cfl_alphas(dec, cdfs))2129 Some(read_cfl_alphas(dec, cdfs))
2192 } else {2130 } else {
@@ -2238,16 +2176,6 @@ pub(super) fn decode_inter_block8(
2238 let use_palette_uv = has_chroma2176 let use_palette_uv = has_chroma
2239 && uv_mode == DC_PRED2177 && uv_mode == DC_PRED
2240 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;2178 && 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- }
2251 if use_palette_uv {2179 if use_palette_uv {
2252 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);2180 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
2253 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);2181 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(
2267 // prints `use_filter_intra` for an intra block inside an INTER frame2195 // prints `use_filter_intra` for an intra block inside an INTER frame
2268 // and nothing else, so this leaf needs the same two lines for a2196 // and nothing else, so this leaf needs the same two lines for a
2269 // range-ladder diff against it.2197 // range-ladder diff against it.
2270- let ec_istep8 = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
2271 if mode == DC_PRED2198 if mode == DC_PRED
2272 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)2199 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
2273 // `av1_filter_intra_allowed` (reconintra.h:77) excludes a2200 // `av1_filter_intra_allowed` (reconintra.h:77) excludes a
@@ -2276,25 +2203,8 @@ pub(super) fn decode_inter_block8(
2276 && let Some(class) = filter_intra_size_class(SIDE)2203 && let Some(class) = filter_intra_size_class(SIDE)
2277 {2204 {
2278 let use_fi = dec.symbol(&mut cdfs.filter_intra[class]) != 0;2205 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- }
2288 if use_fi {2206 if use_fi {
2289 let fi = dec.symbol(&mut cdfs.filter_intra_mode);2207 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- }
2298 filter_intra = Some(fi);2208 filter_intra = Some(fi);
2299 }2209 }
2300 }2210 }
@@ -2448,10 +2358,6 @@ pub(super) fn decode_inter_block8(
2448 read_plane(2358 read_plane(
2449 dec,2359 dec,
2450 cdfs,2360 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).
2455 txbset_for(tx_px, reduced_tx_set),2361 txbset_for(tx_px, reduced_tx_set),
2456 default_scan(tx_px),2362 default_scan(tx_px),
2457 0,2363 0,
@@ -2467,7 +2373,6 @@ pub(super) fn decode_inter_block8(
2467 tu_py,2373 tu_py,
2468 tx_px,2374 tx_px,
2469 tx_px,2375 tx_px,
2470- base_q_idx,
2471 None,2376 None,
2472 filter_intra,2377 filter_intra,
2473 Some(tu_skip_ctx),2378 Some(tu_skip_ctx),
@@ -2566,14 +2471,6 @@ pub(super) fn decode_inter_block8(
2566 read_plane(2471 read_plane(
2567 dec,2472 dec,
2568 cdfs,2473 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`.
2577 txbset_for(8, reduced_tx_set),2474 txbset_for(8, reduced_tx_set),
2578 scan8,2475 scan8,
2579 0,2476 0,
@@ -2589,7 +2486,6 @@ pub(super) fn decode_inter_block8(
2589 py,2486 py,
2590 SIDE,2487 SIDE,
2591 TX8,2488 TX8,
2592- base_q_idx,
2593 None,2489 None,
2594 filter_intra,2490 filter_intra,
2595 None,2491 None,
@@ -2636,7 +2532,6 @@ pub(super) fn decode_inter_block8(
2636 cdfs,2532 cdfs,
2637 neighbours,2533 neighbours,
2638 leaf_mi,2534 leaf_mi,
2639- (px, py),
2640 (cpx, cpy),2535 (cpx, cpy),
2641 SIDE,2536 SIDE,
2642 (chroma_w, chroma_h),2537 (chroma_w, chroma_h),
@@ -2644,13 +2539,11 @@ pub(super) fn decode_inter_block8(
2644 (chroma_w, chroma_h),2539 (chroma_w, chroma_h),
2645 chroma_w,2540 chroma_w,
2646 reach,2541 reach,
2647- (y.width, y.height),
2648 mode,2542 mode,
2649 uv_predict_mode,2543 uv_predict_mode,
2650 angle_delta_uv,2544 angle_delta_uv,
2651 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),2545 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
2652 smooth_neighbor_uv,2546 smooth_neighbor_uv,
2653- base_q_idx,
2654 &mut uo,2547 &mut uo,
2655 &mut vo,2548 &mut vo,
2656 fctx,2549 fctx,
@@ -2713,7 +2606,6 @@ pub(super) fn decode_inter_block8(
2713 cpy,2606 cpy,
2714 chroma_w,2607 chroma_w,
2715 chroma_tx,2608 chroma_tx,
2716- base_q_idx,
2717 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),2609 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
2718 None,2610 None,
2719 None,2611 None,
@@ -2767,7 +2659,6 @@ pub(super) fn decode_inter_block8(
2767 cpy,2659 cpy,
2768 chroma_w,2660 chroma_w,
2769 chroma_tx,2661 chroma_tx,
2770- base_q_idx,
2771 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),2662 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
2772 None,2663 None,
2773 None,2664 None,
crates/ec-av1/src/decode/inter_ctx.rsmodified+5 -328
@@ -64,31 +64,13 @@ pub(super) fn resolve_interp_filter(
64 // `h_kind`/`v_kind` argument order, which is why this function returns64 // `h_kind`/`v_kind` argument order, which is why this function returns
65 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).65 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
66 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);66 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- }
73 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;67 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
74 let sym1 = if enable_dual_filter {68 let sym1 = if enable_dual_filter {
75 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);69 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- }
82 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u870 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
83 } else {71 } else {
84 sym072 sym0
85 };73 };
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- }
92 (74 (
93 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),75 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
94 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),76 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
@@ -293,13 +275,6 @@ pub(super) fn read_intrabc_dv(
293 true,275 true,
294 fctx,276 fctx,
295 );277 );
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- }
303 dv278 dv
304 }279 }
305 280
@@ -331,7 +306,6 @@ impl PlaneBuf<'_> {
331 &mut self,306 &mut self,
332 x: usize,307 x: usize,
333 y: usize,308 y: usize,
334- plane: usize,
335 side: usize,309 side: usize,
336 w: usize,310 w: usize,
337 h: usize,311 h: usize,
@@ -359,13 +333,6 @@ impl PlaneBuf<'_> {
359 // prediction is byte-identical to the oracle's and whose committed333 // prediction is byte-identical to the oracle's and whose committed
360 // samples are not can only be a DIFFERENT WRITE -- and this is the334 // samples are not can only be a DIFFERENT WRITE -- and this is the
361 // only write path with no rung of its own.335 // 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- }
369 // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the336 // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the
370 // oracle's rung of the same name (aomdec's337 // oracle's rung of the same name (aomdec's
371 // `dec_build_inter_predictor`). This is the ONE site every inter338 // `dec_build_inter_predictor`). This is the ONE site every inter
@@ -376,33 +343,6 @@ impl PlaneBuf<'_> {
376 // pictures, so a rung line alone is ambiguous, but a geometry whose343 // pictures, so a rung line alone is ambiguous, but a geometry whose
377 // samples differ by at most 1 is a unique match (any wrong pairing344 // samples differ by at most 1 is a unique match (any wrong pairing
378 // differs by tens).345 // 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- }
406 // lane-recoparse: an all-zero residual (60% of the units) is a plain346 // lane-recoparse: an all-zero residual (60% of the units) is a plain
407 // prediction copy -- the same arithmetic with `r == 0`, without347 // prediction copy -- the same arithmetic with `r == 0`, without
408 // reading `side * h` zeros out of [`ZERO_RESIDUAL`].348 // reading `side * h` zeros out of [`ZERO_RESIDUAL`].
@@ -412,9 +352,8 @@ impl PlaneBuf<'_> {
412 let dst = (y + row) * self.width + x;352 let dst = (y + row) * self.width + x;
413 let pred = &prediction[src..src + w];353 let pred = &prediction[src..src + w];
414 let out = &mut self.data.to_mut()[dst..dst + w];354 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) {
416 let v = i32::from(p).clamp(0, max) as u16;356 let v = i32::from(p).clamp(0, max) as u16;
417- pix_write("mc_copy", x, y, w, x + col, y + row, *o, v);
418 *o = v;357 *o = v;
419 }358 }
420 }359 }
@@ -427,9 +366,8 @@ impl PlaneBuf<'_> {
427 let pred = &prediction[src..src + w];366 let pred = &prediction[src..src + w];
428 let res = &residual[src..src + w];367 let res = &residual[src..src + w];
429 let out = &mut self.data.to_mut()[dst..dst + w];368 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) {
431 let v = (i32::from(p) + r).clamp(0, max) as u16;370 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);
433 *o = v;371 *o = v;
434 }372 }
435 }373 }
@@ -521,12 +459,6 @@ pub(super) fn read_inter_plane(
521 default_tx_type,459 default_tx_type,
522 None,460 None,
523 )?;461 )?;
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- }
530 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but462 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
531 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the463 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
532 // caller hands the 32-point `scan` there, and the coded corner goes into464 // caller hands the 32-point `scan` there, and the coded corner goes into
@@ -572,7 +504,6 @@ pub(super) fn read_intra_chroma_lossless(
572 cdfs: &mut Cdfs,504 cdfs: &mut Cdfs,
573 neighbours: &mut Neighbours,505 neighbours: &mut Neighbours,
574 at_mi: (usize, usize),506 at_mi: (usize, usize),
575- (px, py): (usize, usize),
576 (cpx, cpy): (usize, usize),507 (cpx, cpy): (usize, usize),
577 side: usize,508 side: usize,
578 (blk_w, blk_h): (usize, usize),509 (blk_w, blk_h): (usize, usize),
@@ -580,13 +511,11 @@ pub(super) fn read_intra_chroma_lossless(
580 (reg_w, reg_h): (usize, usize),511 (reg_w, reg_h): (usize, usize),
581 stride: usize,512 stride: usize,
582 reach: Reach,513 reach: Reach,
583- (frame_w, frame_h): (usize, usize),
584 mode: usize,514 mode: usize,
585 uv_predict_mode: usize,515 uv_predict_mode: usize,
586 angle_delta_uv: i32,516 angle_delta_uv: i32,
587 palette_uv_bufs: Option<(&[u16], &[u16])>,517 palette_uv_bufs: Option<(&[u16], &[u16])>,
588 smooth_neighbor_uv: bool,518 smooth_neighbor_uv: bool,
589- base_q_idx: u8,
590 u_out: &mut Vec<i32>,519 u_out: &mut Vec<i32>,
591 v_out: &mut Vec<i32>,520 v_out: &mut Vec<i32>,
592 fctx: &crate::decode::FrameCtx,521 fctx: &crate::decode::FrameCtx,
@@ -629,11 +558,6 @@ pub(super) fn read_intra_chroma_lossless(
629 4 << ss_x(fctx),558 4 << ss_x(fctx),
630 4 << ss_y(fctx),559 4 << ss_y(fctx),
631 reach,560 reach,
632- px,
633- py,
634- frame_w,
635- frame_h,
636- fctx,
637 );561 );
638 if let Some((ub, vb)) = palette_uv_bufs {562 if let Some((ub, vb)) = palette_uv_bufs {
639 let buf = if plane_idx == 1 { ub } else { vb };563 let buf = if plane_idx == 1 { ub } else { vb };
@@ -657,7 +581,6 @@ pub(super) fn read_intra_chroma_lossless(
657 cpy + oy,581 cpy + oy,
658 4,582 4,
659 4,583 4,
660- base_q_idx,
661 None,584 None,
662 None,585 None,
663 offset,586 offset,
@@ -778,7 +701,6 @@ pub(super) fn read_inter_chroma_lossless(
778 // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma701 // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma
779 // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin702 // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin
780 // the walk/unit totals exactly rather than as a floor on wrong output.703 // the walk/unit totals exactly rather than as a floor on wrong output.
781- let counted_128 = blk_w > 64 || blk_h > 64;
782 for plane_idx in 1..3 {704 for plane_idx in 1..3 {
783 for rr in 0..reg_h / 4 {705 for rr in 0..reg_h / 4 {
784 for cc in 0..reg_w / 4 {706 for cc in 0..reg_w / 4 {
@@ -1001,8 +923,7 @@ pub(super) fn read_single_ref(
1001 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }923 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
1002 }924 }
1003 };925 };
1004- if ref_frame != LAST_FRAME {926+ if ref_frame != LAST_FRAME {}
1005- }
1006 ref_frame927 ref_frame
1007 }928 }
1008 929
@@ -1042,9 +963,8 @@ pub(crate) struct RefPix<'p> {
1042 #[derive(Clone)]963 #[derive(Clone)]
1043 pub(crate) struct SharedRefs {964 pub(crate) struct SharedRefs {
1044 pub(crate) dims: [Option<(usize, usize)>; 8],965 pub(crate) dims: [Option<(usize, usize)>; 8],
1045- pub(crate) wait: std::sync::Arc<966+ pub(crate) wait:
1046- dyn Fn() -> Result<[Option<std::sync::Arc<Picture>>; 8]> + Send + Sync,967+ std::sync::Arc<dyn Fn() -> Result<[Option<std::sync::Arc<Picture>>; 8]> + Send + Sync>,
1047- >,
1048 }968 }
1049 969
1050 /// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait970 /// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait
@@ -1179,12 +1099,6 @@ impl<'p> RefPix<'p> {
1179 /// (lane-defer8).1099 /// (lane-defer8).
1180 pub(super) fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> {1100 pub(super) fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> {
1181 refpix.dims(ref_frame).ok_or_else(|| {1101 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- }
1188 // lane-hdrlossless: libaom errors on the same stream1102 // lane-hdrlossless: libaom errors on the same stream
1189 // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL)1103 // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL)
1190 // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame1104 // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame
@@ -1475,23 +1389,6 @@ pub(crate) fn has_overlappable_neighbour(
1475 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty()1389 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty()
1476 }1390 }
1477 1391
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-
1495 /// `av1_findSamples` (`mvref_common.c`), full port: the up to1392 /// `av1_findSamples` (`mvref_common.c`), full port: the up to
1496 /// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour1393 /// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
1497 /// samples (`record_samples`) that share this block's own single reference1394 /// samples (`record_samples`) that share this block's own single reference
@@ -1523,16 +1420,8 @@ pub(crate) fn find_samples(
1523 // motion_mode alphabet over the 2-symbol obmc one.1420 // motion_mode alphabet over the 2-symbol obmc one.
1524 // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on1421 // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on
1525 // every warp block; the flag itself is a process constant.1422 // 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}"));
1528 let single_ref_match = |info: &MiInfo| {1423 let single_ref_match = |info: &MiInfo| {
1529 let m = info.ref_frame == ref_frame && info.ref_frame1 == NO_REF1;1424 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- }
1536 m1425 m
1537 };1426 };
1538 let mut do_tl = true;1427 let mut do_tl = true;
@@ -1754,46 +1643,6 @@ pub(super) fn neighbour_filter(
1754 ))1643 ))
1755 }1644 }
1756 1645
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-
1797 /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh1646 /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
1798 /// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`1647 /// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
1799 /// under `av1_setup_build_prediction_by_{above,left}_pred`).1648 /// under `av1_setup_build_prediction_by_{above,left}_pred`).
@@ -2022,71 +1871,6 @@ fn obmc_blend_h(
2022 }1871 }
2023 }1872 }
2024 1873
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-
2090 /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts1874 /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
2091 /// the overlap strip against each bordering above/left inter neighbour's own1875 /// the overlap strip against each bordering above/left inter neighbour's own
2092 /// mv/ref/filter and blends it into this block's just-built single-reference1876 /// mv/ref/filter and blends it into this block's just-built single-reference
@@ -2192,23 +1976,7 @@ pub(crate) fn obmc_plan(
2192 // `av1_setup_build_prediction_by_above_pred` reads1976 // `av1_setup_build_prediction_by_above_pred` reads
2193 // `above_mbmi->interp_filters`).1977 // `above_mbmi->interp_filters`).
2194 let above_syms = above_filter.get(mi_col + src4).copied().unwrap_or([3; 2]);1978 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- );
2208 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;1979 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- );
2212 let nb_dims = ref_dims(nb.ref_frame, refpix)?;1980 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
2213 above.push(ObmcNb {1981 above.push(ObmcNb {
2214 off4,1982 off4,
@@ -2225,23 +1993,7 @@ pub(crate) fn obmc_plan(
2225 overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))1993 overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
2226 {1994 {
2227 let left_syms = left_filter.get(mi_row + src4).copied().unwrap_or([3; 2]);1995 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- );
2241 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;1996 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- );
2245 let nb_dims = ref_dims(nb.ref_frame, refpix)?;1997 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
2246 left.push(ObmcNb {1998 left.push(ObmcNb {
2247 off4,1999 off4,
@@ -2358,41 +2110,6 @@ pub(crate) fn obmc_run(
2358 // block, reused by every neighbour of the above and left passes.2110 // block, reused by every neighbour of the above and left passes.
2359 let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());2111 let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());
2360 2112
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- }
2396 for nb in &plan.above {2113 for nb in &plan.above {
2397 let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else {2114 let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else {
2398 return;2115 return;
@@ -2500,16 +2217,6 @@ pub(crate) fn obmc_run(
2500 &mut tmp_u,2217 &mut tmp_u,
2501 fctx,2218 fctx,
2502 );2219 );
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- }
2513 let ch = cbh.min((write_h >> ss_y(fctx)) - coy);2220 let ch = cbh.min((write_h >> ss_y(fctx)) - coy);
2514 obmc_blend_h(pred_u, chroma_stride, 0, coy, cbw, ch, &tmp_u);2221 obmc_blend_h(pred_u, chroma_stride, 0, coy, cbw, ch, &tmp_u);
2515 obmc_neighbour_pred(2222 obmc_neighbour_pred(
@@ -2528,13 +2235,6 @@ pub(crate) fn obmc_run(
2528 );2235 );
2529 obmc_blend_h(pred_v, chroma_stride, 0, coy, cbw, ch, &tmp_v);2236 obmc_blend_h(pred_v, chroma_stride, 0, coy, cbw, ch, &tmp_v);
2530 }2237 }
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- }
2538 }2238 }
2539 2239
2540 /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to2240 /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
@@ -2667,15 +2367,6 @@ pub(super) fn read_comp_mode(
2667 ) -> bool {2367 ) -> bool {
2668 let ctx = reference_mode_ctx(above, left);2368 let ctx = reference_mode_ctx(above, left);
2669 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;2369 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- }
2679 compound2370 compound
2680 }2371 }
2681 2372
@@ -2979,17 +2670,3 @@ thread_local! {
2979 /// chroma plane -- the non-vacuity bar for the assertion at that site.2670 /// chroma plane -- the non-vacuity bar for the assertion at that site.
2980 pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };2671 pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2981 }2672 }
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(
132 .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16)132 .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16)
133 .map(|s| (s.horz, s.has_chroma));133 .map(|s| (s.horz, s.has_chroma));
134 if write_w.min(write_h) < 8 && strip16.is_none() {134 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- }
154 return Err(unsupported(135 return Err(unsupported(
155 "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)",136 "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)",
156 ));137 ));
@@ -215,14 +196,7 @@ pub(super) fn decode_inter_block_intra_arm(
215 );196 );
216 return Ok(None);197 return Ok(None);
217 }198 }
218- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
219 let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]);199 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- }
226 if mode >= 13 {200 if mode >= 13 {
227 return Err(unsupported(201 return Err(unsupported(
228 "an intra mode this decoder does not code (round 2)",202 "an intra mode this decoder does not code (round 2)",
@@ -263,10 +237,8 @@ pub(super) fn decode_inter_block_intra_arm(
263 let uv_mode = if !has_chroma {237 let uv_mode = if !has_chroma {
264 DC_PRED238 DC_PRED
265 } else if cfl_allowed {239 } else if cfl_allowed {
266- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
267 dec.symbol(&mut cdfs.uv_mode_cfl[mode])240 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
268 } else {241 } else {
269- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
270 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])242 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
271 };243 };
272 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {244 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
@@ -322,24 +294,9 @@ pub(super) fn decode_inter_block_intra_arm(
322 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);294 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
323 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));295 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
324 }296 }
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- }
332 let use_palette_uv = has_chroma297 let use_palette_uv = has_chroma
333 && uv_mode == DC_PRED298 && uv_mode == DC_PRED
334 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;299 && 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- }
343 if use_palette_uv {300 if use_palette_uv {
344 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);301 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
345 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);302 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(
532 dec,489 dec,
533 cdfs,490 cdfs,
534 txbset_for(tx_px, reduced),491 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.
539 default_scan(tx_px.min(32)),492 default_scan(tx_px.min(32)),
540 0,493 0,
541 neighbours.around_mi(tu_mi, tx_px)[0],494 neighbours.around_mi(tu_mi, tx_px)[0],
@@ -550,7 +503,6 @@ pub(super) fn decode_inter_block_intra_arm(
550 tu_py,503 tu_py,
551 tx_px,504 tx_px,
552 tx_px.min(32),505 tx_px.min(32),
553- base_q_idx,
554 None,506 None,
555 filter_intra,507 filter_intra,
556 Some(tu_skip_ctx),508 Some(tu_skip_ctx),
@@ -619,32 +571,18 @@ pub(super) fn decode_inter_block_intra_arm(
619 cdfs,571 cdfs,
620 neighbours,572 neighbours,
621 at_mi,573 at_mi,
622- (px, py),
623 (cpx, cpy),574 (cpx, cpy),
624 side,575 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`).
636 (chroma_stride, chroma_buf_h),576 (chroma_stride, chroma_buf_h),
637 (cc * chunk_chroma_w, cr * chunk_chroma_h),577 (cc * chunk_chroma_w, cr * chunk_chroma_h),
638 (chunk_chroma_w, chunk_chroma_h),578 (chunk_chroma_w, chunk_chroma_h),
639 chroma_stride,579 chroma_stride,
640 reach,580 reach,
641- (y.width, y.height),
642 mode,581 mode,
643 uv_predict_mode,582 uv_predict_mode,
644 angle_delta_uv,583 angle_delta_uv,
645 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),584 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
646 smooth_neighbor_uv,585 smooth_neighbor_uv,
647- base_q_idx,
648 &mut u_units,586 &mut u_units,
649 &mut v_units,587 &mut v_units,
650 fctx,588 fctx,
@@ -696,11 +634,6 @@ pub(super) fn decode_inter_block_intra_arm(
696 cr * chunk_luma + ur * unit_luma_h,634 cr * chunk_luma + ur * unit_luma_h,
697 unit_luma_w,635 unit_luma_w,
698 reach,636 reach,
699- px,
700- py,
701- y.width,
702- y.height,
703- fctx,
704 );637 );
705 let cu_grid = if skip {638 let cu_grid = if skip {
706 push_intra(639 push_intra(
@@ -740,15 +673,8 @@ pub(super) fn decode_inter_block_intra_arm(
740 cu_y,673 cu_y,
741 cu_tx,674 cu_tx,
742 cu_tx,675 cu_tx,
743- base_q_idx,
744- // CfL is refused above 32x32
745- // (`is_cfl_allowed`), so never here.
746 None,676 None,
747 None,677 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).
752 Some(3),678 Some(3),
753 smooth_neighbor_uv,679 smooth_neighbor_uv,
754 fctx,680 fctx,
@@ -918,7 +844,6 @@ pub(super) fn decode_inter_block_intra_arm(
918 py,844 py,
919 side,845 side,
920 luma_tx,846 luma_tx,
921- base_q_idx,
922 None,847 None,
923 filter_intra,848 filter_intra,
924 None,849 None,
@@ -939,26 +864,18 @@ pub(super) fn decode_inter_block_intra_arm(
939 cdfs,864 cdfs,
940 neighbours,865 neighbours,
941 at_mi,866 at_mi,
942- (px, py),
943 (cpx, cpy),867 (cpx, cpy),
944 side,868 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.
950 (chroma_stride, chroma_buf_h),869 (chroma_stride, chroma_buf_h),
951 (0, 0),870 (0, 0),
952 (chroma_stride, chroma_buf_h),871 (chroma_stride, chroma_buf_h),
953 chroma_stride,872 chroma_stride,
954 reach,873 reach,
955- (y.width, y.height),
956 mode,874 mode,
957 uv_predict_mode,875 uv_predict_mode,
958 angle_delta_uv,876 angle_delta_uv,
959 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),877 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
960 smooth_neighbor_uv,878 smooth_neighbor_uv,
961- base_q_idx,
962 &mut uo,879 &mut uo,
963 &mut vo,880 &mut vo,
964 fctx,881 fctx,
@@ -1008,11 +925,6 @@ pub(super) fn decode_inter_block_intra_arm(
1008 cu_row * chroma_tx,925 cu_row * chroma_tx,
1009 chroma_tx,926 chroma_tx,
1010 reach,927 reach,
1011- px,
1012- py,
1013- y.width,
1014- y.height,
1015- fctx,
1016 );928 );
1017 let cu_grid = read_plane(929 let cu_grid = read_plane(
1018 dec,930 dec,
@@ -1032,9 +944,6 @@ pub(super) fn decode_inter_block_intra_arm(
1032 cpy + cu_row * chroma_tx,944 cpy + cu_row * chroma_tx,
1033 chroma_tx,945 chroma_tx,
1034 chroma_tx,946 chroma_tx,
1035- base_q_idx,
1036- // CfL is capped at 32x32 (`is_cfl_allowed`),
1037- // so a block this size never carries alpha.
1038 None,947 None,
1039 None,948 None,
1040 Some(3),949 Some(3),
@@ -1095,7 +1004,6 @@ pub(super) fn decode_inter_block_intra_arm(
1095 cpy,1004 cpy,
1096 chroma_side,1005 chroma_side,
1097 chroma_tx,1006 chroma_tx,
1098- base_q_idx,
1099 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1007 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1100 None,1008 None,
1101 None,1009 None,
@@ -1133,11 +1041,6 @@ pub(super) fn decode_inter_block_intra_arm(
1133 luma_span_x,1041 luma_span_x,
1134 luma_span_y,1042 luma_span_y,
1135 reach,1043 reach,
1136- px,
1137- py,
1138- y.width,
1139- y.height,
1140- fctx,
1141 );1044 );
1142 // The 4:2:2 plane block is `(chroma_w, chroma_h)` --1045 // The 4:2:2 plane block is `(chroma_w, chroma_h)` --
1143 // 32x64 -- but codes TWO stacked TX_32X32 units, so1046 // 32x64 -- but codes TWO stacked TX_32X32 units, so
@@ -1171,12 +1074,8 @@ pub(super) fn decode_inter_block_intra_arm(
1171 cpy + cu_row * cu_h,1074 cpy + cu_row * cu_h,
1172 cu_w,1075 cu_w,
1173 cu_w,1076 cu_w,
1174- base_q_idx,
1175 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1077 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1176 None,1078 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).
1180 Some(3),1079 Some(3),
1181 smooth_neighbor_uv,1080 smooth_neighbor_uv,
1182 fctx,1081 fctx,
@@ -1249,7 +1148,6 @@ pub(super) fn decode_inter_block_intra_arm(
1249 cpy,1148 cpy,
1250 chroma_side,1149 chroma_side,
1251 chroma_tx,1150 chroma_tx,
1252- base_q_idx,
1253 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1151 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1254 None,1152 None,
1255 None,1153 None,
@@ -1278,11 +1176,6 @@ pub(super) fn decode_inter_block_intra_arm(
1278 luma_span_x,1176 luma_span_x,
1279 luma_span_y,1177 luma_span_y,
1280 reach,1178 reach,
1281- px,
1282- py,
1283- y.width,
1284- y.height,
1285- fctx,
1286 );1179 );
1287 // The V twin of the U arm's per-unit window above.1180 // The V twin of the U arm's per-unit window above.
1288 if let Some((_, vb)) = &palette_uv_bufs {1181 if let Some((_, vb)) = &palette_uv_bufs {
@@ -1309,7 +1202,6 @@ pub(super) fn decode_inter_block_intra_arm(
1309 cpy + cu_row * cu_h,1202 cpy + cu_row * cu_h,
1310 cu_w,1203 cu_w,
1311 cu_w,1204 cu_w,
1312- base_q_idx,
1313 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1205 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1314 None,1206 None,
1315 Some(3),1207 Some(3),
crates/ec-av1/src/decode/inter_shapes.rsmodified+1 -26
@@ -81,11 +81,6 @@ pub(super) fn read_block_tx_size(
81 //81 //
82 // The RECT twin [`read_block_tx_size_rect`] has published on this arm82 // The RECT twin [`read_block_tx_size_rect`] has published on this arm
83 // since lane-av1lm444loss; only the square arm had the hole.83 // 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- };
89 // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the84 // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the
90 // write: this publish CHANGES at least one of the above-band cells it85 // write: this publish CHANGES at least one of the above-band cells it
91 // covers -- the cell did not already hold `pub_above`, so a later86 // covers -- the cell did not already hold `pub_above`, so a later
@@ -104,8 +99,6 @@ pub(super) fn read_block_tx_size(
104 // first-touch case. The count is still a decision (no reader, no99 // first-touch case. The count is still a decision (no reader, no
105 // intra-only frame, no unchanged column), so the gate keeps its teeth;100 // intra-only frame, no unchanged column), so the gate keeps its teeth;
106 // only the doc's stronger reading was wrong.101 // 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));
109 set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter);102 set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter);
110 return Ok((4, Some(leaves)));103 return Ok((4, Some(leaves)));
111 }104 }
@@ -251,6 +244,7 @@ pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
251 // these triples are what decides whether those refusals can fire at all. Bit244 // these triples are what decides whether those refusals can fire at all. Bit
252 // 31 is "a triple this table does not list", which is what makes the gate a245 // 31 is "a triple this table does not list", which is what makes the gate a
253 // census rather than a restatement of its own table.246 // census rather than a restatement of its own table.
247+#[cfg(test)]
254 pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [248 pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
255 (16, 16, 16),249 (16, 16, 16),
256 (32, 32, 32),250 (32, 32, 32),
@@ -383,9 +377,6 @@ pub(super) fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
383 // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and377 // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and
384 // for which no TX_4X32 exists -- that chroma is coded as a378 // for which no TX_4X32 exists -- that chroma is coded as a
385 // TX_8X32-chunked merge, not a 4-px unit.379 // 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- }
389 return Err(unsupported(380 return Err(unsupported(
390 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",381 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
391 ));382 ));
@@ -675,16 +666,6 @@ pub(super) fn read_block_tx_size_rect(
675 let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]);666 let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]);
676 let ctx = txfm_partition_ctx_rect(above_px, left_px, bw.max(bh), tx_w, tx_h);667 let ctx = txfm_partition_ctx_rect(above_px, left_px, bw.max(bh), tx_w, tx_h);
677 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;668 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- }
688 if !split {669 if !split {
689 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));670 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
690 return Ok(None);671 return Ok(None);
@@ -993,16 +974,10 @@ pub(super) fn read_inter_plane_rect(
993 skip_ctx,974 skip_ctx,
994 dc_sign_ctx(around.2),975 dc_sign_ctx(around.2),
995 default_tx_type,976 default_tx_type,
996- plane_idx,
997 )?977 )?
998 };978 };
999 let grid = extend_corner(corner, cw, ch, w, h);979 let grid = extend_corner(corner, cw, ch, w, h);
1000 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);980 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- }
1006 // `reconstruct_mc_rect` reads both buffers at the square prediction981 // `reconstruct_mc_rect` reads both buffers at the square prediction
1007 // stride, so the dense `w x h` residual is re-laid at that stride982 // stride, so the dense `w x h` residual is re-laid at that stride
1008 // (`TxParams::stride`) after the inverse transform.983 // (`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(
97 .map(|(picture, _)| picture)97 .map(|(picture, _)| picture)
98 }98 }
99 99
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-
116 /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec100 /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
117 /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from101 /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
118 /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults102 /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
@@ -252,38 +236,6 @@ thread_local! {
252 pub(crate) static SUB8_LOSSLESS_NO_VARTX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };236 pub(crate) static SUB8_LOSSLESS_NO_VARTX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
253 }237 }
254 238
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-
287 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.239 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
288 #[allow(clippy::too_many_arguments)]240 #[allow(clippy::too_many_arguments)]
289 pub(super) fn read_sb128_root(241 pub(super) fn read_sb128_root(
@@ -329,9 +281,6 @@ pub(super) fn read_sb128_root(
329 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);281 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
330 let part128 = if has_cols128 && has_rows128 {282 let part128 = if has_cols128 && has_rows128 {
331 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);283 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- }
335 p284 p
336 } else {285 } else {
337 match (has_cols128, has_rows128) {286 match (has_cols128, has_rows128) {
@@ -351,7 +300,6 @@ pub(super) fn read_sb128_root(
351 }300 }
352 _ => {301 _ => {
353 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));302 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
354- bump_edge_both_cut(3);
355 PARTITION_SPLIT303 PARTITION_SPLIT
356 }304 }
357 }305 }
@@ -376,8 +324,7 @@ pub(super) fn read_sb128_root(
376 // lane-sb128c r9: the four AB shapes at the 128 root -- one324 // lane-sb128c r9: the four AB shapes at the 128 root -- one
377 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile325 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
378 // paths below in libaom `decode_partition`'s own visit order.326 // paths below in libaom `decode_partition`'s own visit order.
379- p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {327+ p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {}
380- }
381 _ => {328 _ => {
382 return Err(unsupported(329 return Err(unsupported(
383 "a 128x128 superblock partition value outside the 8-symbol alphabet",330 "a 128x128 superblock partition value outside the 8-symbol alphabet",
@@ -481,7 +428,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
481 plane: 0,428 plane: 0,
482 };429 };
483 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));430 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)));
485 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));431 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
486 let mut u = PlaneBuf {432 let mut u = PlaneBuf {
487 data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),433 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(
582 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));528 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
583 fctx.quant_deltas.with(|c| c.set(deltas));529 fctx.quant_deltas.with(|c| c.set(deltas));
584 fctx.current_delta_lf.with(|c| c.set([0; 4]));530 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- }
592 let mut dec = SymbolDecoder::new(tile_bytes);531 let mut dec = SymbolDecoder::new(tile_bytes);
593 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets532 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets
594 // it codes every symbol against the tables it started with.533 // it codes every symbol against the tables it started with.
@@ -942,28 +881,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
942 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own881 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
943 // three-way write exactly.882 // three-way write exactly.
944 let part = if has_cols && has_rows {883 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- }
955 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);884 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- }
967 p885 p
968 } else {886 } else {
969 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as887 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
@@ -975,16 +893,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
975 // the first block of that row.893 // the first block of that row.
976 match (has_cols, has_rows) {894 match (has_cols, has_rows) {
977 (true, false) => {895 (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- );
985 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));896 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));
988 if b == 1 {897 if b == 1 {
989 PARTITION_SPLIT898 PARTITION_SPLIT
990 } else {899 } else {
@@ -992,26 +901,14 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
992 }901 }
993 }902 }
994 (false, true) => {903 (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- );
1002 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));904 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));
1005 if b == 1 {905 if b == 1 {
1006 PARTITION_SPLIT906 PARTITION_SPLIT
1007 } else {907 } else {
1008 PARTITION_VERT908 PARTITION_VERT
1009 }909 }
1010 }910 }
1011- _ => {911+ _ => PARTITION_SPLIT,
1012- bump_edge_both_cut(2);
1013- PARTITION_SPLIT
1014- }
1015 }912 }
1016 };913 };
1017 // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or914 // 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(
1065 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),962 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
1066 );963 );
1067 let part32 = if has_cols32 && has_rows32 {964 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- }
1078 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);965 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- }
1095 p966 p
1096 } else {967 } else {
1097 // lane-hgkf r1: the 32-level frame-edge bit is the968 // lane-hgkf r1: the 32-level frame-edge bit is the
@@ -1099,19 +970,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1099 // superblock level above).970 // superblock level above).
1100 match (has_cols32, has_rows32) {971 match (has_cols32, has_rows32) {
1101 (true, false) => {972 (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- );
1109 let b = dec.symbol_fixed(&gather(973 let b = dec.symbol_fixed(&gather(
1110 &cdfs.partition_w32[ctx32],974 &cdfs.partition_w32[ctx32],
1111 VERT_ALIKE,975 VERT_ALIKE,
1112 ));976 ));
1113- bump_edge32(b.min(1));
1114- bump_edge_part(2 + b.min(1));
1115 if b == 1 {977 if b == 1 {
1116 PARTITION_SPLIT978 PARTITION_SPLIT
1117 } else {979 } else {
@@ -1119,29 +981,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1119 }981 }
1120 }982 }
1121 (false, true) => {983 (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- );
1129 let b = dec.symbol_fixed(&gather(984 let b = dec.symbol_fixed(&gather(
1130 &cdfs.partition_w32[ctx32],985 &cdfs.partition_w32[ctx32],
1131 HORZ_ALIKE,986 HORZ_ALIKE,
1132 ));987 ));
1133- bump_edge32(b.min(1));
1134- bump_edge_part(2 + b.min(1));
1135 if b == 1 {988 if b == 1 {
1136 PARTITION_SPLIT989 PARTITION_SPLIT
1137 } else {990 } else {
1138 PARTITION_VERT991 PARTITION_VERT
1139 }992 }
1140 }993 }
1141- _ => {994+ _ => PARTITION_SPLIT,
1142- bump_edge_both_cut(1);
1143- PARTITION_SPLIT
1144- }
1145 }995 }
1146 };996 };
1147 // lane-av1unwritten r4: VERT on a 32x32 block selects997 // lane-av1unwritten r4: VERT on a 32x32 block selects
@@ -1198,16 +1048,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1198 let at16 = (sr, sc);1048 let at16 = (sr, sc);
1199 let ctx16 = neighbours.partition_ctx(at16, SUB);1049 let ctx16 = neighbours.partition_ctx(at16, SUB);
1200 if has_cols16 && has_rows16 {1050 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- }
1211 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);1051 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
1212 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be1052 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
1213 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`1053 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -1217,21 +1057,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1217 // keep decoding because the helper is exact, not a heuristic. key-frame 16x16 level.1057 // keep decoding because the helper is exact, not a heuristic. key-frame 16x16 level.
1218 refuse_invalid_subsize((16, 16), part16, fctx)?;1058 refuse_invalid_subsize((16, 16), part16, fctx)?;
1219 1059
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- }
1235 if part16 == PARTITION_HORZ || part16 == PARTITION_VERT1060 if part16 == PARTITION_HORZ || part16 == PARTITION_VERT
1236 {1061 {
1237 let (bw, bh) = if part16 == PARTITION_HORZ {1062 let (bw, bh) = if part16 == PARTITION_HORZ {
@@ -1303,8 +1128,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1303 // rectangle: libaom switches those squares onto `has_tr_vert_*`/1128 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
1304 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is1129 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
1305 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).1130 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
1306- let arm = part16 - PARTITION_HORZ_A;
1307- bump_ab16(arm);
1308 let _vert_guard = if part16 == PARTITION_VERT_A1131 let _vert_guard = if part16 == PARTITION_VERT_A
1309 || part16 == PARTITION_VERT_B1132 || part16 == PARTITION_VERT_B
1310 {1133 {
@@ -1327,7 +1150,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1327 &mut y,1150 &mut y,
1328 &mut u,1151 &mut u,
1329 &mut v,1152 &mut v,
1330- base_q_idx,
1331 enable_filter_intra,1153 enable_filter_intra,
1332 allow_screen_content_tools,1154 allow_screen_content_tools,
1333 allow_intrabc,1155 allow_intrabc,
@@ -1522,15 +1344,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1522 {1344 {
1523 // lane-av1unwritten r6: arm census --1345 // lane-av1unwritten r6: arm census --
1524 // which partition values reach here.1346 // 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- );
1534 decode_rect4_16(1347 decode_rect4_16(
1535 &mut dec,1348 &mut dec,
1536 &mut cdfs,1349 &mut cdfs,
@@ -1603,16 +1416,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1603 }1416 }
1604 let leaf_ctx =1417 let leaf_ctx =
1605 neighbours.partition_ctx_mi(leaf_mi, 8);1418 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- }
1616 let part8 =1419 let part8 =
1617 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);1420 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
1618 // lane-av1unwritten r9: the1421 // lane-av1unwritten r9: the
@@ -1621,17 +1424,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1621 // r9 made sensitive to a second1424 // r9 made sensitive to a second
1622 // site at an already covered level.1425 // site at an already covered level.
1623 refuse_invalid_subsize((8, 8), part8, fctx)?;1426 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- }
1635 if part8 == PARTITION_HORZ1427 if part8 == PARTITION_HORZ
1636 || part8 == PARTITION_VERT1428 || part8 == PARTITION_VERT
1637 {1429 {
@@ -1665,7 +1457,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1665 &mut y,1457 &mut y,
1666 &mut u,1458 &mut u,
1667 &mut v,1459 &mut v,
1668- base_q_idx,
1669 enable_filter_intra,1460 enable_filter_intra,
1670 allow_screen_content_tools,1461 allow_screen_content_tools,
1671 allow_intrabc,1462 allow_intrabc,
@@ -1686,7 +1477,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1686 &mut y,1477 &mut y,
1687 &mut u,1478 &mut u,
1688 &mut v,1479 &mut v,
1689- base_q_idx,
1690 enable_filter_intra,1480 enable_filter_intra,
1691 allow_intrabc,1481 allow_intrabc,
1692 reduced_tx_set,1482 reduced_tx_set,
@@ -1706,7 +1496,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1706 &mut y,1496 &mut y,
1707 &mut u,1497 &mut u,
1708 &mut v,1498 &mut v,
1709- base_q_idx,
1710 enable_filter_intra,1499 enable_filter_intra,
1711 allow_intrabc,1500 allow_intrabc,
1712 tx_select,1501 tx_select,
@@ -1755,7 +1544,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1755 // quadrants get no neighbour or tx-grid1544 // quadrants get no neighbour or tx-grid
1756 // write.1545 // write.
1757 if !has_cols16 && !has_rows16 {1546 if !has_cols16 && !has_rows16 {
1758- bump_edge_both_cut(0);
1759 } else {1547 } else {
1760 // lane-golomb r1 (class1548 // lane-golomb r1 (class
1761 // `parsed-then-discarded`): the gathered1549 // `parsed-then-discarded`): the gathered
@@ -1765,13 +1553,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1765 // This path can only walk the four SPLIT1553 // This path can only walk the four SPLIT
1766 // leaves, so a 0 refuses by name instead1554 // leaves, so a 0 refuses by name instead
1767 // of desyncing.1555 // 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- );
1775 let edge_split = if has_cols16 {1556 let edge_split = if has_cols16 {
1776 dec.symbol_fixed(&gather(1557 dec.symbol_fixed(&gather(
1777 &cdfs.partition_w16[ctx16],1558 &cdfs.partition_w16[ctx16],
@@ -1786,7 +1567,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1786 // lane-hgkf r1: slots 2/3 of1567 // lane-hgkf r1: slots 2/3 of
1787 // [`EDGE_PART_HITS`], the gate's proof the1568 // [`EDGE_PART_HITS`], the gate's proof the
1788 // non-SPLIT edge arm actually decoded.1569 // non-SPLIT edge arm actually decoded.
1789- bump_edge_part(if edge_split == 1 { 3 } else { 2 });
1790 if edge_split == 0 {1570 if edge_split == 0 {
1791 // lane-av1subsizesweep: this arm is the ONE1571 // lane-av1subsizesweep: this arm is the ONE
1792 // frame-edge partition read in the file that1572 // frame-edge partition read in the file that
@@ -1826,17 +1606,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1826 refuse_invalid_subsize((16, 16), edge_part, fctx)?;1606 refuse_invalid_subsize((16, 16), edge_part, fctx)?;
1827 // lane-av1unwritten r6: arm census -- which1607 // lane-av1unwritten r6: arm census -- which
1828 // partition value reaches here.1608 // 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- );
1840 let (mi_row0, mi_col0) =1609 let (mi_row0, mi_col0) =
1841 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);1610 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
1842 let (bw, bh) =1611 let (bw, bh) =
@@ -1893,7 +1662,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1893 neighbours.left_mode[sr] = right;1662 neighbours.left_mode[sr] = right;
1894 }1663 }
1895 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);1664 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1896- let pre8 = dec.debug_state().0;
1897 let part8 =1665 let part8 =
1898 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);1666 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
1899 // lane-av1unwritten r9: key-frame 8x81667 // lane-av1unwritten r9: key-frame 8x8
@@ -1907,11 +1675,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1907 // than live pixels, and it is guarded1675 // than live pixels, and it is guarded
1908 // anyway.1676 // anyway.
1909 refuse_invalid_subsize((8, 8), part8, fctx)?;1677 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- }
1915 let leaf_mode = if part8 == PARTITION_NONE {1678 let leaf_mode = if part8 == PARTITION_NONE {
1916 decode_leaf8(1679 decode_leaf8(
1917 &mut dec,1680 &mut dec,
@@ -1924,7 +1687,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1924 &mut y,1687 &mut y,
1925 &mut u,1688 &mut u,
1926 &mut v,1689 &mut v,
1927- base_q_idx,
1928 enable_filter_intra,1690 enable_filter_intra,
1929 allow_screen_content_tools,1691 allow_screen_content_tools,
1930 allow_intrabc,1692 allow_intrabc,
@@ -1945,7 +1707,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1945 &mut y,1707 &mut y,
1946 &mut u,1708 &mut u,
1947 &mut v,1709 &mut v,
1948- base_q_idx,
1949 enable_filter_intra,1710 enable_filter_intra,
1950 allow_intrabc,1711 allow_intrabc,
1951 reduced_tx_set,1712 reduced_tx_set,
@@ -1965,7 +1726,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1965 &mut y,1726 &mut y,
1966 &mut u,1727 &mut u,
1967 &mut v,1728 &mut v,
1968- base_q_idx,
1969 enable_filter_intra,1729 enable_filter_intra,
1970 allow_intrabc,1730 allow_intrabc,
1971 tx_select,1731 tx_select,
@@ -2018,9 +1778,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2018 reduced_tx_set,1778 reduced_tx_set,
2019 fctx,1779 fctx,
2020 )?;1780 )?;
2021- if !has_rows32 {1781+ if !has_rows32 {}
2022- bump_edge32(2);
2023- }
2024 // lane-hgkf r1: at the frame edge only the first half of the strip is1782 // lane-hgkf r1: at the frame edge only the first half of the strip is
2025 // coded (libaom `decode_partition` guards the second half with the same1783 // coded (libaom `decode_partition` guards the second half with the same
2026 // test that made this partition non-square).1784 // test that made this partition non-square).
@@ -2064,9 +1822,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2064 reduced_tx_set,1822 reduced_tx_set,
2065 fctx,1823 fctx,
2066 )?;1824 )?;
2067- if !has_cols32 {1825+ if !has_cols32 {}
2068- bump_edge32(3);
2069- }
2070 // lane-hgkf r1: at the frame edge only the first half of the strip is1826 // lane-hgkf r1: at the frame edge only the first half of the strip is
2071 // coded (libaom `decode_partition` guards the second half with the same1827 // coded (libaom `decode_partition` guards the second half with the same
2072 // test that made this partition non-square).1828 // test that made this partition non-square).
@@ -2453,9 +2209,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
2453 reduced_tx_set,2209 reduced_tx_set,
2454 fctx,2210 fctx,
2455 )?;2211 )?;
2456- if !has_rows {2212+ if !has_rows {}
2457- bump_edge32(6);
2458- }
2459 // lane-golomb r1: at the frame edge only the first half of the2213 // lane-golomb r1: at the frame edge only the first half of the
2460 // strip is coded (libaom `decode_partition` guards the second2214 // strip is coded (libaom `decode_partition` guards the second
2461 // with the same has_rows test that made this partition non-square).2215 // 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(
2499 reduced_tx_set,2253 reduced_tx_set,
2500 fctx,2254 fctx,
2501 )?;2255 )?;
2502- if !has_cols {2256+ if !has_cols {}
2503- bump_edge32(7);
2504- }
2505 // lane-golomb r1: at the frame edge only the first half of the2257 // lane-golomb r1: at the frame edge only the first half of the
2506 // strip is coded (libaom `decode_partition` guards the second2258 // strip is coded (libaom `decode_partition` guards the second
2507 // with the same has_cols test that made this partition non-square).2259 // 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(
2675 }2427 }
2676 crate::timeline::recon_done();2428 crate::timeline::recon_done();
2677 2429
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- }
2688 // lane-av1fwd: the encoder's filter search re-decodes this same key2430 // lane-av1fwd: the encoder's filter search re-decodes this same key
2689 // frame tile per candidate -- capture it once (see [`FilterReplay`]),2431 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
2690 // on the shape whose tail is the two filter calls and nothing else.2432 // 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(
140 // lane-inter128intra r1: `get_tx_size_context` compares the bands140 // lane-inter128intra r1: `get_tx_size_context` compares the bands
141 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --141 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
142 // TX_64X64 for every 128-axis block, hence the `min(64)`.142 // 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));
144 dec.symbol(&mut cdfs.tx_size_cat3[ctx])144 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
145 } else {145 } else {
146 0146 0
@@ -223,11 +223,6 @@ pub(super) fn decode_block_128rect(
223 tu_row * logical_tx,223 tu_row * logical_tx,
224 logical_tx,224 logical_tx,
225 reach,225 reach,
226- px,
227- py,
228- y.width,
229- y.height,
230- fctx,
231 );226 );
232 if skip {227 if skip {
233 push_intra(228 push_intra(
@@ -272,7 +267,6 @@ pub(super) fn decode_block_128rect(
272 tu_py,267 tu_py,
273 logical_tx,268 logical_tx,
274 coeff_tx_side,269 coeff_tx_side,
275- base_q_idx,
276 None,270 None,
277 None,271 None,
278 Some(tu_skip_ctx),272 Some(tu_skip_ctx),
@@ -325,11 +319,6 @@ pub(super) fn decode_block_128rect(
325 luma_span,319 luma_span,
326 luma_span_h,320 luma_span_h,
327 reach,321 reach,
328- px,
329- py,
330- y.width,
331- y.height,
332- fctx,
333 );322 );
334 if skip {323 if skip {
335 push_intra(324 push_intra(
@@ -386,7 +375,6 @@ pub(super) fn decode_block_128rect(
386 cu_y,375 cu_y,
387 chroma_tx,376 chroma_tx,
388 chroma_tx,377 chroma_tx,
389- base_q_idx,
390 None,378 None,
391 None,379 None,
392 Some(3),380 Some(3),
@@ -531,7 +519,6 @@ pub(super) fn decode_leaf8(
531 y: &mut PlaneBuf<'static>,519 y: &mut PlaneBuf<'static>,
532 u: &mut PlaneBuf<'static>,520 u: &mut PlaneBuf<'static>,
533 v: &mut PlaneBuf<'static>,521 v: &mut PlaneBuf<'static>,
534- base_q_idx: u8,
535 enable_filter_intra: bool,522 enable_filter_intra: bool,
536 allow_screen_content_tools: bool,523 allow_screen_content_tools: bool,
537 allow_intrabc: bool,524 allow_intrabc: bool,
@@ -810,19 +797,7 @@ pub(super) fn decode_leaf8(
810 if tu_px >= y.true_width || tu_py >= y.true_height {797 if tu_px >= y.true_width || tu_py >= y.true_height {
811 continue;798 continue;
812 }799 }
813- let tu_reach = tu_reach(800+ let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, 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- );
826 push_intra(801 push_intra(
827 y,802 y,
828 u,803 u,
@@ -946,19 +921,7 @@ pub(super) fn decode_leaf8(
946 if chroma_units_ll {921 if chroma_units_ll {
947 for cu_row in 0..cu_shape.1 / 4 {922 for cu_row in 0..cu_shape.1 / 4 {
948 for cu_col in 0..cu_shape.0 / 4 {923 for cu_col in 0..cu_shape.0 / 4 {
949- let cu_reach = tu_reach(924+ let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, 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- );
962 push_intra(925 push_intra(
963 y,926 y,
964 u,927 u,
@@ -1005,19 +968,7 @@ pub(super) fn decode_leaf8(
1005 for (buf, plane) in [(ub, 1usize), (vb, 2usize)] {968 for (buf, plane) in [(ub, 1usize), (vb, 2usize)] {
1006 if let Some(buf) = buf {969 if let Some(buf) = buf {
1007 for cu_row in 0..2 {970 for cu_row in 0..2 {
1008- let cu_reach = tu_reach(971+ let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, 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- );
1021 set_palette_pred(972 set_palette_pred(
1022 palette_window(&buf, cw, 0, cu_row * 4, 4, 4),973 palette_window(&buf, cw, 0, cu_row * 4, 4, 4),
1023 fctx,974 fctx,
@@ -1070,19 +1021,7 @@ pub(super) fn decode_leaf8(
1070 if chroma_units_ll {1021 if chroma_units_ll {
1071 for cu_row in 0..cu_shape.1 / 4 {1022 for cu_row in 0..cu_shape.1 / 4 {
1072 for cu_col in 0..cu_shape.0 / 4 {1023 for cu_col in 0..cu_shape.0 / 4 {
1073- let cu_reach = tu_reach(1024+ let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, 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- );
1086 push_intra(1025 push_intra(
1087 y,1026 y,
1088 u,1027 u,
@@ -1115,19 +1054,7 @@ pub(super) fn decode_leaf8(
1115 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone()));1054 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone()));
1116 if let Some(vb) = vb {1055 if let Some(vb) = vb {
1117 for cu_row in 0..2 {1056 for cu_row in 0..2 {
1118- let cu_reach = tu_reach(1057+ let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, 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- );
1131 set_palette_pred(palette_window(&vb, cw, 0, cu_row * 4, 4, 4), fctx);1058 set_palette_pred(palette_window(&vb, cw, 0, cu_row * 4, 4, 4), fctx);
1132 push_intra(1059 push_intra(
1133 y,1060 y,
@@ -1214,7 +1141,6 @@ pub(super) fn decode_leaf8(
1214 py,1141 py,
1215 8,1142 8,
1216 TX8,1143 TX8,
1217- base_q_idx,
1218 None,1144 None,
1219 filter_intra,1145 filter_intra,
1220 None,1146 None,
@@ -1301,7 +1227,6 @@ pub(super) fn decode_leaf8(
1301 cpy,1227 cpy,
1302 csz,1228 csz,
1303 csz,1229 csz,
1304- base_q_idx,
1305 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1230 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1306 None,1231 None,
1307 None,1232 None,
@@ -1331,7 +1256,6 @@ pub(super) fn decode_leaf8(
1331 cpy,1256 cpy,
1332 csz,1257 csz,
1333 csz,1258 csz,
1334- base_q_idx,
1335 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1259 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1336 None,1260 None,
1337 None,1261 None,
@@ -1357,19 +1281,7 @@ pub(super) fn decode_leaf8(
1357 let tu_px = px + tu_col * 4;1281 let tu_px = px + tu_col * 4;
1358 let tu_py = py + tu_row * 4;1282 let tu_py = py + tu_row * 4;
1359 let tu_around = neighbours.around_mi(tu_mi, 4)[0];1283 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
1360- let tu_reach = tu_reach(1284+ let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, 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- );
1373 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);1285 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
1374 // Each 4x4 unit predicts from its own window of the block's1286 // Each 4x4 unit predicts from its own window of the block's
1375 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at1287 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
@@ -1407,21 +1319,12 @@ pub(super) fn decode_leaf8(
1407 tu_py,1319 tu_py,
1408 4,1320 4,
1409 4,1321 4,
1410- base_q_idx,
1411 None,1322 None,
1412 filter_intra,1323 filter_intra,
1413 Some(tu_skip_ctx),1324 Some(tu_skip_ctx),
1414 smooth_neighbor,1325 smooth_neighbor,
1415 fctx,1326 fctx,
1416 )?;1327 )?;
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- }
1425 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);1328 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
1426 // The FIRST (top-left, co-located with this group's chroma)1329 // The FIRST (top-left, co-located with this group's chroma)
1427 // TU's coded tx_type is what the group's chroma inherits --1330 // TU's coded tx_type is what the group's chroma inherits --
@@ -1551,7 +1454,6 @@ pub(super) fn decode_leaf8(
1551 cdfs,1454 cdfs,
1552 neighbours,1455 neighbours,
1553 leaf_mi,1456 leaf_mi,
1554- (px, py),
1555 (cpx, cpy),1457 (cpx, cpy),
1556 8,1458 8,
1557 (blk_w, blk_h),1459 (blk_w, blk_h),
@@ -1559,13 +1461,11 @@ pub(super) fn decode_leaf8(
1559 (blk_w, blk_h),1461 (blk_w, blk_h),
1560 blk_w,1462 blk_w,
1561 reach,1463 reach,
1562- (y.width, y.height),
1563 mode,1464 mode,
1564 uv_predict_mode,1465 uv_predict_mode,
1565 angle_delta_uv,1466 angle_delta_uv,
1566 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),1467 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
1567 smooth_neighbor_uv,1468 smooth_neighbor_uv,
1568- base_q_idx,
1569 &mut uo,1469 &mut uo,
1570 &mut vo,1470 &mut vo,
1571 fctx,1471 fctx,
@@ -1600,7 +1500,6 @@ pub(super) fn decode_leaf8(
1600 cdfs,1500 cdfs,
1601 neighbours,1501 neighbours,
1602 leaf_mi,1502 leaf_mi,
1603- (px, py),
1604 (cpx, cpy),1503 (cpx, cpy),
1605 8,1504 8,
1606 (8, 8),1505 (8, 8),
@@ -1608,13 +1507,11 @@ pub(super) fn decode_leaf8(
1608 (8, 8),1507 (8, 8),
1609 8,1508 8,
1610 reach,1509 reach,
1611- (y.width, y.height),
1612 mode,1510 mode,
1613 uv_predict_mode,1511 uv_predict_mode,
1614 angle_delta_uv,1512 angle_delta_uv,
1615 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),1513 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
1616 smooth_neighbor_uv,1514 smooth_neighbor_uv,
1617- base_q_idx,
1618 &mut uo,1515 &mut uo,
1619 &mut vo,1516 &mut vo,
1620 fctx,1517 fctx,
@@ -1651,7 +1548,6 @@ pub(super) fn decode_leaf8(
1651 cpy,1548 cpy,
1652 csz,1549 csz,
1653 csz,1550 csz,
1654- base_q_idx,
1655 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1551 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1656 None,1552 None,
1657 None,1553 None,
@@ -1679,7 +1575,6 @@ pub(super) fn decode_leaf8(
1679 cpy,1575 cpy,
1680 csz,1576 csz,
1681 csz,1577 csz,
1682- base_q_idx,
1683 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1578 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1684 None,1579 None,
1685 None,1580 None,
@@ -1872,7 +1767,6 @@ pub(super) fn leaf8_chroma422_unit(
1872 usize::from(around.0) + usize::from(around.1),1767 usize::from(around.0) + usize::from(around.1),
1873 dc_sign_ctx(around.2),1768 dc_sign_ctx(around.2),
1874 default_tx,1769 default_tx,
1875- plane_idx,
1876 )?;1770 )?;
1877 let residual = dequant_and_inverse_typed_wh(1771 let residual = dequant_and_inverse_typed_wh(
1878 &levels,1772 &levels,
@@ -1949,28 +1843,10 @@ pub(super) fn read_intra_mode_sub8(
1949 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom1843 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
1950 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.1844 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
1951 let has_chroma = has_chroma && !mono(fctx);1845 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- }
1961 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder1846 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
1962 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.1847 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
1963 macro_rules! istep {1848 macro_rules! istep {
1964- ($name:literal, $val:expr) => {1849+ ($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- };
1974 }1850 }
1975 // lane-seg2: same `intra_segment_id` placement as the square and rect1851 // lane-seg2: same `intra_segment_id` placement as the square and rect
1976 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`1852 // 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(
1982 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);1858 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
1983 }1859 }
1984 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;1860 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- }
1992 istep!("skip", skip as i32);1861 istep!("skip", skip as i32);
1993 if !seg_id_pre_skip(fctx) {1862 if !seg_id_pre_skip(fctx) {
1994 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);1863 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(
2000 istep!("dq", 0);1869 istep!("dq", 0);
2001 if allow_intrabc {1870 if allow_intrabc {
2002 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;1871 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- }
2010 if use_intrabc {1872 if use_intrabc {
2011 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block1873 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
2012 // vector right after the flag and RETURNS -- no y/uv mode, angle1874 // vector right after the flag and RETURNS -- no y/uv mode, angle
@@ -2022,12 +1884,6 @@ pub(super) fn read_intra_mode_sub8(
2022 let left_ctx = INTRA_MODE_CTX[left_mode];1884 let left_ctx = INTRA_MODE_CTX[left_mode];
2023 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);1885 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
2024 istep!("mode", mode);1886 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- }
2031 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/1887 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
2032 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,1888 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
2033 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta1889 // 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(
2046 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class1902 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
2047 // `wrong-alphabet-same-value`, lane-av1-llsub8).1903 // `wrong-alphabet-same-value`, lane-av1-llsub8).
2048 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {1904 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");
2050 dec.symbol(&mut cdfs.uv_mode_cfl[mode])1905 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2051 } else {1906 } else {
2052- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2053 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])1907 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2054 };1908 };
2055- if trace {
2056- eprintln!(
2057- "TRACE sub8 uv_mode value={uv_mode} rng={}",
2058- dec.debug_state().0
2059- );
2060- }
2061 let alpha = if uv_mode == UV_CFL_PRED {1909 let alpha = if uv_mode == UV_CFL_PRED {
2062 Some(read_cfl_alphas(dec, cdfs))1910 Some(read_cfl_alphas(dec, cdfs))
2063 } else {1911 } else {
@@ -2072,12 +1920,6 @@ pub(super) fn read_intra_mode_sub8(
2072 let mut filter_intra = None;1920 let mut filter_intra = None;
2073 if mode == DC_PRED && enable_filter_intra {1921 if mode == DC_PRED && enable_filter_intra {
2074 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;1922 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- }
2081 if use_filter_intra {1923 if use_filter_intra {
2082 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);1924 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
2083 filter_intra = Some(fi_mode);1925 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(
35 u: &mut PlaneBuf<'static>,35 u: &mut PlaneBuf<'static>,
36 v: &mut PlaneBuf<'static>,36 v: &mut PlaneBuf<'static>,
37 scan4: &[u16],37 scan4: &[u16],
38- base_q_idx: u8,
39 smooth_neighbor_uv: bool,38 smooth_neighbor_uv: bool,
40 fctx: &crate::decode::FrameCtx,39 fctx: &crate::decode::FrameCtx,
41 ) -> Result<(Grid, Grid, usize, usize)> {40 ) -> Result<(Grid, Grid, usize, usize)> {
@@ -307,7 +306,6 @@ pub(super) fn sub8_leaf_chroma444(
307 py,306 py,
308 4,307 4,
309 TX4,308 TX4,
310- base_q_idx,
311 None,309 None,
312 None,310 None,
313 None,311 None,
@@ -333,7 +331,6 @@ pub(super) fn sub8_leaf_chroma444(
333 py,331 py,
334 4,332 4,
335 TX4,333 TX4,
336- base_q_idx,
337 None,334 None,
338 None,335 None,
339 None,336 None,
@@ -419,7 +416,6 @@ pub(super) fn sub8_leaf_chroma444(
419 upy,416 upy,
420 4,417 4,
421 TX4,418 TX4,
422- base_q_idx,
423 None,419 None,
424 None,420 None,
425 Some(3),421 Some(3),
@@ -468,7 +464,6 @@ pub(super) fn sub8_leaf_chroma444(
468 skip_ctx,464 skip_ctx,
469 dc_sign_ctx(around[plane_idx].2),465 dc_sign_ctx(around[plane_idx].2),
470 default_tx,466 default_tx,
471- plane_idx,
472 )?;467 )?;
473 let residual = dequant_and_inverse_typed_wh(468 let residual = dequant_and_inverse_typed_wh(
474 &levels,469 &levels,
@@ -533,7 +528,6 @@ pub(super) fn sub8_leaf_chroma444(
533 py,528 py,
534 4,529 4,
535 TX4,530 TX4,
536- base_q_idx,
537 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),531 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
538 None,532 None,
539 None,533 None,
@@ -558,7 +552,6 @@ pub(super) fn sub8_leaf_chroma444(
558 py,552 py,
559 4,553 4,
560 TX4,554 TX4,
561- base_q_idx,
562 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),555 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
563 None,556 None,
564 None,557 None,
@@ -616,7 +609,6 @@ pub(super) fn sub8_leaf_chroma444(
616 upy,609 upy,
617 4,610 4,
618 TX4,611 TX4,
619- base_q_idx,
620 None,612 None,
621 None,613 None,
622 Some(3),614 Some(3),
@@ -666,7 +658,6 @@ pub(super) fn sub8_leaf_chroma444(
666 skip_ctx,658 skip_ctx,
667 dc_sign_ctx(around[plane_idx].2),659 dc_sign_ctx(around[plane_idx].2),
668 default_tx,660 default_tx,
669- plane_idx,
670 )?;661 )?;
671 let residual = dequant_and_inverse_typed_wh(662 let residual = dequant_and_inverse_typed_wh(
672 &levels,663 &levels,
@@ -795,16 +786,7 @@ pub(super) fn sub8_leaf_chroma422(
795 u: &mut PlaneBuf<'static>,786 u: &mut PlaneBuf<'static>,
796 v: &mut PlaneBuf<'static>,787 v: &mut PlaneBuf<'static>,
797 scan4: &[u16],788 scan4: &[u16],
798- base_q_idx: u8,
799 smooth_neighbor_uv: bool,789 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.
808 leaf_shape: (usize, usize),790 leaf_shape: (usize, usize),
809 fctx: &crate::decode::FrameCtx,791 fctx: &crate::decode::FrameCtx,
810 ) -> Result<(Grid, Grid)> {792 ) -> Result<(Grid, Grid)> {
@@ -1128,7 +1110,6 @@ pub(super) fn sub8_leaf_chroma422(
1128 cpy,1110 cpy,
1129 4,1111 4,
1130 TX4,1112 TX4,
1131- base_q_idx,
1132 None,1113 None,
1133 None,1114 None,
1134 None,1115 None,
@@ -1154,7 +1135,6 @@ pub(super) fn sub8_leaf_chroma422(
1154 cpy,1135 cpy,
1155 4,1136 4,
1156 TX4,1137 TX4,
1157- base_q_idx,
1158 None,1138 None,
1159 None,1139 None,
1160 None,1140 None,
@@ -1182,7 +1162,6 @@ pub(super) fn sub8_leaf_chroma422(
1182 cpy,1162 cpy,
1183 4,1163 4,
1184 TX4,1164 TX4,
1185- base_q_idx,
1186 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1165 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1187 None,1166 None,
1188 None,1167 None,
@@ -1207,7 +1186,6 @@ pub(super) fn sub8_leaf_chroma422(
1207 cpy,1186 cpy,
1208 4,1187 4,
1209 TX4,1188 TX4,
1210- base_q_idx,
1211 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1189 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1212 None,1190 None,
1213 None,1191 None,
@@ -1257,13 +1235,9 @@ pub(super) fn decode_leaf_split4(
1257 y: &mut PlaneBuf<'static>,1235 y: &mut PlaneBuf<'static>,
1258 u: &mut PlaneBuf<'static>,1236 u: &mut PlaneBuf<'static>,
1259 v: &mut PlaneBuf<'static>,1237 v: &mut PlaneBuf<'static>,
1260- base_q_idx: u8,
1261 enable_filter_intra: bool,1238 enable_filter_intra: bool,
1262 allow_intrabc: bool,1239 allow_intrabc: bool,
1263 reduced_tx_set: bool,1240 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
1267 fctx: &crate::decode::FrameCtx,1241 fctx: &crate::decode::FrameCtx,
1268 ) -> Result<(usize, usize)> {1242 ) -> Result<(usize, usize)> {
1269 let (r, c) = outer_at;1243 let (r, c) = outer_at;
@@ -1426,7 +1400,6 @@ pub(super) fn decode_leaf_split4(
1426 py,1400 py,
1427 4,1401 4,
1428 4,1402 4,
1429- base_q_idx,
1430 None,1403 None,
1431 None,1404 None,
1432 None,1405 None,
@@ -1464,7 +1437,6 @@ pub(super) fn decode_leaf_split4(
1464 u,1437 u,
1465 v,1438 v,
1466 scan4,1439 scan4,
1467- base_q_idx,
1468 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),1440 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
1469 fctx,1441 fctx,
1470 )?;1442 )?;
@@ -1484,7 +1456,6 @@ pub(super) fn decode_leaf_split4(
1484 u,1456 u,
1485 v,1457 v,
1486 scan4,1458 scan4,
1487- base_q_idx,
1488 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),1459 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
1489 (4, 4),1460 (4, 4),
1490 fctx,1461 fctx,
@@ -1555,7 +1526,6 @@ pub(super) fn decode_leaf_split4(
1555 py,1526 py,
1556 4,1527 4,
1557 4,1528 4,
1558- base_q_idx,
1559 None,1529 None,
1560 filter_intra,1530 filter_intra,
1561 None,1531 None,
@@ -1586,7 +1556,6 @@ pub(super) fn decode_leaf_split4(
1586 u,1556 u,
1587 v,1557 v,
1588 scan4,1558 scan4,
1589- base_q_idx,
1590 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),1559 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
1591 fctx,1560 fctx,
1592 )?;1561 )?;
@@ -1612,7 +1581,6 @@ pub(super) fn decode_leaf_split4(
1612 u,1581 u,
1613 v,1582 v,
1614 scan4,1583 scan4,
1615- base_q_idx,
1616 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),1584 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
1617 (4, 4),1585 (4, 4),
1618 fctx,1586 fctx,
@@ -1770,7 +1738,6 @@ pub(super) fn decode_leaf_split4(
1770 cpy,1738 cpy,
1771 4,1739 4,
1772 TX4,1740 TX4,
1773- base_q_idx,
1774 None,1741 None,
1775 None,1742 None,
1776 None,1743 None,
@@ -1796,7 +1763,6 @@ pub(super) fn decode_leaf_split4(
1796 cpy,1763 cpy,
1797 4,1764 4,
1798 TX4,1765 TX4,
1799- base_q_idx,
1800 None,1766 None,
1801 None,1767 None,
1802 None,1768 None,
@@ -1826,7 +1792,6 @@ pub(super) fn decode_leaf_split4(
1826 cpy,1792 cpy,
1827 4,1793 4,
1828 TX4,1794 TX4,
1829- base_q_idx,
1830 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1795 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1831 None,1796 None,
1832 None,1797 None,
@@ -1851,7 +1816,6 @@ pub(super) fn decode_leaf_split4(
1851 cpy,1816 cpy,
1852 4,1817 4,
1853 TX4,1818 TX4,
1854- base_q_idx,
1855 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1819 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1856 None,1820 None,
1857 None,1821 None,
@@ -1960,7 +1924,6 @@ pub(super) fn decode_leaf_rect8(
1960 y: &mut PlaneBuf<'static>,1924 y: &mut PlaneBuf<'static>,
1961 u: &mut PlaneBuf<'static>,1925 u: &mut PlaneBuf<'static>,
1962 v: &mut PlaneBuf<'static>,1926 v: &mut PlaneBuf<'static>,
1963- base_q_idx: u8,
1964 enable_filter_intra: bool,1927 enable_filter_intra: bool,
1965 allow_intrabc: bool,1928 allow_intrabc: bool,
1966 tx_select: bool,1929 tx_select: bool,
@@ -2137,19 +2100,7 @@ pub(super) fn decode_leaf_rect8(
2137 let tu_reach = if single {2100 let tu_reach = if single {
2138 reach2101 reach
2139 } else {2102 } else {
2140- tu_reach(2103+ tu_reach(bw, bh, tu_px - px, tu_py - py, tw, 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- )
2153 };2104 };
2154 let mut yb = vec![0u16; tw * th];2105 let mut yb = vec![0u16; tw * th];
2155 mc::predict_with_filter(2106 mc::predict_with_filter(
@@ -2252,7 +2203,6 @@ pub(super) fn decode_leaf_rect8(
2252 skip_ctx,2203 skip_ctx,
2253 dc_sign_ctx(around.2),2204 dc_sign_ctx(around.2),
2254 TxType::DctDct,2205 TxType::DctDct,
2255- 0,
2256 )?;2206 )?;
2257 if li == 0 {2207 if li == 0 {
2258 chroma_tx = tx_type;2208 chroma_tx = tx_type;
@@ -2384,7 +2334,6 @@ pub(super) fn decode_leaf_rect8(
2384 u,2334 u,
2385 v,2335 v,
2386 scan4,2336 scan4,
2387- base_q_idx,
2388 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2337 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2389 fctx,2338 fctx,
2390 )?;2339 )?;
@@ -2406,7 +2355,6 @@ pub(super) fn decode_leaf_rect8(
2406 u,2355 u,
2407 v,2356 v,
2408 scan4,2357 scan4,
2409- base_q_idx,
2410 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2358 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2411 (bw, bh),2359 (bw, bh),
2412 fctx,2360 fctx,
@@ -2438,7 +2386,7 @@ pub(super) fn decode_leaf_rect8(
2438 let depth = if tx_select && !lossless(fctx) {2386 let depth = if tx_select && !lossless(fctx) {
2439 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect2387 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect
2440 // reader already does.2388 // 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);
2442 dec.symbol(&mut cdfs.tx_size_cat0[ctx])2390 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
2443 } else {2391 } else {
2444 02392 0
@@ -2475,19 +2423,7 @@ pub(super) fn decode_leaf_rect8(
2475 // (lane-palette2 r12): a transform unit inside a block is not2423 // (lane-palette2 r12): a transform unit inside a block is not
2476 // a block at that position, so its reach comes from the2424 // a block at that position, so its reach comes from the
2477 // block's own row, offset by the unit's position.2425 // block's own row, offset by the unit's position.
2478- let tu_reach = tu_reach(2426+ let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, 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- );
2491 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);2427 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
2492 if skip {2428 if skip {
2493 // A skipped leaf still predicts per transform unit: the2429 // A skipped leaf still predicts per transform unit: the
@@ -2537,7 +2473,6 @@ pub(super) fn decode_leaf_rect8(
2537 tu_py,2473 tu_py,
2538 4,2474 4,
2539 TX4,2475 TX4,
2540- base_q_idx,
2541 None,2476 None,
2542 filter_intra,2477 filter_intra,
2543 Some(tu_skip_ctx),2478 Some(tu_skip_ctx),
@@ -2576,7 +2511,6 @@ pub(super) fn decode_leaf_rect8(
2576 u,2511 u,
2577 v,2512 v,
2578 scan4,2513 scan4,
2579- base_q_idx,
2580 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2514 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2581 fctx,2515 fctx,
2582 )?;2516 )?;
@@ -2604,7 +2538,6 @@ pub(super) fn decode_leaf_rect8(
2604 u,2538 u,
2605 v,2539 v,
2606 scan4,2540 scan4,
2607- base_q_idx,
2608 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2541 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2609 (bw, bh),2542 (bw, bh),
2610 fctx,2543 fctx,
@@ -2661,7 +2594,6 @@ pub(super) fn decode_leaf_rect8(
2661 0,2594 0,
2662 dc_sign_ctx(around.2),2595 dc_sign_ctx(around.2),
2663 TxType::DctDct,2596 TxType::DctDct,
2664- 0,
2665 )?;2597 )?;
2666 if levels.iter().any(|&l| l != 0) {2598 if levels.iter().any(|&l| l != 0) {
2667 if vert {2599 if vert {
@@ -2738,7 +2670,6 @@ pub(super) fn decode_leaf_rect8(
2738 u,2670 u,
2739 v,2671 v,
2740 scan4,2672 scan4,
2741- base_q_idx,
2742 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2673 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2743 fctx,2674 fctx,
2744 )?;2675 )?;
@@ -2769,7 +2700,6 @@ pub(super) fn decode_leaf_rect8(
2769 u,2700 u,
2770 v,2701 v,
2771 scan4,2702 scan4,
2772- base_q_idx,
2773 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),2703 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
2774 (bw, bh),2704 (bw, bh),
2775 fctx,2705 fctx,
@@ -2970,7 +2900,6 @@ pub(super) fn decode_leaf_rect8(
2970 cpy,2900 cpy,
2971 4,2901 4,
2972 TX4,2902 TX4,
2973- base_q_idx,
2974 None,2903 None,
2975 None,2904 None,
2976 None,2905 None,
@@ -2996,7 +2925,6 @@ pub(super) fn decode_leaf_rect8(
2996 cpy,2925 cpy,
2997 4,2926 4,
2998 TX4,2927 TX4,
2999- base_q_idx,
3000 None,2928 None,
3001 None,2929 None,
3002 None,2930 None,
@@ -3027,7 +2955,6 @@ pub(super) fn decode_leaf_rect8(
3027 cpy,2955 cpy,
3028 4,2956 4,
3029 TX4,2957 TX4,
3030- base_q_idx,
3031 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),2958 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
3032 None,2959 None,
3033 None,2960 None,
@@ -3052,7 +2979,6 @@ pub(super) fn decode_leaf_rect8(
3052 cpy,2979 cpy,
3053 4,2980 4,
3054 TX4,2981 TX4,
3055- base_q_idx,
3056 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),2982 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
3057 None,2983 None,
3058 None,2984 None,
crates/ec-av1/src/decode/mod.rsmodified+5 -438
@@ -40,7 +40,6 @@ use ec_core::{Error, Result};
40 // itself was lifted by lane-av112bitc before that (the combines absorb the40 // itself was lifted by lane-av112bitc before that (the combines absorb the
41 // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`).41 // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`).
42 42
43-
44 mod frame_tile;43 mod frame_tile;
45 44
46 mod inter_block8;45 mod inter_block8;
@@ -431,38 +430,6 @@ thread_local! {
431 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };430 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
432 }431 }
433 432
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-
466 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).433 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
467 pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {434 pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
468 fctx.sb128_flag.with(|c| c.set(v));435 fctx.sb128_flag.with(|c| c.set(v));
@@ -544,20 +511,6 @@ thread_local! {
544 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };511 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
545 }512 }
546 513
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-
561 /// [`gather`] over an alphabet of any length -- the 128-level partition CDF514 /// [`gather`] over an alphabet of any length -- the 128-level partition CDF
562 /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec515 /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
563 /// `partition_cdf_length`), so its forced-split gather sums 5 elements where516 /// `partition_cdf_length`), so its forced-split gather sums 5 elements where
@@ -903,17 +856,6 @@ pub(crate) fn set_segmentation(
903 prev: Option<&[u8]>,856 prev: Option<&[u8]>,
904 fctx: &crate::decode::FrameCtx,857 fctx: &crate::decode::FrameCtx,
905 ) {858 ) {
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- }
917 fctx.seg.with(|s| *s.borrow_mut() = seg);859 fctx.seg.with(|s| *s.borrow_mut() = seg);
918 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));860 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
919 fctx.seg_ids861 fctx.seg_ids
@@ -940,19 +882,6 @@ pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
940 fctx.seg_ids.with(|m| m.borrow().clone())882 fctx.seg_ids.with(|m| m.borrow().clone())
941 }883 }
942 884
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-
956 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently885 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently
957 /// being decoded, with its `FeatureData` value.886 /// being decoded, with its `FeatureData` value.
958 fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {887 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 {
977 // lane-d792: which SEGMENT a block's quantizer came out of, beside the906 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
978 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels907 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
979 // already proven equal is a segment-id defect, not a quantizer one.908 // 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- }
983 q909 q
984 }910 }
985 911
@@ -1153,12 +1079,6 @@ fn read_segment_id(
1153 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);1079 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1154 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`1080 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1155 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.1081 // (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- }
1162 id as u81082 id as u8
1163 }1083 }
1164 1084
@@ -1324,15 +1244,8 @@ fn tu_reach(
1324 row_off: usize,1244 row_off: usize,
1325 tx: usize,1245 tx: usize,
1326 block: Reach,1246 block: Reach,
1327- px: usize,
1328- py: usize,
1329- width: usize,
1330- height: usize,
1331- fctx: &crate::decode::FrameCtx,
1332 ) -> Reach {1247 ) -> Reach {
1333- let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);1248+ 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
1336 }1249 }
1337 1250
1338 /// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect1251 /// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect
@@ -1351,38 +1264,17 @@ fn tu_reach_rect(
1351 tx_w: usize,1264 tx_w: usize,
1352 tx_h: usize,1265 tx_h: usize,
1353 block: Reach,1266 block: Reach,
1354- px: usize,
1355- py: usize,
1356- width: usize,
1357- height: usize,
1358- fctx: &crate::decode::FrameCtx,
1359 ) -> Reach {1267 ) -> Reach {
1360- let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);1268+ 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
1365 }1269 }
1366 1270
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-
1372 /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).1271 /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1373-pub(crate) fn note_fwd_kf() {1272+pub(crate) fn note_fwd_kf() {}
1374-}
1375 1273
1376 thread_local! {1274 thread_local! {
1377 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };1275 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1378 }1276 }
1379 1277
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-
1386 /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/1278 /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1387 /// [`ENABLE_FILTER_INTRA_INTER`].1279 /// [`ENABLE_FILTER_INTRA_INTER`].
1388 pub(crate) fn set_inter_tx_mode(1280 pub(crate) fn set_inter_tx_mode(
@@ -1399,16 +1291,6 @@ pub(crate) fn set_inter_tx_mode(
1399 .with(|c| c.set(enable_filter_intra));1291 .with(|c| c.set(enable_filter_intra));
1400 }1292 }
1401 1293
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-
1412 // lane-av1muchroma site 1: the total number of samples by which1294 // lane-av1muchroma site 1: the total number of samples by which
1413 // `decode_block`'s SKIP arm chroma bookkeeping grids fell SHORT of their own1295 // `decode_block`'s SKIP arm chroma bookkeeping grids fell SHORT of their own
1414 // plane block, summed over every skipped block decoded. It reads the1296 // plane block, summed over every skipped block decoded. It reads the
@@ -1423,12 +1305,6 @@ thread_local! {
1423 const { std::cell::Cell::new(0) };1305 const { std::cell::Cell::new(0) };
1424 }1306 }
1425 1307
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-
1432 // Number of times `decode_block`'s SKIP arm ran at a shape where the1308 // Number of times `decode_block`'s SKIP arm ran at a shape where the
1433 // per-axis and square chroma allocations DIFFER -- i.e. at 4:2:2, where1309 // per-axis and square chroma allocations DIFFER -- i.e. at 4:2:2, where
1434 // the square is half the plane block. Zero on 4:2:0 and 4:4:4, where the1310 // the square is half the plane block. Zero on 4:2:0 and 4:4:4, where the
@@ -1440,12 +1316,6 @@ thread_local! {
1440 const { std::cell::Cell::new(0) };1316 const { std::cell::Cell::new(0) };
1441 }1317 }
1442 1318
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-
1449 // lane-av1floorshift: the two FRAME chroma plane allocators1319 // lane-av1floorshift: the two FRAME chroma plane allocators
1450 // (`decode_key_frame_tile_with_cdfs` and `decode_inter_tile`'s `PlaneBuf` trio)1320 // (`decode_key_frame_tile_with_cdfs` and `decode_inter_tile`'s `PlaneBuf` trio)
1451 // size U and V as `(width >> ss_x) x (height >> ss_y)` with `width`/`height`1321 // size U and V as `(width >> ss_x) x (height >> ss_y)` with `width`/`height`
@@ -1488,147 +1358,6 @@ thread_local! {
1488 const { std::cell::Cell::new(0) };1358 const { std::cell::Cell::new(0) };
1489 }1359 }
1490 1360
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-
1632 /// A just-decoded palette-Y block's own predicted pixels1361 /// A just-decoded palette-Y block's own predicted pixels
1633 /// (`side*side`, row-major, `colors[map[i]]`), consumed by1362 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1634 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the1363 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
@@ -1675,27 +1404,12 @@ fn palette_window(
1675 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.1404 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1676 #[track_caller]1405 #[track_caller]
1677 fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {1406 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- }
1686 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));1407 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
1687 }1408 }
1688 1409
1689 #[track_caller]1410 #[track_caller]
1690 fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {1411 fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
1691 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());1412 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- }
1699 got1413 got
1700 }1414 }
1701 1415
@@ -1760,13 +1474,6 @@ pub(crate) struct TxParams {
1760 /// ran on a frame that is NOT `CodedLossless`.1474 /// ran on a frame that is NOT `CodedLossless`.
1761 static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);1475 static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1762 1476
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-
1770 /// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS1477 /// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
1771 /// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.1478 /// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
1772 /// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a1479 /// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
@@ -1783,13 +1490,6 @@ pub(crate) fn lossless_wht_units() -> usize {
1783 static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =1490 static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
1784 std::sync::atomic::AtomicUsize::new(0);1491 std::sync::atomic::AtomicUsize::new(0);
1785 1492
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-
1793 impl TxParams {1493 impl TxParams {
1794 /// The one copy of the produce-the-residual code.1494 /// The one copy of the produce-the-residual code.
1795 fn run(self, grid: &[i32]) -> Vec<i32> {1495 fn run(self, grid: &[i32]) -> Vec<i32> {
@@ -2130,14 +1830,6 @@ fn push_mc_rect(
2130 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block1830 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block
2131 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring1831 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring
2132 // block's reconstruction (lanes/av1ibcfork.report.md).1832 // 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- }
2141 let Some((src, stride)) = prediction.inline(stride) else {1833 let Some((src, stride)) = prediction.inline(stride) else {
2142 let Pred::Cur {1834 let Pred::Cur {
2143 plane: sp,1835 plane: sp,
@@ -2452,7 +2144,7 @@ fn exec_mc(
2452 1 => &mut *u,2144 1 => &mut *u,
2453 _ => &mut *v,2145 _ => &mut *v,
2454 };2146 };
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);
2456 }2148 }
2457 2149
2458 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so2150 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
@@ -2483,11 +2175,6 @@ thread_local! {
2483 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };2175 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2484 }2176 }
2485 2177
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-
2491 thread_local! {2178 thread_local! {
2492 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as2179 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
2493 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the2180 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
@@ -2497,12 +2184,6 @@ thread_local! {
2497 const { std::cell::Cell::new(0) };2184 const { std::cell::Cell::new(0) };
2498 }2185 }
2499 2186
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-
2506 /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes2187 /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
2507 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any2188 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
2508 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an2189 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
@@ -2582,8 +2263,7 @@ fn record_intrabc_mi_rect(
2582 2263
2583 /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose2264 /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
2584 /// `force_integer_mv` bit is set.2265 /// `force_integer_mv` bit is set.
2585-pub fn note_force_integer_mv_frame() {2266+pub fn note_force_integer_mv_frame() {}
2586-}
2587 2267
2588 // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter2268 // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
2589 // off the neighbour band -- the positive half of the proof for "an OBMC2269 // off the neighbour band -- the positive half of the proof for "an OBMC
@@ -2595,48 +2275,6 @@ thread_local! {
2595 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };2275 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2596 }2276 }
2597 2277
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-
2640 thread_local! {2278 thread_local! {
2641 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };2279 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2642 }2280 }
@@ -2652,19 +2290,6 @@ thread_local! {
2652 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };2290 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
2653 }2291 }
2654 2292
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-
2668 /// One 16x4 / 4x16 inter strip's chroma situation, handed to2293 /// One 16x4 / 4x16 inter strip's chroma situation, handed to
2669 /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom2294 /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
2670 /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites2295 /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
@@ -2686,11 +2311,6 @@ pub(crate) struct InterStripChroma {
2686 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,2311 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2687 }2312 }
2688 2313
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-
2694 /// Everything [`decode_inter_block`] needs to fold temporal MV candidates2314 /// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2695 /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:2315 /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2696 /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s2316 /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
@@ -2803,12 +2423,6 @@ pub(crate) fn build_motion_field(
2803 crate::par::run_bands_mut(&bands, cols, fctx, cells, |r0, r1, mine, _| {2423 crate::par::run_bands_mut(&bands, cols, fctx, cells, |r0, r1, mine, _| {
2804 fill(r0, r1, mine);2424 fill(r0, r1, mine);
2805 });2425 });
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- }
2812 field2426 field
2813 }2427 }
2814 2428
@@ -2852,32 +2466,12 @@ pub fn cdef_mixed_skip_units() -> usize {
2852 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())2466 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
2853 }2467 }
2854 2468
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-
2861 /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded2469 /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
2862 /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).2470 /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
2863 pub fn cdef_unwritten_skip_units() -> usize {2471 pub fn cdef_unwritten_skip_units() -> usize {
2864 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())2472 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
2865 }2473 }
2866 2474
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-
2881 // Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).2475 // Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
2882 // lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and2476 // lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
2883 // without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a2477 // without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
@@ -2889,11 +2483,6 @@ thread_local! {
2889 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };2483 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2890 }2484 }
2891 2485
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-
2897 /// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on2486 /// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
2898 /// either of its two early returns.2487 /// either of its two early returns.
2899 struct PlaneGuard(usize);2488 struct PlaneGuard(usize);
@@ -2953,12 +2542,6 @@ const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
2953 const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];2542 const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
2954 const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];2543 const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
2955 2544
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-
2962 fn element_prob(cdf: &[u16], element: usize) -> u16 {2545 fn element_prob(cdf: &[u16], element: usize) -> u16 {
2963 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }2546 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
2964 }2547 }
@@ -3164,9 +2747,6 @@ fn base_ctx(
3164 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`2747 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3165 // pins the rule against the tables over their whole 5x5 domain.2748 // pins the rule against the tables over their whole 5x5 domain.
3166 if let Some((w, h)) = rect_shape {2749 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- }
3170 if w < h && row < 2 {2750 if w < h && row < 2 {
3171 return ctx + 11;2751 return ctx + 11;
3172 }2752 }
@@ -3580,7 +3160,6 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
3580 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];3160 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
3581 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];3161 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
3582 3162
3583- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
3584 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan3163 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
3585 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt3164 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
3586 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s3165 // 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) ->
3591 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,3170 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
3592 (_, Some(class1)) => class1,3171 (_, Some(class1)) => class1,
3593 };3172 };
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");
3599 let group = dec.symbol(eob_pt) + 1;3173 let group = dec.symbol(eob_pt) + 1;
3600- if trace {
3601- eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
3602- }
3603 let bits = OFFSET_BITS[group];3174 let bits = OFFSET_BITS[group];
3604 let mut offset = 0u32;3175 let mut offset = 0u32;
3605 if bits > 0 {3176 if bits > 0 {
3606 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;3177 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- }
3610 offset = top << (bits - 1);3178 offset = top << (bits - 1);
3611 if bits > 1 {3179 if bits > 1 {
3612 offset |= dec.literal(bits - 1);3180 offset |= dec.literal(bits - 1);
@@ -3715,4 +3283,3 @@ pub(crate) fn decode_key_frame_tile(
3715 3283
3716 #[cfg(test)]3284 #[cfg(test)]
3717 mod tests;3285 mod tests;
3718-
crates/ec-av1/src/decode/post_filter.rsmodified+10 -13
@@ -68,16 +68,16 @@ fn cdef_rows(
68 .enumerate()68 .enumerate()
69 .map(|(k, &(a, b))| {69 .map(|(k, &(a, b))| {
70 let start = row_of(a, p) * geom[p].stride;70 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+ };
72 (start, end)76 (start, end)
73 })77 })
74 .collect()78 .collect()
75 };79 };
76- let (yd, ud, vd) = (80+ let (yd, ud, vd) = (y.data.to_mut(), u.data.to_mut(), v.data.to_mut());
77- y.data.to_mut(),
78- u.data.to_mut(),
79- v.data.to_mut(),
80- );
81 let (ry, ru, rv) = (81 let (ry, ru, rv) = (
82 plane_ranges(0, yd.len()),82 plane_ranges(0, yd.len()),
83 plane_ranges(1, ud.len()),83 plane_ranges(1, ud.len()),
@@ -97,7 +97,10 @@ fn cdef_rows(
97 (start, end)97 (start, end)
98 })98 })
99 .collect();99 .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()
101 }104 }
102 None => (0..n).map(|_| None).collect(),105 None => (0..n).map(|_| None).collect(),
103 };106 };
@@ -161,9 +164,6 @@ pub(super) fn apply_cdef(
161 wrote: Option<&mut [u8]>,164 wrote: Option<&mut [u8]>,
162 ) {165 ) {
163 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.166 // 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- }
167 // `cdef.bits == 0` still means "no filtering at all" whenever the single167 // `cdef.bits == 0` still means "no filtering at all" whenever the single
168 // (index 0) strength pair is all-zero -- the fast path every existing168 // (index 0) strength pair is all-zero -- the fast path every existing
169 // gate stream takes. A `bits > 0` frame can still be all-zero-strength169 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
@@ -295,9 +295,6 @@ pub(super) fn apply_loop_restoration(
295 fctx: &crate::decode::FrameCtx,295 fctx: &crate::decode::FrameCtx,
296 ) {296 ) {
297 // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings.297 // 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- }
301 let mut out = scratch_empty();298 let mut out = scratch_empty();
302 crate::restoration::apply_loop_restoration_plane(299 crate::restoration::apply_loop_restoration_plane(
303 &y.data,300 &y.data,
crates/ec-av1/src/decode/rect.rsmodified+6 -278
@@ -61,41 +61,15 @@ pub(super) fn read_intra_mode_rect(
61 // `palette_uv` even on a chroma-reference strip. Fold the plane count61 // `palette_uv` even on a chroma-reference strip. Fold the plane count
62 // into the same `has_chroma` this reader already gates on.62 // into the same `has_chroma` this reader already gates on.
63 let has_chroma = has_chroma && !mono(fctx);63 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- }
78 macro_rules! istep {64 macro_rules! istep {
79- ($name:literal, $val:expr) => {65+ ($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- };
88 }66 }
89 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is67 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
90 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at68 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
91 // the one point every rect caller routes through, so no call site can69 // the one point every rect caller routes through, so no call site can
92 // offer the 14-symbol CFL alphabet on a 64-axis block (class70 // offer the 14-symbol CFL alphabet on a 64-axis block (class
93 // wrong-alphabet-same-value: same value, wrong interval, silent desync).71 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
94- let cfl = if cfl && bw.max(bh) > 32 {72+ let cfl = if cfl && bw.max(bh) > 32 { false } else { cfl };
95- false
96- } else {
97- cfl
98- };
99 // lane-intra14 r1: on the INTER block path everything up to and including73 // lane-intra14 r1: on the INTER block path everything up to and including
100 // `is_inter` was already read by [`decode_inter_block`], so this reader74 // `is_inter` was already read by [`decode_inter_block`], so this reader
101 // starts at the mode syntax with the `skip` that caller read.75 // starts at the mode syntax with the `skip` that caller read.
@@ -160,7 +134,6 @@ pub(super) fn read_intra_mode_rect(
160 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`134 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
161 // off `kf_y_mode_cdf[above][left]`).135 // off `kf_y_mode_cdf[above][left]`).
162 let mode = if let Some((size_group, _)) = inter {136 let mode = if let Some((size_group, _)) = inter {
163- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
164 dec.symbol(&mut cdfs.y_mode[size_group])137 dec.symbol(&mut cdfs.y_mode[size_group])
165 } else {138 } else {
166 let above_ctx = INTRA_MODE_CTX[above_mode];139 let above_ctx = INTRA_MODE_CTX[above_mode];
@@ -185,10 +158,8 @@ pub(super) fn read_intra_mode_rect(
185 let uv_mode = if !has_chroma {158 let uv_mode = if !has_chroma {
186 DC_PRED159 DC_PRED
187 } else if cfl {160 } else if cfl {
188- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
189 dec.symbol(&mut cdfs.uv_mode_cfl[mode])161 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
190 } else {162 } else {
191- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
192 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])163 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
193 };164 };
194 istep!("uv_mode", uv_mode as i32);165 istep!("uv_mode", uv_mode as i32);
@@ -233,15 +204,6 @@ pub(super) fn read_intra_mode_rect(
233 }204 }
234 }205 }
235 let mut filter_intra = None;206 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- }
245 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y207 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
246 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.208 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
247 if mode == DC_PRED209 if mode == DC_PRED
@@ -250,9 +212,6 @@ pub(super) fn read_intra_mode_rect(
250 && let Some(class) = filter_intra_size_class_rect(bw, bh)212 && let Some(class) = filter_intra_size_class_rect(bw, bh)
251 {213 {
252 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;214 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- }
256 istep!("use_filter_intra", use_filter_intra as i32);215 istep!("use_filter_intra", use_filter_intra as i32);
257 if use_filter_intra {216 if use_filter_intra {
258 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);217 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
@@ -334,9 +293,6 @@ pub(super) fn record_strip_palette(
334 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode293 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
335 // path left a stale `left_palette_size` behind when294 // path left a stale `left_palette_size` behind when
336 // `av1_get_palette_mode_ctx` disagrees with libaom's.295 // `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- }
340 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip296 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
341 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only297 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
342 // existed because the 16px [`SUB`] cell held one slot for all the strips298 // existed because the 16px [`SUB`] cell held one slot for all the strips
@@ -503,17 +459,12 @@ pub(super) fn decode_rect_split(
503 at_mi: (usize, usize),459 at_mi: (usize, usize),
504 bw: usize,460 bw: usize,
505 bh: usize,461 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`].
510 tx_w: usize,462 tx_w: usize,
511 tx_h: usize,463 tx_h: usize,
512 m: &RectStripModes,464 m: &RectStripModes,
513 y: &mut PlaneBuf<'static>,465 y: &mut PlaneBuf<'static>,
514 u: &mut PlaneBuf<'static>,466 u: &mut PlaneBuf<'static>,
515 v: &mut PlaneBuf<'static>,467 v: &mut PlaneBuf<'static>,
516- base_q_idx: u8,
517 reduced_tx_set: bool,468 reduced_tx_set: bool,
518 fctx: &crate::decode::FrameCtx,469 fctx: &crate::decode::FrameCtx,
519 ) -> Result<()> {470 ) -> Result<()> {
@@ -593,14 +544,6 @@ pub(super) fn decode_rect_split(
593 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)544 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
594 );545 );
595 if !m.skip {546 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- }
604 if !m.skip && chroma.is_none() && !chroma_tiled {547 if !m.skip && chroma.is_none() && !chroma_tiled {
605 // Diagnostic for the next caller that lands here (class548 // Diagnostic for the next caller that lands here (class
606 // refusal-names-a-correlate: the message names the tool, not the549 // refusal-names-a-correlate: the message names the tool, not the
@@ -754,9 +697,6 @@ pub(super) fn decode_rect_split(
754 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once697 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
755 // the square-up size is TX_64X64), and this unit covers its698 // the square-up size is TX_64X64), and this unit covers its
756 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.699 // 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- }
760 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];700 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
761 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));701 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
762 let (corner, tu_tx_type) = read_coeffs(702 let (corner, tu_tx_type) = read_coeffs(
@@ -834,7 +774,6 @@ pub(super) fn decode_rect_split(
834 tu_skip_ctx,774 tu_skip_ctx,
835 dc_sign_ctx(tu_around.2),775 dc_sign_ctx(tu_around.2),
836 TxType::DctDct,776 TxType::DctDct,
837- 0,
838 )?;777 )?;
839 let residual = dequant_and_inverse_typed_wh(778 let residual = dequant_and_inverse_typed_wh(
840 &tu_grid,779 &tu_grid,
@@ -890,7 +829,6 @@ pub(super) fn decode_rect_split(
890 tu_py,829 tu_py,
891 tx_w,830 tx_w,
892 tx_w,831 tx_w,
893- base_q_idx,
894 None,832 None,
895 m.filter_intra,833 m.filter_intra,
896 Some(tu_skip_ctx),834 Some(tu_skip_ctx),
@@ -1117,11 +1055,6 @@ pub(super) fn decode_rect_split(
1117 cu_row * span_y,1055 cu_row * span_y,
1118 span_x,1056 span_x,
1119 block_reach,1057 block_reach,
1120- px,
1121- py,
1122- y.width,
1123- y.height,
1124- fctx,
1125 );1058 );
1126 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);1059 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
1127 if let Some((ub, vb)) = &m.palette_uv {1060 if let Some((ub, vb)) = &m.palette_uv {
@@ -1149,7 +1082,6 @@ pub(super) fn decode_rect_split(
1149 cu_y,1082 cu_y,
1150 4,1083 4,
1151 4,1084 4,
1152- base_q_idx,
1153 m.alpha1085 m.alpha
1154 .zip(ac)1086 .zip(ac)
1155 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),1087 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
@@ -1308,16 +1240,10 @@ pub(super) fn decode_rect_split(
1308 uw << ss_x(fctx),1240 uw << ss_x(fctx),
1309 uh << ss_y(fctx),1241 uh << ss_y(fctx),
1310 reach,1242 reach,
1311- px,
1312- py,
1313- y.width,
1314- y.height,
1315- fctx,
1316 );1243 );
1317 if cu_reach.above_right != reach.above_right1244 if cu_reach.above_right != reach.above_right
1318 || cu_reach.below_left != reach.below_left1245 || cu_reach.below_left != reach.below_left
1319- {1246+ {}
1320- }
1321 // 32x32 does not fit read_coeffs_rect's scratch (768). The1247 // 32x32 does not fit read_coeffs_rect's scratch (768). The
1322 // square reader is the path every other 32x32 chroma unit uses.1248 // square reader is the path every other 32x32 chroma unit uses.
1323 let levels = if uw == uh {1249 let levels = if uw == uh {
@@ -1339,7 +1265,6 @@ pub(super) fn decode_rect_split(
1339 cu_y,1265 cu_y,
1340 uw,1266 uw,
1341 uw,1267 uw,
1342- base_q_idx,
1343 cfl,1268 cfl,
1344 None,1269 None,
1345 bigger.then_some(3),1270 bigger.then_some(3),
@@ -1360,7 +1285,6 @@ pub(super) fn decode_rect_split(
1360 skip_ctx,1285 skip_ctx,
1361 dc_sign_ctx(cu_around[plane_idx].2),1286 dc_sign_ctx(cu_around[plane_idx].2),
1362 default_tx,1287 default_tx,
1363- plane_idx,
1364 )?;1288 )?;
1365 let residual = dequant_and_inverse_typed_wh(1289 let residual = dequant_and_inverse_typed_wh(
1366 &levels,1290 &levels,
@@ -1450,7 +1374,6 @@ pub(super) fn decode_rect_split(
1450 skip_ctx,1374 skip_ctx,
1451 dc_sign_ctx(around[plane_idx].2),1375 dc_sign_ctx(around[plane_idx].2),
1452 default_tx,1376 default_tx,
1453- plane_idx,
1454 )?;1377 )?;
1455 // The same delta_q proof the unsplit rect64 path records1378 // The same delta_q proof the unsplit rect64 path records
1456 // (lane-rectsplit r4: lifting the split-transform refusal moved1379 // (lane-rectsplit r4: lifting the split-transform refusal moved
@@ -1527,13 +1450,6 @@ pub(super) fn decode_rect_split(
1527 0,1450 0,
1528 fctx,1451 fctx,
1529 );1452 );
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- }
1537 Ok(())1453 Ok(())
1538 }1454 }
1539 1455
@@ -1921,13 +1837,6 @@ pub(super) fn decode_intra_rect_in_inter(
1921 }1837 }
1922 neighbours.above_side[c] = bw;1838 neighbours.above_side[c] = bw;
1923 neighbours.left_side[r] = bh;1839 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- }
1931 return Ok(());1840 return Ok(());
1932 }1841 }
1933 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half1842 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
@@ -1965,13 +1874,6 @@ pub(super) fn decode_intra_rect_in_inter(
1965 // palette_syntax`), so a 128-root half consumes no palette syntax and1874 // palette_syntax`), so a 128-root half consumes no palette syntax and
1966 // a screen-content frame's half is syntactically identical to the1875 // a screen-content frame's half is syntactically identical to the
1967 // non-screen one this arm already decodes byte-exact.1876 // 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- }
1975 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));1877 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
1976 let res = decode_block_128rect(1878 let res = decode_block_128rect(
1977 dec,1879 dec,
@@ -1994,11 +1896,6 @@ pub(super) fn decode_intra_rect_in_inter(
1994 return res;1896 return res;
1995 }1897 }
1996 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {1898 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- }
2002 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip1899 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
2003 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that1900 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
2004 // can arrive here are enumerated against the measured block-shape1901 // can arrive here are enumerated against the measured block-shape
@@ -2072,26 +1969,12 @@ pub(super) fn decode_intra_rect_in_inter(
2072 };1969 };
2073 fctx.intra_in_inter_mode.with(|c| c.set(None));1970 fctx.intra_in_inter_mode.with(|c| c.set(None));
2074 res?;1971 res?;
2075- let shape = match (bw, bh) {
2076- (64, 16) => 0,
2077- (16, 64) => 1,
2078- (32, 8) => 2,
2079- _ => 3,
2080- };
2081 return Ok(());1972 return Ok(());
2082 }1973 }
2083- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
2084 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);1974 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
2085 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its1975 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
2086 // own, so a cross-decoder bisection could only see the block's first1976 // own, so a cross-decoder bisection could only see the block's first
2087 // coefficient. Same names/format as [`read_tx_size`]'s rung.1977 // 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- }
2095 if mode >= 13 {1978 if mode >= 13 {
2096 return Err(unsupported(1979 return Err(unsupported(
2097 "an intra mode this decoder does not code (round 2)",1980 "an intra mode this decoder does not code (round 2)",
@@ -2116,19 +1999,10 @@ pub(super) fn decode_intra_rect_in_inter(
2116 let uv_mode = if !has_chroma {1999 let uv_mode = if !has_chroma {
2117 DC_PRED2000 DC_PRED
2118 } else if cfl_allowed {2001 } else if cfl_allowed {
2119- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2120 dec.symbol(&mut cdfs.uv_mode_cfl[mode])2002 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2121 } else {2003 } else {
2122- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2123 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])2004 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2124 };2005 };
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- }
2132 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {2006 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
2133 Some(read_cfl_alphas(dec, cdfs))2007 Some(read_cfl_alphas(dec, cdfs))
2134 } else {2008 } else {
@@ -2172,14 +2046,6 @@ pub(super) fn decode_intra_rect_in_inter(
2172 let use_palette_uv = has_chroma2046 let use_palette_uv = has_chroma
2173 && uv_mode == DC_PRED2047 && uv_mode == DC_PRED
2174 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;2048 && 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- }
2183 if use_palette_uv {2049 if use_palette_uv {
2184 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);2050 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
2185 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);2051 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(
2254 // segment regardless of frame type; class sweep of the sub8 leaf's fix).2120 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
2255 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {2121 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
2256 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].2122 // 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));
2258 let d = match tx_cat {2124 let d = match tx_cat {
2259 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),2125 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
2260 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),2126 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
2261 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),2127 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
2262 };2128 };
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- }
2269 d2129 d
2270 } else {2130 } else {
2271 02131 0
@@ -2273,9 +2133,6 @@ pub(super) fn decode_intra_rect_in_inter(
2273 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the2133 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
2274 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and2134 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
2275 // the two are indistinguishable when the diagnostic fires on splits alone.2135 // 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- }
2279 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);2136 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
2280 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,2137 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
2281 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block2138 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
@@ -2320,7 +2177,6 @@ pub(super) fn decode_intra_rect_in_inter(
2320 y,2177 y,
2321 u,2178 u,
2322 v,2179 v,
2323- base_q_idx,
2324 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),2180 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2325 fctx,2181 fctx,
2326 )?;2182 )?;
@@ -2352,11 +2208,6 @@ pub(super) fn decode_intra_rect_in_inter(
2352 palette_uv.as_ref().map_or(0, |p| p.size),2208 palette_uv.as_ref().map_or(0, |p| p.size),
2353 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),2209 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
2354 );2210 );
2355- let class = match bw.max(bh) {
2356- 64 => 0,
2357- 32 => 1,
2358- _ => 2,
2359- };
2360 Ok(())2211 Ok(())
2361 }2212 }
2362 2213
@@ -2397,8 +2248,6 @@ pub(super) fn decode_intrabc_rect(
2397 base_q_idx: u8,2248 base_q_idx: u8,
2398 fctx: &crate::decode::FrameCtx,2249 fctx: &crate::decode::FrameCtx,
2399 ) -> Result<()> {2250 ) -> Result<()> {
2400- // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
2401- let idx = usize::from(bh > bw);
2402 if skip {2251 if skip {
2403 } else {2252 } else {
2404 }2253 }
@@ -2449,12 +2298,6 @@ pub(super) fn decode_intrabc_rect(
2449 fctx,2298 fctx,
2450 )?;2299 )?;
2451 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.2300 // 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- }
2458 // The whole-block prediction: `predict_inter_block` runs once, before any2301 // The whole-block prediction: `predict_inter_block` runs once, before any
2459 // coefficient is read. The source is this frame's own reconstruction,2302 // coefficient is read. The source is this frame's own reconstruction,
2460 // which is already written.2303 // which is already written.
@@ -2958,12 +2801,6 @@ pub(super) fn decode_intrabc_128rect(
2958 base_q_idx: u8,2801 base_q_idx: u8,
2959 fctx: &crate::decode::FrameCtx,2802 fctx: &crate::decode::FrameCtx,
2960 ) -> Result<()> {2803 ) -> 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- }
2967 let (px, py) = (mi_c * MI, mi_r * MI);2804 let (px, py) = (mi_c * MI, mi_r * MI);
2968 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis2805 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
2969 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's2806 // `(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(
3283 } else {3120 } else {
3284 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)3121 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)
3285 };3122 };
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- }
3318 let (cu_x, cu_y) = (3123 let (cu_x, cu_y) = (
3319 cpx + cc * chunk_chroma_w + uc * cu_tx,3124 cpx + cc * chunk_chroma_w + uc * cu_tx,
3320 cpy + cr * chunk_chroma_h + ur * cu_tx,3125 cpy + cr * chunk_chroma_h + ur * cu_tx,
@@ -3364,13 +3169,6 @@ pub(super) fn decode_intrabc_128rect(
3364 plane_idx,3169 plane_idx,
3365 &cu_grid,3170 &cu_grid,
3366 );3171 );
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- }
3374 // lane-av1-ibcrect: per-unit chroma context -- the3172 // lane-av1-ibcrect: per-unit chroma context -- the
3375 // end-of-block record's composed-grid re-stamp3173 // end-of-block record's composed-grid re-stamp
3376 // must not stand (replayed below).3174 // must not stand (replayed below).
@@ -3690,14 +3488,8 @@ pub(super) fn decode_block_rect(
3690 // 1920x792 128-superblock stream,3488 // 1920x792 128-superblock stream,
3691 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read3489 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
3692 // `tx_size_cat2` row 1 where libaom reads row 2.3490 // `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);
3694 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);3492 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- }
3701 d3493 d
3702 } else {3494 } else {
3703 03495 0
@@ -3717,13 +3509,6 @@ pub(super) fn decode_block_rect(
3717 // unit's reconstruction inside this same strip (spec 5.11.36) --3509 // unit's reconstruction inside this same strip (spec 5.11.36) --
3718 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].3510 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
3719 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);3511 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- }
3727 let modes = RectStripModes {3512 let modes = RectStripModes {
3728 skip,3513 skip,
3729 mode,3514 mode,
@@ -3757,7 +3542,6 @@ pub(super) fn decode_block_rect(
3757 y,3542 y,
3758 u,3543 u,
3759 v,3544 v,
3760- base_q_idx,
3761 reduced_tx_set,3545 reduced_tx_set,
3762 fctx,3546 fctx,
3763 )?;3547 )?;
@@ -3782,14 +3566,6 @@ pub(super) fn decode_block_rect(
3782 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));3566 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
3783 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));3567 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
3784 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);3568 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- }
3793 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV3569 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
3794 // block's prediction is the reconstructed colour-index map, set fresh3570 // block's prediction is the reconstructed colour-index map, set fresh
3795 // right before each `reconstruct_rect` call below (lane-palette2 r4).3571 // right before each `reconstruct_rect` call below (lane-palette2 r4).
@@ -3987,12 +3763,7 @@ pub(super) fn decode_block_rect(
3987 0,3763 0,
3988 dc_sign_ctx(around[0].2),3764 dc_sign_ctx(around[0].2),
3989 TxType::DctDct,3765 TxType::DctDct,
3990- 0,
3991 )?;3766 )?;
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- }
3996 let luma_residual = dequant_and_inverse_typed_wh(3767 let luma_residual = dequant_and_inverse_typed_wh(
3997 &luma_levels,3768 &luma_levels,
3998 bw,3769 bw,
@@ -4039,12 +3810,7 @@ pub(super) fn decode_block_rect(
4039 dc_sign_ctx(around[1].2),3810 dc_sign_ctx(around[1].2),
4040 u_default_tx,3811 u_default_tx,
4041 fctx,3812 fctx,
4042- 1,
4043 )?;3813 )?;
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- }
4048 let u_residual = dequant_and_inverse_typed_wh(3814 let u_residual = dequant_and_inverse_typed_wh(
4049 &u_levels,3815 &u_levels,
4050 chroma_w,3816 chroma_w,
@@ -4090,12 +3856,7 @@ pub(super) fn decode_block_rect(
4090 dc_sign_ctx(around[2].2),3856 dc_sign_ctx(around[2].2),
4091 v_default_tx,3857 v_default_tx,
4092 fctx,3858 fctx,
4093- 2,
4094 )?;3859 )?;
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- }
4099 let v_residual = dequant_and_inverse_typed_wh(3860 let v_residual = dequant_and_inverse_typed_wh(
4100 &v_levels,3861 &v_levels,
4101 chroma_w,3862 chroma_w,
@@ -4153,9 +3914,6 @@ pub(super) fn decode_block_rect(
4153 0,3914 0,
4154 fctx,3915 fctx,
4155 );3916 );
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- }
4159 Ok(())3917 Ok(())
4160 }3918 }
4161 3919
@@ -4200,12 +3958,6 @@ pub(super) fn decode_leaf_rect(
4200 fctx: &crate::decode::FrameCtx,3958 fctx: &crate::decode::FrameCtx,
4201 ) -> Result<usize> {3959 ) -> Result<usize> {
4202 let _ = base_q_idx;3960 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- }
4209 let (r, c) = outer_at;3961 let (r, c) = outer_at;
4210 let mut above_mode = neighbours.above_mode[c];3962 let mut above_mode = neighbours.above_mode[c];
4211 let mut left_mode = neighbours.left_mode[r];3963 let mut left_mode = neighbours.left_mode[r];
@@ -4306,9 +4058,6 @@ pub(super) fn decode_leaf_rect(
4306 let (pal_uv_size, pal_uv_colors) = palette_uv4058 let (pal_uv_size, pal_uv_colors) = palette_uv
4307 .as_ref()4059 .as_ref()
4308 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));4060 .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- }
4312 let uv_predict_mode = if uv_mode == UV_CFL_PRED {4061 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4313 DC_PRED4062 DC_PRED
4314 } else {4063 } else {
@@ -4328,7 +4077,7 @@ pub(super) fn decode_leaf_rect(
4328 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours4077 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
4329 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next4078 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
4330 // read was the leaf's own txb_skip.4079 // 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);
4332 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,4081 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
4333 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so4082 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
4334 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol4083 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
@@ -4346,14 +4095,6 @@ pub(super) fn decode_leaf_rect(
4346 // symbol in the tile is read from the wrong place (class4095 // symbol in the tile is read from the wrong place (class
4347 // `wrong-alphabet-same-value`, here same alphabet / wrong row).4096 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
4348 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);4097 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- }
4357 d4098 d
4358 } else {4099 } else {
4359 04100 0
@@ -4398,7 +4139,6 @@ pub(super) fn decode_leaf_rect(
4398 y,4139 y,
4399 u,4140 u,
4400 v,4141 v,
4401- base_q_idx,
4402 reduced_tx_set,4142 reduced_tx_set,
4403 fctx,4143 fctx,
4404 )?;4144 )?;
@@ -4561,17 +4301,7 @@ pub(super) fn decode_leaf_rect(
4561 0,4301 0,
4562 dc_sign_ctx(around[0].2),4302 dc_sign_ctx(around[0].2),
4563 TxType::DctDct,4303 TxType::DctDct,
4564- 0,
4565 )?;4304 )?;
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- }
4575 luma_levels = l_levels;4305 luma_levels = l_levels;
4576 let luma_residual = dequant_and_inverse_typed_wh(4306 let luma_residual = dequant_and_inverse_typed_wh(
4577 &luma_levels,4307 &luma_levels,
@@ -4619,7 +4349,6 @@ pub(super) fn decode_leaf_rect(
4619 dc_sign_ctx(around[1].2),4349 dc_sign_ctx(around[1].2),
4620 u_default_tx,4350 u_default_tx,
4621 fctx,4351 fctx,
4622- 1,
4623 )?;4352 )?;
4624 u_levels = u_l;4353 u_levels = u_l;
4625 let u_residual = dequant_and_inverse_typed_wh(4354 let u_residual = dequant_and_inverse_typed_wh(
@@ -4667,7 +4396,6 @@ pub(super) fn decode_leaf_rect(
4667 dc_sign_ctx(around[2].2),4396 dc_sign_ctx(around[2].2),
4668 v_default_tx,4397 v_default_tx,
4669 fctx,4398 fctx,
4670- 2,
4671 )?;4399 )?;
4672 v_levels = v_l;4400 v_levels = v_l;
4673 let v_residual = dequant_and_inverse_typed_wh(4401 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(
161 // 1920x792 128-superblock stream,161 // 1920x792 128-superblock stream,
162 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read162 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
163 // `tx_size_cat2` row 1 where libaom reads row 2.163 // `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);
165 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);165 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- }
172 d166 d
173 } else {167 } else {
174 0168 0
@@ -210,7 +204,6 @@ pub(super) fn decode_block_rect4(
210 y,204 y,
211 u,205 u,
212 v,206 v,
213- base_q_idx,
214 false,207 false,
215 fctx,208 fctx,
216 )?;209 )?;
@@ -333,7 +326,6 @@ pub(super) fn decode_block_rect4(
333 0,326 0,
334 dc_sign_ctx(around[0].2),327 dc_sign_ctx(around[0].2),
335 TxType::DctDct,328 TxType::DctDct,
336- 0,
337 )?;329 )?;
338 let luma_residual = dequant_and_inverse_typed_wh(330 let luma_residual = dequant_and_inverse_typed_wh(
339 &luma_levels,331 &luma_levels,
@@ -375,20 +367,7 @@ pub(super) fn decode_block_rect4(
375 for plane in [1usize, 2] {367 for plane in [1usize, 2] {
376 for unit_row in 0..4usize {368 for unit_row in 0..4usize {
377 let unit_mi = (mi_r + unit_row * 2, mi_c);369 let unit_mi = (mi_r + unit_row * 2, mi_c);
378- let unit_reach = tu_reach_rect(370+ let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach);
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- );
392 if let Some((ub, vb)) = &palette_uv_bufs {371 if let Some((ub, vb)) = &palette_uv_bufs {
393 let pbuf = if plane == 1 { ub } else { vb };372 let pbuf = if plane == 1 { ub } else { vb };
394 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);373 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(
496 0,475 0,
497 dc_sign_ctx(around[0].2),476 dc_sign_ctx(around[0].2),
498 TxType::DctDct,477 TxType::DctDct,
499- 0,
500 )?;478 )?;
501 let mut planes = Vec::with_capacity(2);479 let mut planes = Vec::with_capacity(2);
502 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.480 // 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(
525 dc_sign_ctx(chroma_around[plane].2),503 dc_sign_ctx(chroma_around[plane].2),
526 default_tx,504 default_tx,
527 fctx,505 fctx,
528- plane,
529 )?;506 )?;
530 planes.push((levels, tx_type));507 planes.push((levels, tx_type));
531 }508 }
@@ -662,20 +639,7 @@ pub(super) fn decode_block_rect4(
662 // libaom's `set_entropy_context` leaves.639 // libaom's `set_entropy_context` leaves.
663 for plane in [1usize, 2] {640 for plane in [1usize, 2] {
664 for unit_row in 0..4usize {641 for unit_row in 0..4usize {
665- let unit_reach = tu_reach_rect(642+ let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach);
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- );
679 if let Some((ub, vb)) = &palette_uv_bufs {643 if let Some((ub, vb)) = &palette_uv_bufs {
680 let pbuf = if plane == 1 { ub } else { vb };644 let pbuf = if plane == 1 { ub } else { vb };
681 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);645 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(
933 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is897 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
934 // what makes this a chroma-sizing defect and not a block-geometry one.898 // what makes this a chroma-sizing defect and not a block-geometry one.
935 // Re-measured by this lane; see lanes/av1chromarect.report.md.899 // 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- }
939 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));900 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
940 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));901 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
941 let side = bw.max(bh);902 let side = bw.max(bh);
@@ -1737,15 +1698,6 @@ pub(super) fn decode_rect4_16_intrabc(
1737 bh,1698 bh,
1738 );1699 );
1739 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;1700 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- }
1749 if !split {1701 if !split {
1750 None1702 None
1751 } else {1703 } else {
@@ -2303,16 +2255,8 @@ pub(super) fn decode_rect4_16_strip(
2303 let depth = if tx_select && !lossless(fctx) {2255 let depth = if tx_select && !lossless(fctx) {
2304 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands2256 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
2305 // (`get_tx_size_context`, libaom `pred_common.h:342`).2257 // (`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);
2307 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);2259 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- }
2316 d2260 d
2317 } else {2261 } else {
2318 02262 0
@@ -2387,7 +2331,6 @@ pub(super) fn decode_rect4_16_strip(
2387 tu_skip_ctx,2331 tu_skip_ctx,
2388 dc_sign_ctx(tu_around.2),2332 dc_sign_ctx(tu_around.2),
2389 TxType::DctDct,2333 TxType::DctDct,
2390- 0,
2391 )?;2334 )?;
2392 let residual = dequant_and_inverse_typed_wh(2335 let residual = dequant_and_inverse_typed_wh(
2393 &tu_grid,2336 &tu_grid,
@@ -2440,7 +2383,6 @@ pub(super) fn decode_rect4_16_strip(
2440 tu_py,2383 tu_py,
2441 tx_w,2384 tx_w,
2442 tx_w,2385 tx_w,
2443- base_q_idx,
2444 None,2386 None,
2445 filter_intra,2387 filter_intra,
2446 Some(tu_skip_ctx),2388 Some(tu_skip_ctx),
@@ -2496,7 +2438,6 @@ pub(super) fn decode_rect4_16_strip(
2496 0,2438 0,
2497 dc_sign_ctx(around.2),2439 dc_sign_ctx(around.2),
2498 TxType::DctDct,2440 TxType::DctDct,
2499- 0,
2500 )?;2441 )?;
2501 let residual = dequant_and_inverse_typed_wh(2442 let residual = dequant_and_inverse_typed_wh(
2502 &levels,2443 &levels,
@@ -2632,8 +2573,7 @@ pub(super) fn decode_rect4_16_strip(
2632 ss_y(fctx),2573 ss_y(fctx),
2633 false,2574 false,
2634 )2575 )
2635- {2576+ {}
2636- }
2637 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane2577 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
2638 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is2578 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
2639 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major2579 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
@@ -2676,11 +2616,6 @@ pub(super) fn decode_rect4_16_strip(
2676 4 << ss_x(fctx),2616 4 << ss_x(fctx),
2677 4 << ss_y(fctx),2617 4 << ss_y(fctx),
2678 pair_reach,2618 pair_reach,
2679- ppx,
2680- ppy,
2681- y.width,
2682- y.height,
2683- fctx,
2684 );2619 );
2685 if let Some((ub, vb)) = &palette_uv_bufs {2620 if let Some((ub, vb)) = &palette_uv_bufs {
2686 let buf = if plane == 1 { ub } else { vb };2621 let buf = if plane == 1 { ub } else { vb };
@@ -2771,11 +2706,6 @@ pub(super) fn decode_rect4_16_strip(
2771 4 << ss_x(fctx),2706 4 << ss_x(fctx),
2772 4 << ss_y(fctx),2707 4 << ss_y(fctx),
2773 pair_reach,2708 pair_reach,
2774- ppx,
2775- ppy,
2776- y.width,
2777- y.height,
2778- fctx,
2779 );2709 );
2780 if let Some((ub, vb)) = &palette_uv_bufs {2710 if let Some((ub, vb)) = &palette_uv_bufs {
2781 let buf = if plane == 1 { ub } else { vb };2711 let buf = if plane == 1 { ub } else { vb };
@@ -2799,7 +2729,6 @@ pub(super) fn decode_rect4_16_strip(
2799 cpy + oy,2729 cpy + oy,
2800 4,2730 4,
2801 4,2731 4,
2802- base_q_idx,
2803 None,2732 None,
2804 None,2733 None,
2805 offset,2734 offset,
@@ -2839,20 +2768,7 @@ pub(super) fn decode_rect4_16_strip(
2839 // `set_entropy_context` zeroed the block's own cells,2768 // `set_entropy_context` zeroed the block's own cells,
2840 // so the pair-wide zero stamp below stays correct.2769 // so the pair-wide zero stamp below stays correct.
2841 for unit_row in 0..2usize {2770 for unit_row in 0..2usize {
2842- let unit_reach = tu_reach_rect(2771+ let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach);
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- );
2856 if let Some((ub, vb)) = &palette_uv_bufs {2772 if let Some((ub, vb)) = &palette_uv_bufs {
2857 let pbuf = if plane == 1 { ub } else { vb };2773 let pbuf = if plane == 1 { ub } else { vb };
2858 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);2774 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(
2928 for plane in [1usize, 2] {2844 for plane in [1usize, 2] {
2929 for unit_row in 0..2usize {2845 for unit_row in 0..2usize {
2930 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);2846 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
2931- let unit_reach = tu_reach_rect(2847+ let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach);
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- );
2945 if let Some((ub, vb)) = &palette_uv_bufs {2848 if let Some((ub, vb)) = &palette_uv_bufs {
2946 let pbuf = if plane == 1 { ub } else { vb };2849 let pbuf = if plane == 1 { ub } else { vb };
2947 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);2850 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(
3014 // row is unreachable there. It is also the witness arm:2917 // row is unreachable there. It is also the witness arm:
3015 // a restored `/2 chroma height` lands on (8,4) and the2918 // a restored `/2 chroma height` lands on (8,4) and the
3016 // counter reads 0.2919 // counter reads 0.
3017- (8, 8) => {2920+ (8, 8) => (TxbSet::Chroma8, default_scan(8)),
3018- (TxbSet::Chroma8, default_scan(8))
3019- }
3020 // lane-av1-422o: with the `chroma422_pair16` arm above,2921 // lane-av1-422o: with the `chroma422_pair16` arm above,
3021 // the (2,16) own-strip shape and the 4:4:4 shapes are the2922 // the (2,16) own-strip shape and the 4:4:4 shapes are the
3022 // only residents; anything else is a named-lane gap.2923 // only residents; anything else is a named-lane gap.
@@ -3039,7 +2940,6 @@ pub(super) fn decode_rect4_16_strip(
3039 dc_sign_ctx(around[plane].2),2940 dc_sign_ctx(around[plane].2),
3040 default_tx,2941 default_tx,
3041 fctx,2942 fctx,
3042- plane,
3043 )?;2943 )?;
3044 planes.push((levels, tx_type));2944 planes.push((levels, tx_type));
3045 }2945 }
@@ -3280,7 +3180,7 @@ pub(super) fn decode_block_rect64(
3280 // 1920x792 128-superblock stream,3180 // 1920x792 128-superblock stream,
3281 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read3181 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
3282 // `tx_size_cat2` row 1 where libaom reads row 2.3182 // `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);
3284 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)3184 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
3285 // counts `sub_tx_size_map` steps from the block's own max rect3185 // counts `sub_tx_size_map` steps from the block's own max rect
3286 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain3186 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
@@ -3289,12 +3189,6 @@ pub(super) fn decode_block_rect64(
3289 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF3189 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
3290 // here was a wrong-table read of a real symbol.3190 // here was a wrong-table read of a real symbol.
3291 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);3191 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- }
3298 d3192 d
3299 } else {3193 } else {
3300 03194 0
@@ -3315,15 +3209,7 @@ pub(super) fn decode_block_rect64(
3315 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r13209 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
3316 // measured the old square formula mis-tiling exactly that strip).3210 // measured the old square formula mis-tiling exactly that strip).
3317 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);3211 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
3318- if bw.max(bh) / bw.min(bh) == 4 {3212+ 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- }
3327 let modes = RectStripModes {3213 let modes = RectStripModes {
3328 skip,3214 skip,
3329 mode,3215 mode,
@@ -3357,7 +3243,6 @@ pub(super) fn decode_block_rect64(
3357 y,3243 y,
3358 u,3244 u,
3359 v,3245 v,
3360- base_q_idx,
3361 reduced_tx_set,3246 reduced_tx_set,
3362 fctx,3247 fctx,
3363 )?;3248 )?;
@@ -3491,12 +3376,6 @@ pub(super) fn decode_block_rect64(
3491 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).3376 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
3492 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));3377 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
3493 let scan32 = default_scan(TX32);3378 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- }
3500 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {3379 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
3501 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);3380 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
3502 read_coeffs(3381 read_coeffs(
@@ -3533,26 +3412,13 @@ pub(super) fn decode_block_rect64(
3533 0,3412 0,
3534 dc_sign_ctx(around[0].2),3413 dc_sign_ctx(around[0].2),
3535 TxType::DctDct,3414 TxType::DctDct,
3536- 0,
3537 )?3415 )?
3538 };3416 };
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- }
3543 let mut luma_levels = vec![0i32; bw * bh];3417 let mut luma_levels = vec![0i32; bw * bh];
3544 for row in 0..luma_ch {3418 for row in 0..luma_ch {
3545 luma_levels[row * bw..][..luma_cw]3419 luma_levels[row * bw..][..luma_cw]
3546 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);3420 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
3547 }3421 }
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- }
3556 let luma_residual = dequant_and_inverse_typed_wh(3422 let luma_residual = dequant_and_inverse_typed_wh(
3557 &luma_levels,3423 &luma_levels,
3558 bw,3424 bw,
@@ -3582,22 +3448,6 @@ pub(super) fn decode_block_rect64(
3582 smooth_neighbor,3448 smooth_neighbor,
3583 fctx,3449 fctx,
3584 );3450 );
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- }
3601 // CHROMA. At 4:2:0 the plane block is already one adjusted UV3451 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
3602 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma3452 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
3603 // is larger than that, so it is tiled into 32-capped units.3453 // is larger than that, so it is tiled into 32-capped units.
@@ -3624,15 +3474,6 @@ pub(super) fn decode_block_rect64(
3624 // arm nothing had reached) from `nh >= 2` (the arm the corpus census3474 // arm nothing had reached) from `nh >= 2` (the arm the corpus census
3625 // already covered), and can see WHY a candidate block did not fire.3475 // already covered), and can see WHY a candidate block did not fire.
3626 // Diagnostic only; no decode behaviour depends on it.3476 // 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- }
3636 let mut u_levels = vec![0i32; chroma_w * chroma_h];3477 let mut u_levels = vec![0i32; chroma_w * chroma_h];
3637 let mut v_levels = vec![0i32; chroma_w * chroma_h];3478 let mut v_levels = vec![0i32; chroma_w * chroma_h];
3638 // The tiled units below stamp their own coefficient context3479 // The tiled units below stamp their own coefficient context
@@ -3703,7 +3544,6 @@ pub(super) fn decode_block_rect64(
3703 cpy + cu_row * uh,3544 cpy + cu_row * uh,
3704 uw,3545 uw,
3705 uw,3546 uw,
3706- base_q_idx,
3707 cfl,3547 cfl,
3708 None,3548 None,
3709 bigger.then_some(3),3549 bigger.then_some(3),
@@ -3725,7 +3565,6 @@ pub(super) fn decode_block_rect64(
3725 dc_sign_ctx(cu_around[plane_idx].2),3565 dc_sign_ctx(cu_around[plane_idx].2),
3726 TxType::DctDct,3566 TxType::DctDct,
3727 fctx,3567 fctx,
3728- plane_idx,
3729 )?;3568 )?;
3730 let residual = dequant_and_inverse_typed_wh(3569 let residual = dequant_and_inverse_typed_wh(
3731 &levels,3570 &levels,
@@ -3844,9 +3683,5 @@ pub(super) fn decode_block_rect64(
3844 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at3683 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
3845 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.3684 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
3846 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));3685 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- }
3851 Ok(())3686 Ok(())
3852 }3687 }
crates/ec-av1/src/decode/replay.rsmodified+1 -7
@@ -508,11 +508,6 @@ pub(super) fn cdef_band(
508 let y_dir = if y_pri_strength != 0 { dir } else { 0 };508 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
509 let t = cdef_adjust_strength(y_pri_strength, var);509 let t = cdef_adjust_strength(y_pri_strength, var);
510 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.510 // 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- }
516 let enable_primary = t != 0;511 let enable_primary = t != 0;
517 let enable_secondary = y_sec_strength != 0;512 let enable_secondary = y_sec_strength != 0;
518 if (ox + 8 > frame_w || oy + 8 > frame_h)513 if (ox + 8 > frame_w || oy + 8 > frame_h)
@@ -520,8 +515,7 @@ pub(super) fn cdef_band(
520 || enable_secondary515 || enable_secondary
521 || cdef.uv_pri_strength[sidx] != 0516 || cdef.uv_pri_strength[sidx] != 0
522 || cdef.uv_sec_strength[sidx] != 0)517 || cdef.uv_sec_strength[sidx] != 0)
523- {518+ {}
524- }
525 if enable_primary || enable_secondary {519 if enable_primary || enable_secondary {
526 cdef_filter_block(520 cdef_filter_block(
527 &win_y,521 &win_y,
crates/ec-av1/src/decode/sub8_inter.rsmodified+85 -187
@@ -71,7 +71,6 @@ pub(super) fn decode_inter_sub8_split4(
71 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] =71 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] =
72 [None; 4];72 [None; 4];
73 let mut first_tx_type = TxType::DctDct;73 let mut first_tx_type = TxType::DctDct;
74- let mut sub0_tx_type = TxType::DctDct;
75 // This loop iteration's own sub-block luma `tx_type` (libaom `mbmi->tx_type`74 // This loop iteration's own sub-block luma `tx_type` (libaom `mbmi->tx_type`
76 // after its `read_tx_type`): the per-piece 4:4:4 chroma units inherit it75 // after its `read_tx_type`): the per-piece 4:4:4 chroma units inherit it
77 // (`av1_get_tx_type`, blockd.h -- inter chroma never codes its own symbol).76 // (`av1_get_tx_type`, blockd.h -- inter chroma never codes its own symbol).
@@ -110,11 +109,6 @@ pub(super) fn decode_inter_sub8_split4(
110 let skip_ctx =109 let skip_ctx =
111 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);110 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
112 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;111 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- };
118 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx);112 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx);
119 maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx);113 maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx);
120 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);114 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);
@@ -127,21 +121,7 @@ pub(super) fn decode_inter_sub8_split4(
127 neighbours.left_inter[rmi],121 neighbours.left_inter[rmi],
128 );122 );
129 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;123 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- }
137 if !is_inter {124 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- }
145 // lane-sub8intra: the `BLOCK_4X4` twin of the HORZ/VERT arm --125 // lane-sub8intra: the `BLOCK_4X4` twin of the HORZ/VERT arm --
146 // same [`decode_intra_sub8_leaf`], no tx-depth symbol, chroma on126 // same [`decode_intra_sub8_leaf`], no tx-depth symbol, chroma on
147 // the chroma-reference sub-blocks (`is_chroma_reference`: the127 // the chroma-reference sub-blocks (`is_chroma_reference`: the
@@ -161,7 +141,6 @@ pub(super) fn decode_inter_sub8_split4(
161 y,141 y,
162 u,142 u,
163 v,143 v,
164- base_q_idx,
165 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),144 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
166 fctx.tx_select_inter.with(std::cell::Cell::get),145 fctx.tx_select_inter.with(std::cell::Cell::get),
167 reduced_tx_set,146 reduced_tx_set,
@@ -175,12 +154,6 @@ pub(super) fn decode_inter_sub8_split4(
175 // Same print point as the oracle's `EC_MODE` (entry of154 // Same print point as the oracle's `EC_MODE` (entry of
176 // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the155 // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the
177 // two range ladders line up element for element.156 // 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- }
184 let ref_frame = read_single_ref(157 let ref_frame = read_single_ref(
185 dec,158 dec,
186 cdfs,159 cdfs,
@@ -230,7 +203,6 @@ pub(super) fn decode_inter_sub8_split4(
230 tpl,203 tpl,
231 );204 );
232 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;205 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
233- let mut is_globalmv = false;
234 let (mv, is_new_mv) = if !not_new {206 let (mv, is_new_mv) = if !not_new {
235 let mut idx = 0usize;207 let mut idx = 0usize;
236 while idx < 2 && stack.entries.len() > idx + 1 {208 while idx < 2 && stack.entries.len() > idx + 1 {
@@ -254,7 +226,6 @@ pub(super) fn decode_inter_sub8_split4(
254 )226 )
255 } else {227 } else {
256 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;228 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
257- is_globalmv = !not_zero;
258 let mv = if !not_zero {229 let mv = if !not_zero {
259 gm_table[(ref_frame - LAST_FRAME) as usize]230 gm_table[(ref_frame - LAST_FRAME) as usize]
260 } else {231 } else {
@@ -276,17 +247,8 @@ pub(super) fn decode_inter_sub8_split4(
276 };247 };
277 // Same print point as the oracle's `EC_MODE_MV` (right after248 // Same print point as the oracle's `EC_MODE_MV` (right after
278 // `assign_mv`), the second rung of the sub-8x8 range ladder.249 // `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- }
287 // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see250 // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see
288 // this function's own doc); `read_mb_interp_filter` still runs.251 // this function's own doc); `read_mb_interp_filter` still runs.
289- let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
290 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame252 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
291 || neighbours.above_ref1[cmi] == Some(ref_frame)253 || neighbours.above_ref1[cmi] == Some(ref_frame)
292 {254 {
@@ -301,18 +263,6 @@ pub(super) fn decode_inter_sub8_split4(
301 } else {263 } else {
302 [3, 3]264 [3, 3]
303 };265 };
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- }
316 // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom266 // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom
317 // `is_nontrans_global_motion` returns 0 for267 // `is_nontrans_global_motion` returns 0 for
318 // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model --268 // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model --
@@ -328,16 +278,6 @@ pub(super) fn decode_inter_sub8_split4(
328 left_filter_ctx,278 left_filter_ctx,
329 false,279 false,
330 );280 );
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- }
341 grid.set(281 grid.set(
342 rmi,282 rmi,
343 cmi,283 cmi,
@@ -387,7 +327,11 @@ pub(super) fn decode_inter_sub8_split4(
387 let pred_y: Vec<u16>;327 let pred_y: Vec<u16>;
388 let sy = if pred_deferred(refpix) {328 let sy = if pred_deferred(refpix) {
389 push_pred(build);329 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+ }
391 } else {335 } else {
392 let mut built: [Vec<u16>; 3] = Default::default();336 let mut built: [Vec<u16>; 3] = Default::default();
393 build(y, u, v, refpix, fctx, &mut built);337 build(y, u, v, refpix, fctx, &mut built);
@@ -429,9 +373,6 @@ pub(super) fn decode_inter_sub8_split4(
429 fctx,373 fctx,
430 )?;374 )?;
431 piece_tx_type = tx_type;375 piece_tx_type = tx_type;
432- if i == 0 {
433- sub0_tx_type = tx_type;
434- }
435 if i == 3 {376 if i == 3 {
436 // `av1_get_tx_type`'s chroma tail scales `blk_row`/`blk_col`377 // `av1_get_tx_type`'s chroma tail scales `blk_row`/`blk_col`
437 // back by the subsampling, but it indexes `xd->tx_type_map`,378 // back by the subsampling, but it indexes `xd->tx_type_map`,
@@ -497,7 +438,18 @@ pub(super) fn decode_inter_sub8_split4(
497 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);438 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
498 let (su, sv) = if pred_deferred(refpix) {439 let (su, sv) = if pred_deferred(refpix) {
499 push_pred(build_c);440 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+ )
501 } else {453 } else {
502 let mut built: [Vec<u16>; 3] = Default::default();454 let mut built: [Vec<u16>; 3] = Default::default();
503 build_c(y, u, v, refpix, fctx, &mut built);455 build_c(y, u, v, refpix, fctx, &mut built);
@@ -681,7 +633,18 @@ pub(super) fn decode_inter_sub8_split4(
681 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);633 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
682 let (su, sv) = if pred_deferred(refpix) {634 let (su, sv) = if pred_deferred(refpix) {
683 push_pred(build_c);635 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+ )
685 } else {648 } else {
686 let mut built: [Vec<u16>; 3] = Default::default();649 let mut built: [Vec<u16>; 3] = Default::default();
687 build_c(y, u, v, refpix, fctx, &mut built);650 build_c(y, u, v, refpix, fctx, &mut built);
@@ -899,7 +862,18 @@ pub(super) fn decode_inter_sub8_split4(
899 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);862 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);
900 let (su, sv) = if pred_deferred(refpix) {863 let (su, sv) = if pred_deferred(refpix) {
901 push_pred(build);864 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+ )
903 } else {877 } else {
904 let mut built: [Vec<u16>; 3] = Default::default();878 let mut built: [Vec<u16>; 3] = Default::default();
905 build(y, u, v, refpix, fctx, &mut built);879 build(y, u, v, refpix, fctx, &mut built);
@@ -977,8 +951,6 @@ pub(super) fn decode_inter_sub8_split4(
977 fctx,951 fctx,
978 )?952 )?
979 .0;953 .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);
982 (ug, vg)954 (ug, vg)
983 };955 };
984 let round_up_even = |n: usize| n.div_ceil(2) * 2;956 let round_up_even = |n: usize| n.div_ceil(2) * 2;
@@ -1031,7 +1003,6 @@ pub(super) fn decode_intra_sub8_leaf(
1031 grid: &mut MiGrid,1003 grid: &mut MiGrid,
1032 group_mi: (usize, usize),1004 group_mi: (usize, usize),
1033 lmi: (usize, usize),1005 lmi: (usize, usize),
1034- // `(bw, bh)`: 8x4 / 4x8 under HORZ/VERT, 4x4 under SPLIT.
1035 (bw, bh): (usize, usize),1006 (bw, bh): (usize, usize),
1036 has_chroma: bool,1007 has_chroma: bool,
1037 skip: bool,1008 skip: bool,
@@ -1039,7 +1010,6 @@ pub(super) fn decode_intra_sub8_leaf(
1039 y: &mut PlaneBuf<'static>,1010 y: &mut PlaneBuf<'static>,
1040 u: &mut PlaneBuf<'static>,1011 u: &mut PlaneBuf<'static>,
1041 v: &mut PlaneBuf<'static>,1012 v: &mut PlaneBuf<'static>,
1042- base_q_idx: u8,
1043 enable_filter_intra: bool,1013 enable_filter_intra: bool,
1044 tx_select: bool,1014 tx_select: bool,
1045 reduced_tx_set: bool,1015 reduced_tx_set: bool,
@@ -1055,19 +1025,9 @@ pub(super) fn decode_intra_sub8_leaf(
1055 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);1025 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
1056 let leaf_above = neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode);1026 let leaf_above = neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode);
1057 let leaf_left = neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode);1027 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");
1059 // `size_group_lookup[BLOCK_8X4] == size_group_lookup[BLOCK_4X8] == 0`1028 // `size_group_lookup[BLOCK_8X4] == size_group_lookup[BLOCK_4X8] == 0`
1060 // (libaom common_data.h:61).1029 // (libaom common_data.h:61).
1061- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
1062 let mode = dec.symbol(&mut cdfs.y_mode[0]);1030 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- }
1071 // No angle delta below 8x8 (`av1_use_angle_delta`), for luma or chroma.1031 // No angle delta below 8x8 (`av1_use_angle_delta`), for luma or chroma.
1072 let angle_delta_y = 0;1032 let angle_delta_y = 0;
1073 let (uv_mode, alpha) = if has_chroma {1033 let (uv_mode, alpha) = if has_chroma {
@@ -1081,20 +1041,10 @@ pub(super) fn decode_intra_sub8_leaf(
1081 // always 4x4-or-smaller, so the predicate stays true and this read1041 // always 4x4-or-smaller, so the predicate stays true and this read
1082 // is unchanged.1042 // is unchanged.
1083 let uv_mode = if cfl_allowed_px(bw, bh, fctx) {1043 let uv_mode = if cfl_allowed_px(bw, bh, fctx) {
1084- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
1085 dec.symbol(&mut cdfs.uv_mode_cfl[mode])1044 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
1086 } else {1045 } else {
1087- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
1088 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])1046 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
1089 };1047 };
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- }
1098 let alpha = if uv_mode == UV_CFL_PRED {1048 let alpha = if uv_mode == UV_CFL_PRED {
1099 Some(read_cfl_alphas(dec, cdfs))1049 Some(read_cfl_alphas(dec, cdfs))
1100 } else {1050 } else {
@@ -1113,24 +1063,8 @@ pub(super) fn decode_intra_sub8_leaf(
1113 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize")1063 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize")
1114 };1064 };
1115 let use_fi = dec.symbol(&mut cdfs.filter_intra[fi_class]);1065 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- }
1124 if use_fi != 0 {1066 if use_fi != 0 {
1125 let fi = dec.symbol(&mut cdfs.filter_intra_mode);1067 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- }
1134 filter_intra = Some(fi);1068 filter_intra = Some(fi);
1135 }1069 }
1136 }1070 }
@@ -1146,16 +1080,8 @@ pub(super) fn decode_intra_sub8_leaf(
1146 // no depth symbol either (sweep of the class fixed at the key-frame pair1080 // no depth symbol either (sweep of the class fixed at the key-frame pair
1147 // path).1081 // path).
1148 let depth = if tx_select && bw != bh && !lossless(fctx) {1082 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);
1150 let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]);1084 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- }
1159 d1085 d
1160 } else {1086 } else {
1161 01087 0
@@ -1180,19 +1106,7 @@ pub(super) fn decode_intra_sub8_leaf(
1180 (lmi.0, lmi.1 + tu)1106 (lmi.0, lmi.1 + tu)
1181 };1107 };
1182 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);1108 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
1183- let tu_reach = tu_reach(1109+ let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, 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- );
1196 if skip {1110 if skip {
1197 let zeros = vec![0i32; 16];1111 let zeros = vec![0i32; 16];
1198 push_intra(1112 push_intra(
@@ -1239,7 +1153,6 @@ pub(super) fn decode_intra_sub8_leaf(
1239 tu_py,1153 tu_py,
1240 4,1154 4,
1241 TX4,1155 TX4,
1242- base_q_idx,
1243 None,1156 None,
1244 filter_intra,1157 filter_intra,
1245 Some(tu_skip_ctx),1158 Some(tu_skip_ctx),
@@ -1295,7 +1208,6 @@ pub(super) fn decode_intra_sub8_leaf(
1295 py,1208 py,
1296 4,1209 4,
1297 TX4,1210 TX4,
1298- base_q_idx,
1299 None,1211 None,
1300 filter_intra,1212 filter_intra,
1301 None,1213 None,
@@ -1345,7 +1257,6 @@ pub(super) fn decode_intra_sub8_leaf(
1345 0,1257 0,
1346 dc_sign_ctx(around.2),1258 dc_sign_ctx(around.2),
1347 TxType::DctDct,1259 TxType::DctDct,
1348- 0,
1349 )?;1260 )?;
1350 let residual = dequant_and_inverse_typed_wh(1261 let residual = dequant_and_inverse_typed_wh(
1351 &levels,1262 &levels,
@@ -1485,7 +1396,6 @@ pub(super) fn decode_intra_sub8_leaf(
1485 u,1396 u,
1486 v,1397 v,
1487 scan4,1398 scan4,
1488- base_q_idx,
1489 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),1399 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
1490 (bw, bh),1400 (bw, bh),
1491 fctx,1401 fctx,
@@ -1655,8 +1565,7 @@ pub(super) fn decode_intra_sub8_leaf(
1655 // At 4:4:4 a TX_4X4 chroma unit IS one mi cell.1565 // At 4:4:4 a TX_4X4 chroma unit IS one mi cell.
1656 let tu_mi = (lmi.0 + oy / MI, lmi.1 + ox / MI);1566 let tu_mi = (lmi.0 + oy / MI, lmi.1 + ox / MI);
1657 let tu_around = neighbours.around_mi(tu_mi, MI);1567 let tu_around = neighbours.around_mi(tu_mi, MI);
1658- let tu_r =1568+ let tu_r = tu_reach(bw, bh, ox, oy, 4, reach_c);
1659- tu_reach(bw, bh, ox, oy, 4, reach_c, px, py, y.width, y.height, fctx);
1660 // The plane block (8x4/4x8) is bigger than the TX_4X41569 // The plane block (8x4/4x8) is bigger than the TX_4X4
1661 // transform, so `get_txb_ctx`'s chroma ctx_offset is 10,1570 // transform, so `get_txb_ctx`'s chroma ctx_offset is 10,
1662 // not 7 -- our chroma tables carry the offset-10 rows at1571 // not 7 -- our chroma tables carry the offset-10 rows at
@@ -1680,7 +1589,6 @@ pub(super) fn decode_intra_sub8_leaf(
1680 py + oy,1589 py + oy,
1681 4,1590 4,
1682 TX4,1591 TX4,
1683- base_q_idx,
1684 None,1592 None,
1685 None,1593 None,
1686 Some(3),1594 Some(3),
@@ -1736,7 +1644,6 @@ pub(super) fn decode_intra_sub8_leaf(
1736 skip_ctx,1644 skip_ctx,
1737 dc_sign_ctx(around.2),1645 dc_sign_ctx(around.2),
1738 uv_tx,1646 uv_tx,
1739- plane,
1740 )?;1647 )?;
1741 let residual = dequant_and_inverse_typed_wh(1648 let residual = dequant_and_inverse_typed_wh(
1742 &levels,1649 &levels,
@@ -1796,7 +1703,6 @@ pub(super) fn decode_intra_sub8_leaf(
1796 unit_y,1703 unit_y,
1797 4,1704 4,
1798 TX4,1705 TX4,
1799- base_q_idx,
1800 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),1706 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1801 None,1707 None,
1802 None,1708 None,
@@ -1821,7 +1727,6 @@ pub(super) fn decode_intra_sub8_leaf(
1821 unit_y,1727 unit_y,
1822 4,1728 4,
1823 TX4,1729 TX4,
1824- base_q_idx,
1825 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),1730 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1826 None,1731 None,
1827 None,1732 None,
@@ -1946,7 +1851,6 @@ pub(super) fn decode_inter_sub8_rect2(
1946 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] =1851 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] =
1947 [None; 2];1852 [None; 2];
1948 let mut first_tx_type = TxType::DctDct;1853 let mut first_tx_type = TxType::DctDct;
1949- let mut sub0_tx_type = TxType::DctDct;
1950 // lane-av1-444: `is_chroma_reference` is unconditional at subsampling 0/01854 // lane-av1-444: `is_chroma_reference` is unconditional at subsampling 0/0
1951 // (av1_common_int.h:1459), so every 8x4/4x8 piece is its own chroma1855 // (av1_common_int.h:1459), so every 8x4/4x8 piece is its own chroma
1952 // reference and codes its own 8x4/4x8 U/V units right after its luma --1856 // 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(
2027 );1931 );
2028 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;1932 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
2029 if !is_inter {1933 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- }
2039 // lane-sub8x4 r2: refusal and bypass lifted -- see the split arm's1934 // lane-sub8x4 r2: refusal and bypass lifted -- see the split arm's
2040 // note above for the gate that proves this leaf.1935 // note above for the gate that proves this leaf.
2041 // Its chroma rule is `is_sub8x8_inter`'s: when the1936 // Its chroma rule is `is_sub8x8_inter`'s: when the
@@ -2056,7 +1951,6 @@ pub(super) fn decode_inter_sub8_rect2(
2056 y,1951 y,
2057 u,1952 u,
2058 v,1953 v,
2059- base_q_idx,
2060 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),1954 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2061 fctx.tx_select_inter.with(std::cell::Cell::get),1955 fctx.tx_select_inter.with(std::cell::Cell::get),
2062 reduced_tx_set,1956 reduced_tx_set,
@@ -2067,12 +1961,6 @@ pub(super) fn decode_inter_sub8_rect2(
2067 }1961 }
2068 continue;1962 continue;
2069 }1963 }
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- }
2076 let ref_frame = read_single_ref(1964 let ref_frame = read_single_ref(
2077 dec,1965 dec,
2078 cdfs,1966 cdfs,
@@ -2119,7 +2007,6 @@ pub(super) fn decode_inter_sub8_rect2(
2119 tpl,2007 tpl,
2120 );2008 );
2121 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;2009 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
2122- let mut is_globalmv = false;
2123 let (mv, is_new_mv) = if !not_new {2010 let (mv, is_new_mv) = if !not_new {
2124 let mut idx = 0usize;2011 let mut idx = 0usize;
2125 while idx < 2 && stack.entries.len() > idx + 1 {2012 while idx < 2 && stack.entries.len() > idx + 1 {
@@ -2143,7 +2030,6 @@ pub(super) fn decode_inter_sub8_rect2(
2143 )2030 )
2144 } else {2031 } else {
2145 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;2032 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
2146- is_globalmv = !not_zero;
2147 let mv = if !not_zero {2033 let mv = if !not_zero {
2148 gm_table[(ref_frame - LAST_FRAME) as usize]2034 gm_table[(ref_frame - LAST_FRAME) as usize]
2149 } else {2035 } else {
@@ -2163,15 +2049,6 @@ pub(super) fn decode_inter_sub8_rect2(
2163 };2049 };
2164 (mv, false)2050 (mv, false)
2165 };2051 };
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];
2175 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame2052 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
2176 || neighbours.above_ref1[cmi] == Some(ref_frame)2053 || neighbours.above_ref1[cmi] == Some(ref_frame)
2177 {2054 {
@@ -2249,17 +2126,6 @@ pub(super) fn decode_inter_sub8_rect2(
2249 leaves.push((0, 0, bw, bh));2126 leaves.push((0, 0, bw, bh));
2250 set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip);2127 set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip);
2251 }2128 }
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- }
2263 grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv);2129 grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv);
2264 piece[i] = Some((ref_frame, mv, h_filter, v_filter));2130 piece[i] = Some((ref_frame, mv, h_filter, v_filter));
2265 // Prediction over the leaf's true footprint, laid out at the group's2131 // Prediction over the leaf's true footprint, laid out at the group's
@@ -2301,7 +2167,11 @@ pub(super) fn decode_inter_sub8_rect2(
2301 let pred_y: Vec<u16>;2167 let pred_y: Vec<u16>;
2302 let sy = if pred_deferred(refpix) {2168 let sy = if pred_deferred(refpix) {
2303 push_pred(build);2169 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+ }
2305 } else {2175 } else {
2306 let mut built: [Vec<u16>; 3] = Default::default();2176 let mut built: [Vec<u16>; 3] = Default::default();
2307 build(y, u, v, refpix, fctx, &mut built);2177 build(y, u, v, refpix, fctx, &mut built);
@@ -2404,9 +2274,6 @@ pub(super) fn decode_inter_sub8_rect2(
2404 if idx == 0 {2274 if idx == 0 {
2405 piece_tx_type = tu_tx_type;2275 piece_tx_type = tu_tx_type;
2406 }2276 }
2407- if idx == 0 && i == 0 {
2408- sub0_tx_type = tu_tx_type;
2409- }
2410 if idx == 0 && i == 1 {2277 if idx == 0 && i == 1 {
2411 // `av1_get_tx_type` indexes `xd->tx_type_map`, which2278 // `av1_get_tx_type` indexes `xd->tx_type_map`, which
2412 // `set_mi_offsets` (av1_common_int.h:1679) re-points to the2279 // `set_mi_offsets` (av1_common_int.h:1679) re-points to the
@@ -2475,7 +2342,18 @@ pub(super) fn decode_inter_sub8_rect2(
2475 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);2342 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
2476 let (su, sv) = if pred_deferred(refpix) {2343 let (su, sv) = if pred_deferred(refpix) {
2477 push_pred(build_c);2344 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+ )
2479 } else {2357 } else {
2480 let mut built: [Vec<u16>; 3] = Default::default();2358 let mut built: [Vec<u16>; 3] = Default::default();
2481 build_c(y, u, v, refpix, fctx, &mut built);2359 build_c(y, u, v, refpix, fctx, &mut built);
@@ -2725,7 +2603,18 @@ pub(super) fn decode_inter_sub8_rect2(
2725 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);2603 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
2726 let (su, sv) = if pred_deferred(refpix) {2604 let (su, sv) = if pred_deferred(refpix) {
2727 push_pred(build_c);2605 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+ )
2729 } else {2618 } else {
2730 let mut built: [Vec<u16>; 3] = Default::default();2619 let mut built: [Vec<u16>; 3] = Default::default();
2731 build_c(y, u, v, refpix, fctx, &mut built);2620 build_c(y, u, v, refpix, fctx, &mut built);
@@ -2940,7 +2829,18 @@ pub(super) fn decode_inter_sub8_rect2(
2940 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);2829 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);
2941 let (su, sv) = if pred_deferred(refpix) {2830 let (su, sv) = if pred_deferred(refpix) {
2942 push_pred(build);2831 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+ )
2944 } else {2844 } else {
2945 let mut built: [Vec<u16>; 3] = Default::default();2845 let mut built: [Vec<u16>; 3] = Default::default();
2946 build(y, u, v, refpix, fctx, &mut built);2846 build(y, u, v, refpix, fctx, &mut built);
@@ -3018,8 +2918,6 @@ pub(super) fn decode_inter_sub8_rect2(
3018 fctx,2918 fctx,
3019 )?2919 )?
3020 .0;2920 .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);
3023 (ug, vg)2921 (ug, vg)
3024 };2922 };
3025 let round_up_even = |n: usize| n.div_ceil(2) * 2;2923 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(
543 ) {543 ) {
544 if let Some(t) = archmage::X64V3Token::summon() {544 if let Some(t) = archmage::X64V3Token::summon() {
545 return super::cdef_simd::filter_block_avx2(545 return super::cdef_simd::filter_block_avx2(
546- t, src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,546+ t,
547- pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,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,
548 );563 );
549 }564 }
550 super::cdef_filter_block_scalar(565 super::cdef_filter_block_scalar(
551- src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,566+ src,
552- pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,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,
553 )582 )
554 }583 }
555 584
@@ -890,8 +919,8 @@ fn filter_intra_classes_carry_their_own_libaom_default_row() {
890 );919 );
891 }920 }
892 }921 }
893-use archmage::SimdToken;
894 use super::*;922 use super::*;
923+use archmage::SimdToken;
895 924
896 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --925 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
897 /// `SCAN_4X16[i]` must name the transpose of the position926 /// `SCAN_4X16[i]` must name the transpose of the position
@@ -1513,7 +1542,6 @@ fn a_skipped_block_decodes_to_pure_prediction() {
1513 DC_PRED,1542 DC_PRED,
1514 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],1543 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
1515 );1544 );
1516- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
1517 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);1545 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
1518 let data = enc.finish();1546 let data = enc.finish();
1519 let decoded = decode_key_frame_tile(1547 let decoded = decode_key_frame_tile(
@@ -1718,7 +1746,6 @@ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
1718 // helpers are `#[cfg(test)]`-private to it).1746 // helpers are `#[cfg(test)]`-private to it).
1719 use crate::probe::run_with_stdin;1747 use crate::probe::run_with_stdin;
1720 1748
1721-
1722 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:01749 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
1723 /// frame's planes, at ffmpeg's own (coded, block-padded) size.1750 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
1724 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {1751 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
@@ -1830,7 +1857,8 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
1830 "-of",1857 "-of",
1831 "csv=p=0",1858 "csv=p=0",
1832 ])1859 ])
1833- .arg(&path).output()1860+ .arg(&path)
1861+ .output()
1834 .expect("ffprobe failed to run");1862 .expect("ffprobe failed to run");
1835 let _ = std::fs::remove_file(&path);1863 let _ = std::fs::remove_file(&path);
1836 assert!(1864 assert!(
crates/ec-av1/src/encode/coef.rsmodified+40 -31
@@ -962,7 +962,13 @@ impl Plane<'_> {
962 }962 }
963 963
964 /// Puts a snapshot back.964 /// 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+ ) {
966 for row in 0..side {972 for row in 0..side {
967 self.reconstruction[(y + row) * self.width + x..][..side]973 self.reconstruction[(y + row) * self.width + x..][..side]
968 .copy_from_slice(&saved.0[row * side..][..side]);974 .copy_from_slice(&saved.0[row * side..][..side]);
@@ -1080,19 +1086,20 @@ impl Plane<'_> {
1080 })1086 })
1081 .collect();1087 .collect();
1082 if let Some(k) = search.top_k1088 if let Some(k) = search.top_k
1083- && k < scored.len() {1089+ && k < scored.len()
1084- let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);1090+ {
1085- let dc_entry = dc_pos.map(|i| scored.remove(i));1091+ let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1086- scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));1092+ let dc_entry = dc_pos.map(|i| scored.remove(i));
1087- scored.truncate(if dc_entry.is_some() {1093+ scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1088- k.saturating_sub(1)1094+ scored.truncate(if dc_entry.is_some() {
1089- } else {1095+ k.saturating_sub(1)
1090- k1096+ } else {
1091- });1097+ k
1092- if let Some(dc_entry) = dc_entry {1098+ });
1093- scored.push(dc_entry);1099+ if let Some(dc_entry) = dc_entry {
1094- }1100+ scored.push(dc_entry);
1095 }1101 }
1102+ }
1096 let ranking: Vec<(f64, u8)> = if census_on() {1103 let ranking: Vec<(f64, u8)> = if census_on() {
1097 scored1104 scored
1098 .iter()1105 .iter()
@@ -1179,8 +1186,6 @@ impl Plane<'_> {
1179 trial = candidate;1186 trial = candidate;
1180 }1187 }
1181 }1188 }
1182- ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
1183- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1184 }1189 }
1185 // lane-txset: the block's own transform type, searched on the mode1190 // lane-txset: the block's own transform type, searched on the mode
1186 // and angle the trials above settled -- the same ordering the angle1191 // and angle the trials above settled -- the same ordering the angle
@@ -1405,7 +1410,8 @@ pub(super) const HAS_TR_8X16: [u8; 16] = [
1405 /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).1410 /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1406 pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];1411 pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
1407 /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).1412 /// `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];
1409 /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).1415 /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1410 pub(super) const HAS_BL_16X8: [u8; 16] = [1416 pub(super) const HAS_BL_16X8: [u8; 16] = [
1411 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,1417 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
@@ -1785,18 +1791,6 @@ impl Reach {
1785 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))1791 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
1786 }1792 }
1787 1793
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-
1800 pub(crate) fn vert_ab_partition() -> VertAbGuard {1794 pub(crate) fn vert_ab_partition() -> VertAbGuard {
1801 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))1795 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
1802 }1796 }
@@ -1814,7 +1808,12 @@ impl Reach {
1814 /// row of a superblock reads into the superblock above, which is decoded;1808 /// row of a superblock reads into the superblock above, which is decoded;
1815 /// the rightmost column would read into the superblock to the right, which1809 /// the rightmost column would read into the superblock to the right, which
1816 /// is not; and everything between is the table's to answer.1810 /// 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 {
1818 let (row, col, per_side) = Self::position(side, x, y, fctx);1817 let (row, col, per_side) = Self::position(side, x, y, fctx);
1819 if row == 0 {1818 if row == 0 {
1820 return true;1819 return true;
@@ -1851,7 +1850,12 @@ impl Reach {
1851 /// reads into the superblock to its left, which is decoded only as far1850 /// reads into the superblock to its left, which is decoded only as far
1852 /// down as its own bottom; the bottom row would read into the superblock1851 /// down as its own bottom; the bottom row would read into the superblock
1853 /// below, which is not decoded at all; and the table answers the rest.1852 /// 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 {
1855 let (row, col, per_side) = Self::position(side, x, y, fctx);1859 let (row, col, per_side) = Self::position(side, x, y, fctx);
1856 if col == 0 {1860 if col == 0 {
1857 return row * side + side < reach_sb_px(fctx);1861 return row * side + side < reach_sb_px(fctx);
@@ -2032,7 +2036,12 @@ pub(super) fn obmc_min_side() -> usize {
2032 /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the2036 /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
2033 /// search pay it, so the alphabet cancels out of a comparison and only its2037 /// search pay it, so the alphabet cancels out of a comparison and only its
2034 /// per-value spread decides.2038 /// 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 {
2036 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {2045 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
2037 return 0.0;2046 return 0.0;
2038 };2047 };
crates/ec-av1/src/encode/frame.rsmodified+50 -37
@@ -52,7 +52,8 @@ pub(super) fn deltaq_res_log2() -> Option<u8> {
52 /// sets it holds [`crate::speed::knob_write`], the same exclusive lock the52 /// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
53 /// speed presets take, because the streams every other test pins move under53 /// speed presets take, because the streams every other test pins move under
54 /// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).54 /// 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);
56 57
57 /// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.58 /// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
58 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates59 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -270,13 +271,8 @@ pub(super) fn dq_summary(offsets: &[i32]) -> String {
270 /// grid that is one flat value, i.e. on no delta_q at all). Process-global271 /// grid that is one flat value, i.e. on no delta_q at all). Process-global
271 /// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which272 /// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
272 /// keeps the LARGEST count seen since the last read.273 /// 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+pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize =
274-275+ std::sync::atomic::AtomicUsize::new(0);
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-}
280 276
281 /// This superblock's search state: the quantizer it is coded at, and the277 /// This superblock's search state: the quantizer it is coded at, and the
282 /// lambda that quantizer implies. RD lambda goes as the square of the step,278 /// 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
404 /// the left/above winners, first-best tie-break. Built once on the frame's400 /// the left/above winners, first-best tie-break. Built once on the frame's
405 /// own thread and read-only afterwards, so it cannot make a tile's bytes401 /// own thread and read-only afterwards, so it cannot make a tile's bytes
406 /// depend on the thread count.402 /// 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)> {
408 let (cells_x, cells_y) = (width / 16, height / 16);409 let (cells_x, cells_y) = (width / 16, height / 16);
409 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {410 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
410 let (sx, sy) = (bx as i32 + mx, by as i32 + my);411 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
823 ] {824 ] {
824 let mv = (from.0 + dy * step, from.1 + dx * step);825 let mv = (from.0 + dy * step, from.1 + dx * step);
825 if let Some(s) = sad(r, bx, by, mv)826 if let Some(s) = sad(r, bx, by, mv)
826- && s.0 < best.0 {827+ && s.0 < best.0
827- best = s;828+ {
828- centre = mv;829+ best = s;
829- }830+ centre = mv;
831+ }
830 }832 }
831 step /= 2;833 step /= 2;
832 }834 }
@@ -1288,28 +1290,29 @@ pub(crate) fn encode_inter_frame(
1288 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever1290 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
1289 // off, and the census then prices the default `res = 4` grid).1291 // off, and the census then prices the default `res = 4` grid).
1290 if dq_census()1292 if dq_census()
1291- && let Some(f) = &tpl_factors {1293+ && let Some(f) = &tpl_factors
1292- let res = deltaq_res.unwrap_or(4);1294+ {
1293- let off = |libaom: Option<f64>| -> Vec<i32> {1295+ let res = deltaq_res.unwrap_or(4);
1294- (0..sb_cols * _sb_rows)1296+ let off = |libaom: Option<f64>| -> Vec<i32> {
1295- .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))1297+ (0..sb_cols * _sb_rows)
1296- .collect()1298+ .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
1297- };1299+ .collect()
1298- let strength = dq_tpl_strength(dq_level);1300+ };
1299- let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));1301+ let strength = dq_tpl_strength(dq_level);
1300- let coded = match (deltaq_res.is_some(), strength) {1302+ let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
1301- (false, _) => "none".to_string(),1303+ let coded = match (deltaq_res.is_some(), strength) {
1302- (true, None) => "ours".to_string(),1304+ (false, _) => "none".to_string(),
1303- (true, Some(k)) => format!("libaom k={k}"),1305+ (true, None) => "ours".to_string(),
1304- };1306+ (true, Some(k)) => format!("libaom k={k}"),
1305- eprintln!(1307+ };
1306- "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",1308+ eprintln!(
1307- sb_cols * _sb_rows,1309+ "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
1308- r_frame.unwrap_or(f64::NAN),1310+ sb_cols * _sb_rows,
1309- dq_summary(&ours),1311+ r_frame.unwrap_or(f64::NAN),
1310- dq_summary(&aom),1312+ dq_summary(&ours),
1311- );1313+ dq_summary(&aom),
1312- }1314+ );
1315+ }
1313 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {1316 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
1314 header.delta.q_present = true;1317 header.delta.q_present = true;
1315 header.delta.q_res = res.trailing_zeros() as u8;1318 header.delta.q_res = res.trailing_zeros() as u8;
@@ -2332,9 +2335,19 @@ pub(crate) fn encode_inter_frame(
2332 // rectangles partition the frame, so the order does not change the bytes).2335 // rectangles partition the frame, so the order does not change the bytes).
2333 let mut searched_blocks = Vec::new();2336 let mut searched_blocks = Vec::new();
2334 for (tile_blocks, pixels) in search_tiles(layout.count(), fctx, search_tile)? {2337 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+ );
2336 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {2344 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+ );
2338 }2351 }
2339 searched_blocks.push(tile_blocks);2352 searched_blocks.push(tile_blocks);
2340 }2353 }
crates/ec-av1/src/encode/inter_search.rsmodified+44 -39
@@ -212,7 +212,8 @@ pub(super) fn arfmode() -> u8 {
212 }212 }
213 213
214 /// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.214 /// [`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);
216 217
217 /// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a218 /// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
218 /// process constant ([`crate::envflags`]), so an in-process witness needs219 /// process constant ([`crate::envflags`]), so an in-process witness needs
@@ -279,11 +280,6 @@ thread_local! {
279 const { std::cell::Cell::new(None) };280 const { std::cell::Cell::new(None) };
280 }281 }
281 282
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-
287 /// The default: unpruned, thirteen full trials per block, same as before this283 /// The default: unpruned, thirteen full trials per block, same as before this
288 /// lever. Set from the sweep in the lane report if the quality gate clears it.284 /// lever. Set from the sweep in the lane report if the quality gate clears it.
289 pub(crate) const PRUNE_TOP_K: Option<usize> = None;285 pub(crate) const PRUNE_TOP_K: Option<usize> = None;
@@ -317,11 +313,6 @@ thread_local! {
317 const { std::cell::Cell::new(None) };313 const { std::cell::Cell::new(None) };
318 }314 }
319 315
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-
325 /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`316 /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
326 /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the317 /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
327 /// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes318 /// 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) {
374 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));365 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
375 }366 }
376 367
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-
392 /// One mode's coding of one block, before it is committed.368 /// One mode's coding of one block, before it is committed.
393 #[derive(Clone)]369 #[derive(Clone)]
394 pub(super) struct Trial {370 pub(super) struct Trial {
@@ -526,7 +502,11 @@ where
526 /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`502 /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
527 /// by design) and moved into the worker, exactly as the decoder's filter bands503 /// by design) and moved into the worker, exactly as the decoder's filter bands
528 /// do it through [`crate::par::scope`].504 /// 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>>
530 where510 where
531 T: Send,511 T: Send,
532 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,512 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
@@ -600,7 +580,11 @@ pub(super) struct TilePixels {
600 580
601 /// The rectangle `[x0, x1) x [y0, y1)` of a plane with `stride`, copied out as581 /// The rectangle `[x0, x1) x [y0, y1)` of a plane with `stride`, copied out as
602 /// its rows back to back.582 /// 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> {
604 let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0));588 let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0));
605 for y in y0..y1 {589 for y in y0..y1 {
606 out.extend_from_slice(&plane[y * stride + x0..y * stride + x1]);590 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
610 594
611 /// The inverse of [`take_rect`]: writes `rows` (as `take_rect` produced them)595 /// The inverse of [`take_rect`]: writes `rows` (as `take_rect` produced them)
612 /// back into the rectangle of `plane`.596 /// 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+) {
614 let w = x1 - x0;603 let w = x1 - x0;
615 for (row, y) in (y0..y1).enumerate() {604 for (row, y) in (y0..y1).enumerate() {
616 plane[y * stride + x0..y * stride + x1].copy_from_slice(&rows[row * w..(row + 1) * w]);605 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
622 /// tables the frame stores (spec 7.20), which is what611 /// tables the frame stores (spec 7.20), which is what
623 /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops612 /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
624 /// below publish.613 /// 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 {
626 ec_av1_syntax::TileInfo {618 ec_av1_syntax::TileInfo {
627 uniform_spacing: true,619 uniform_spacing: true,
628 cols: layout.cols(),620 cols: layout.cols(),
@@ -1380,9 +1372,19 @@ pub(crate) fn encode_key_frame_inner(
1380 let searched = search_tiles(layout.count(), fctx, search_tile)?;1372 let searched = search_tiles(layout.count(), fctx, search_tile)?;
1381 let mut searched_coded = Vec::with_capacity(searched.len());1373 let mut searched_coded = Vec::with_capacity(searched.len());
1382 for (coded, pixels) in searched {1374 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+ );
1384 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {1381 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+ );
1386 }1388 }
1387 searched_coded.push(coded);1389 searched_coded.push(coded);
1388 }1390 }
@@ -2104,7 +2106,8 @@ pub(super) fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64>
2104 /// always), the shape [`set_frame_interp`] has: the witness that has to see2106 /// always), the shape [`set_frame_interp`] has: the witness that has to see
2105 /// `mv_hp` symbols coded turns it on through this while holding2107 /// `mv_hp` symbols coded turns it on through this while holding
2106 /// [`crate::speed::knob_write`].2108 /// [`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);
2108 2111
2109 /// Sets [`HP_MV_OVERRIDE`]; `None` clears it.2112 /// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
2110 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates2113 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -4448,9 +4451,10 @@ pub(super) fn search_inter_block(
4448 planes,4451 planes,
4449 (reference.width, reference.height),4452 (reference.width, reference.height),
4450 fctx,4453 fctx,
4451- ) {4454+ )
4452- candidates.push((1, pred));4455+ {
4453- }4456+ candidates.push((1, pred));
4457+ }
4454 if warp_alphabet4458 if warp_alphabet
4455 && let Some(pred) = warp_prediction(4459 && let Some(pred) = warp_prediction(
4456 grid,4460 grid,
@@ -4462,9 +4466,10 @@ pub(super) fn search_inter_block(
4462 info.ref_frame,4466 info.ref_frame,
4463 planes,4467 planes,
4464 fctx,4468 fctx,
4465- ) {4469+ )
4466- candidates.push((2, pred));4470+ {
4467- }4471+ candidates.push((2, pred));
4472+ }
4468 for (motion, pred) in candidates {4473 for (motion, pred) in candidates {
4469 let luma_trial = luma.code_from_prediction(4474 let luma_trial = luma.code_from_prediction(
4470 x,4475 x,
crates/ec-av1/src/encode/mod.rsmodified+0 -50
@@ -821,12 +821,6 @@ fn rectres() -> bool {
821 static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =821 static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
822 std::sync::atomic::AtomicBool::new(false);822 std::sync::atomic::AtomicBool::new(false);
823 823
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-
830 /// How many rect/AB pieces the search left WITH a residual rather than824 /// How many rect/AB pieces the search left WITH a residual rather than
831 /// skipped, since the last [`take_b128_rectres_hits`] (class825 /// skipped, since the last [`take_b128_rectres_hits`] (class
832 /// `gate-blind-to-feature`).826 /// `gate-blind-to-feature`).
@@ -981,12 +975,6 @@ pub fn take_b128_vert_hits() -> usize {
981 /// RD there prefers one whole block; the gate census is the unforced count.975 /// RD there prefers one whole block; the gate census is the unforced count.
982 static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);976 static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
983 977
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-
990 /// lane-ab128: whether the 128 superblock root offers its four AB shapes --978 /// lane-ab128: whether the 128 superblock root offers its four AB shapes --
991 /// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one979 /// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
992 /// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128980 /// 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] {
1029 /// prefers one whole block).1017 /// prefers one whole block).
1030 static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);1018 static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1031 1019
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-
1038 /// lane-ab128: the three pieces of an AB shape at a 128 root, in the order1020 /// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1039 /// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm1021 /// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1040 /// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =1022 /// 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 =
1073 /// for content on which the root also wins its own comparison.1055 /// for content on which the root also wins its own comparison.
1074 static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);1056 static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1075 1057
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-
1090 /// How many 128 roots came out cheaper WITH a residual than skipped, since1058 /// How many 128 roots came out cheaper WITH a residual than skipped, since
1091 /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).1059 /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1092 static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);1060 static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -1475,12 +1443,6 @@ fn partition_hit(which: usize) {
1475 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);1443 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1476 }1444 }
1477 1445
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-
1484 /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full1446 /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1485 /// rate-distortion trials the block search actually runs, by kind, and where1447 /// rate-distortion trials the block search actually runs, by kind, and where
1486 /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by1448 /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
@@ -2002,12 +1964,6 @@ thread_local! {
2002 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };1964 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
2003 }1965 }
2004 1966
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-
2011 thread_local! {1967 thread_local! {
2012 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence1968 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
2013 /// header offers the per-frame `allow_screen_content_tools` bit at all.1969 /// header offers the per-frame `allow_screen_content_tools` bit at all.
@@ -2043,12 +1999,6 @@ thread_local! {
2043 const { std::cell::Cell::new(None) };1999 const { std::cell::Cell::new(None) };
2044 }2000 }
2045 2001
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-
2052 #[cfg(test)]2002 #[cfg(test)]
2053 pub(crate) fn force_screen(value: Option<bool>) {2003 pub(crate) fn force_screen(value: Option<bool>) {
2054 SCREEN_FORCE.with(|c| c.set(value));2004 SCREEN_FORCE.with(|c| c.set(value));
crates/ec-av1/src/encode/more_tests.rsmodified+664 -1228
@@ -1,1260 +1,696 @@
1-use super::*;
2 use super::tests::*;1 use super::tests::*;
2+use super::*;
3 3
4-4+#[test]
5-5+fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
6- /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two6+ let _knobs = crate::speed::knob_read();
7- /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.7+ let fctx = &crate::decode::FrameCtx::for_encoder();
8- /// Five passes over the same `testsrc2` clip8+ // 256x128, not the 128x64 this started at: once a leaf could search
9- /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`9+ // its second reference (lane-av1comp4) the small card's every
10- /// uses: each shape forced at every root ([`force_b128_ab`]), so every10+ // eligible block went to a compound winner, which commits its flat
11- /// context and every visit order the shape reads is exercised rather than11+ // transform, and the split below stopped firing on content that
12- /// the handful the RD would pick, and then an UNFORCED pass whose12+ // still splits at every larger size ([[gate-blind-to-feature]] --
13- /// per-shape count is REPORTED (it is the number the gate rows are read13+ // the guard is right, the fixture had shrunk under it).
14- /// against).14+ let (width, height) = (256usize, 128usize);
15- ///15+ let pictures: Vec<Picture> = (0..5)
16- /// Each pass is sample-exact against the encoder's own reconstruction16+ .map(|i| panned_test_card(width, height, i * 3))
17- /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch17+ .collect();
18- /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED18+ let _ = take_inter_tx_split_hits();
19- /// before this lane by construction: `write_sb128_root` could only name19+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20- /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.20+ let raw = take_inter_tx_split_hits();
21- ///21+ // Summed over the four block classes the census keys on (leaf/32x32 x
22- /// Runs only inside `superblock_size_global_suite`.22+ // single/compound): this assert is about the split firing at all.
23- pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {23+ let split = [
24- let _knobs = crate::speed::knob_write();24+ raw.iter().step_by(2).sum::<usize>(),
25- force_sb128(true);25+ raw.iter().skip(1).step_by(2).sum::<usize>(),
26- let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));26+ ];
27- std::fs::create_dir_all(&dir).unwrap();27+ eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
28- let clip = dir.join("testsrc2-1280x768.y4m");28+ // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
29- let ok = ec_testkit::ffmpeg()29+ // content splits -- a green round trip in which the split never fires
30- .args(["-v", "error", "-y", "-f", "lavfi"])30+ // would prove only the flat path.
31- .args(["-i", "testsrc2=size=1280x768:rate=24"])31+ if tx_select() && tx_select_inter() {
32- .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])32+ assert!(split[1] > 0, "the inter var-tx split never fired");
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- );
112 }33 }
113-34+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
114- #[test]35+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
115- fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {36+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
116- let _knobs = crate::speed::knob_read();37+ let recon = &frame.reconstruction;
117- let fctx = &crate::decode::FrameCtx::for_encoder();38+ for (plane, got, want, stride) in [
118- // 256x128, not the 128x64 this started at: once a leaf could search39+ ("luma", &dec.y, &recon.y, width),
119- // its second reference (lane-av1comp4) the small card's every40+ ("U", &dec.u, &recon.u, width / 2),
120- // eligible block went to a compound winner, which commits its flat41+ ("V", &dec.v, &recon.v, width / 2),
121- // transform, and the split below stopped firing on content that42+ ] {
122- // still splits at every larger size ([[gate-blind-to-feature]] --43+ assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
123- // the guard is right, the fixture had shrunk under it).44+ if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
124- let (width, height) = (256usize, 128usize);45+ panic!(
125- let pictures: Vec<Picture> = (0..5)46+ "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
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 \
157 reconstruction {} ({} of {} samples differ)",47 reconstruction {} ({} of {} samples differ)",
158- at % stride,48+ at % stride,
159- at / stride,49+ at / stride,
160- got[at],50+ got[at],
161- want[at],51+ want[at],
162- got.iter().zip(want).filter(|(a, b)| a != b).count(),52+ got.iter().zip(want).filter(|(a, b)| a != b).count(),
163- got.len(),53+ got.len(),
164- );54+ );
165- }
166 }55 }
167 }56 }
168 }57 }
169-58+}
170- /// The rate term the mode search ranks every decision by has to be the59+
171- /// rate the writer then spends. The search prices a block's coefficients60+/// The rate term the mode search ranks every decision by has to be the
172- /// through `tile::coeff_bits` -- the writer's own symbol chain, but61+/// rate the writer then spends. The search prices a block's coefficients
173- /// against the default CDFs a tile starts from and the contexts of a62+/// through `tile::coeff_bits` -- the writer's own symbol chain, but
174- /// block whose neighbours coded nothing -- while the tile writer codes63+/// against the default CDFs a tile starts from and the contexts of a
175- /// them against a state that has been adapting all frame (the64+/// block whose neighbours coded nothing -- while the tile writer codes
176- /// price-the-narrowing class). This measures that drift: the sum of what65+/// them against a state that has been adapting all frame (the
177- /// the search paid for the coefficients it kept, against the bytes the66+/// price-the-narrowing class). This measures that drift: the sum of what
178- /// writer actually emitted for the whole tile (which also carries the67+/// the search paid for the coefficients it kept, against the bytes the
179- /// partition/mode/skip/mv syntax the sum leaves out, so the writer is68+/// writer actually emitted for the whole tile (which also carries the
180- /// expected to be the larger of the two).69+/// partition/mode/skip/mv syntax the sum leaves out, so the writer is
181- #[test]70+/// expected to be the larger of the two).
182- fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {71+#[test]
183- let _knobs = crate::speed::knob_read();72+fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
184- let fctx = &crate::decode::FrameCtx::for_encoder();73+ let _knobs = crate::speed::knob_read();
185- let (width, height) = (256usize, 128usize);74+ let fctx = &crate::decode::FrameCtx::for_encoder();
186- let pictures: Vec<Picture> = (0..5)75+ let (width, height) = (256usize, 128usize);
187- .map(|i| panned_test_card(width, height, i * 2))76+ let pictures: Vec<Picture> = (0..5)
188- .collect();77+ .map(|i| panned_test_card(width, height, i * 2))
189- let _ = take_predicted_bits();78+ .collect();
190- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();79+ let _ = take_predicted_bits();
191- let predicted = take_predicted_bits();80+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
192- assert_eq!(predicted.len(), encoded.frames.len());81+ let predicted = take_predicted_bits();
193-82+ assert_eq!(predicted.len(), encoded.frames.len());
194- eprintln!("frame predicted bits written bits drift");83+
195- // Split by sign: a NEGATIVE drift is the search OVER-pricing (the84+ eprintln!("frame predicted bits written bits drift");
196- // defect this gate exists to catch), a positive one is the written85+ // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
197- // side carrying syntax the coefficient sum leaves out -- and since86+ // defect this gate exists to catch), a positive one is the written
198- // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual87+ // side carrying syntax the coefficient sum leaves out -- and since
199- // on that side, so the two directions no longer share a bound.88+ // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
200- let mut worst_over: f64 = 0.0;89+ // on that side, so the two directions no longer share a bound.
201- let mut worst_under: f64 = 0.0;90+ let mut worst_over: f64 = 0.0;
202- // The census is per CODED frame, so it is zipped in coding order --91+ let mut worst_under: f64 = 0.0;
203- // which is not display order under a pyramid.92+ // The census is per CODED frame, so it is zipped in coding order --
204- let coded: Vec<&Encoded> = encoded93+ // which is not display order under a pyramid.
205- .coding_order94+ let coded: Vec<&Encoded> = encoded
206- .iter()95+ .coding_order
207- .map(|&i| &encoded.frames[i])96+ .iter()
208- .collect();97+ .map(|&i| &encoded.frames[i])
209- for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {98+ .collect();
210- let written = frame.tile.len() as f64 * 8.0;99+ for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
211- let drift = (written - bits) / written;100+ let written = frame.tile.len() as f64 * 8.0;
212- worst_over = worst_over.max(-drift);101+ let drift = (written - bits) / written;
213- // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at102+ worst_over = worst_over.max(-drift);
214- // all (150-250 bits of tile, nearly all of it partition/mode/mv103+ // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
215- // syntax the coefficient sum never counts), so its ratio measures104+ // all (150-250 bits of tile, nearly all of it partition/mode/mv
216- // that floor rather than any drift. Frames under 512 written bits105+ // syntax the coefficient sum never counts), so its ratio measures
217- // are left out of the under-price bound for that reason; the106+ // that floor rather than any drift. Frames under 512 written bits
218- // over-price bound -- the defect direction, where the search pays107+ // are left out of the under-price bound for that reason; the
219- // MORE than the writer -- still covers every frame.108+ // over-price bound -- the defect direction, where the search pays
220- if written >= 512.0 {109+ // MORE than the writer -- still covers every frame.
221- worst_under = worst_under.max(drift);110+ if written >= 512.0 {
222- }111+ worst_under = worst_under.max(drift);
223- eprintln!(
224- "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
225- drift * 100.0
226- );
227 }112 }
228- // Measured 2026-09-06 on this sequence: -13.5% at the key frame,113+ eprintln!(
229- // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search114+ "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
230- // over-prices every frame but the last (its sum EXCLUDES the115+ drift * 100.0
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
282 );116 );
283 }117 }
284-118+ // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
285- /// The census behind step (1) of the pricer lane: for every transform119+ // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
286- /// block the writer really codes, what the search priced those levels at120+ // over-prices every frame but the last (its sum EXCLUDES the
287- /// against what the writer spent on them, split by table set and non-zero121+ // partition/mode/skip/mv syntax the written side carries, so the true
288- /// count. One average hides the interesting part -- the classes the122+ // coefficient over-price is larger still): the writer's CDFs adapt to
289- /// estimate is systematically wrong about (all-zero blocks, the123+ // the content while the search's stay at the defaults. The bound is
290- /// one-coefficient blocks the inter search lives on) -- so the split is124+ // set just above the worst measured point -- a widening drift is the
291- /// printed and only the total is asserted on.125+ // thing this gate exists to catch.
292- #[test]126+ assert!(
293- fn pricer_error_census_by_block_class() {127+ worst_over <= 0.16,
294- let _knobs = crate::speed::knob_read();128+ "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
295- let fctx = &crate::decode::FrameCtx::for_encoder();129+ worst_over * 100.0
296- let (width, height) = (256usize, 128usize);130+ );
297- let pictures: Vec<Picture> = (0..5)131+ // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
298- .map(|i| panned_test_card(width, height, i * 2))132+ // the worst inter frame, where nearly every block now codes an MV
299- .collect();133+ // residual and a reference the coefficient sum never counts. Re-measured
300- crate::tile::pricer_census_on();134+ // at +29.6% once the encoder's grid published compound blocks properly
301- let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();135+ // (compound share 8.8% -> 11.5%): a compound block carries a second
302- let rows = crate::tile::take_pricer_census();136+ // reference tree, a compound mode symbol and -- for the half-new modes
303- assert!(!rows.is_empty(), "the census saw no transform block");137+ // -- an MV residual, none of which the coefficient sum counts.
304-138+ // lane-av1txbits: pricing against the tables the frame's writer really
305- println!("| set | nz | blocks | priced bits | written bits | error |");139+ // starts from collapses the over-price above to nothing, so the whole
306- println!("|---|---|---|---|---|---|");140+ // remaining gap is the syntax the coefficient sum leaves out. That is
307- let (mut priced_all, mut written_all) = (0.0, 0.0);141+ // the default on a non-screen frame since lane-av1price2 (this
308- for ((set, bucket), (blocks, priced, written)) in &rows {142+ // fixture is one), and it reads +32.6% here.
309- priced_all += priced;143+ // lane-av1obmc: every eligible single-reference inter block now also
310- written_all += written;144+ // carries a `motion_mode` symbol the coefficient sum never counts,
311- println!(145+ // and an OBMC block carries the more expensive of the two values --
312- "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",146+ // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
313- crate::tile::census_bucket_label(*bucket),147+ // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
314- if *written > 0.0 {148+ // decisions, so this bound and the byte pins above FAIL BY DESIGN
315- (priced - written) / written * 100.0149+ // under it; the default path (no motion_mode syntax at all) is the
316- } else {150+ // one they are measured on.
317- 0.0151+ // lane-av1pyrdef: `encode_sequence` codes this fixture under the
318- }152+ // coding pyramid now, so the five frames are a key frame, a hidden
319- );153+ // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
320- }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;
321 println!(201 println!(
322- "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",202+ "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
323- rows.values().map(|r| r.0).sum::<u64>(),203+ crate::tile::census_bucket_label(*bucket),
324- (priced_all - written_all) / written_all * 100.0204+ if *written > 0.0 {
325- );205+ (priced - written) / written * 100.0
326- assert!(written_all > 0.0);206+ } else {
327- }207+ 0.0
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- )),
514 }208 }
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"),
548 );209 );
549 }210 }
550-211+ println!(
551- /// First differing sample between two pictures, as212+ "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
552- /// `(plane, index, left, right)` -- so a gate failure names the plane and213+ rows.values().map(|r| r.0).sum::<u64>(),
553- /// the sample instead of just "differs". A length difference counts as a214+ (priced_all - written_all) / written_all * 100.0
554- /// mismatch of that plane at the first index past the shorter one.215+ );
555- pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {216+ assert!(written_all > 0.0);
556- for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {217+}
557- if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {218+
558- return Some((plane, i, i64::from(l[i]), i64::from(r[i])));219+/// Low motion has to actually buy something: at least one inter frame of
559- }220+/// a panning sequence has to cost fewer bytes than the key frame that
560- if l.len() != r.len() {221+/// starts it, and the inter-block share it prints has to be non-zero --
561- return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));222+/// a search that never picks an inter mode would still pass a rate gate
562- }223+/// on a picture with no motion in it (the class this repo calls
563- }224+/// gate-blind-to-feature), so the share is printed even though it is not
564- None225+/// asserted on beyond being reachable at all.
565- }226+#[test]
566-227+fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
567- /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR228+ let _knobs = crate::speed::knob_read();
568- /// comes from ffmpeg's decode of our own stream, and at EVERY point the229+ let fctx = &crate::decode::FrameCtx::for_encoder();
569- /// stream is decoded twice -- by ffmpeg and by our own230+ let (width, height) = (256usize, 128usize);
570- /// [`crate::stream::decode_stream`] -- and all three pictures (encoder231+ let pictures: Vec<Picture> = (0..5)
571- /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact232+ .map(|i| panned_test_card(width, height, i * 2))
572- /// in Y, U and V over every shown frame in display order. That is itself233+ .collect();
573- /// a gate: it proves the bitstream says what the encoder thinks, in the234+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
574- /// only two decoders that read it.235+
575- pub(super) fn our_ladder(236+ let key_bytes = encoded.frames[0].stream.len();
576- name: &str,237+ eprintln!("frame bytes inter share");
577- source: &[Picture],238+ for (i, frame) in encoded.frames.iter().enumerate() {
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`).
650 eprintln!(239 eprintln!(
651- "{name}: sequence, pyramid requested {:?} effective {:?}",240+ "{i:5} {:5} {:11.2}",
652- crate::encoder::Pyramid::from_env(),241+ frame.stream.len(),
653- last_sequence_pyramid(),242+ frame.inter_block_share
654 );243 );
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)
752 }244 }
753-245+ assert!(
754- /// Byte-exactness gate for encoder work that is meant to change only246+ encoded.frames[1..]
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
911 .iter()247 .iter()
912- .map(|&(q, _, _)| {248+ .any(|f| f.stream.len() < key_bytes),
913- let e = encode_sequence(&source, q, 0.5).unwrap();249+ "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
914- (q, e.stream.len(), fnv(&e.stream))250+ );
915- })251+ assert!(
916- .collect();252+ encoded.frames[1..]
917- crate::speed::set_speed(was);253+ .iter()
918- for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {254+ .any(|f| f.inter_block_share > 0.0),
919- assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");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])));
920 }316 }
921- }317+ if l.len() != r.len() {
922-318+ return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
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- );
931 }319 }
932 }320 }
933-321+ None
934- /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,322+}
935- /// split by block class in lane-av1txdepth): depth 0 is one transform over323+
936- /// the whole block, 1 its four halves; the classes are the 16x16/8x8324+/// Byte-exactness gate for encoder work that is meant to change only
937- /// leaves and the 32x32 root, each single-reference or compound. A class325+/// how long the encoder takes.
938- /// with no counts at all never reached `commit_inter_luma` -- which is326+///
939- /// what its knob being off looks like (class `gate-blind-to-feature`).327+/// The BD gate above measures quality, which a speed lane can move by a
940- pub(super) fn print_inter_tx_census(name: &str) {328+/// hair without failing anything; this pins the streams themselves.
941- let splits = take_inter_tx_split_hits();329+/// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
942- let total: usize = splits.iter().sum();330+/// `cdef_idx` literals and per-unit loop restoration syntax are new bits
943- let row = |label: &str, base: usize| {331+/// in the tile) and again on lane-av1mv's merge of it: an extra
944- let (n0, n1) = (splits[base], splits[base + 1]);332+/// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
945- format!(333+/// above, not by this pin. Re-pinned on lane-av1price2: the search now
946- "{label} 0={n0} 1={n1} ({:.1}% split)",334+/// prices coefficients against the tables the frame's writer really
947- 100.0 * n1 as f64 / (n0 + n1).max(1) as f64335+/// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
948- )336+/// decision change the BD gate judges. Re-pinned again on
949- };337+/// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
950- eprintln!(338+/// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
951- "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",339+/// is the same kind of decision change. Re-pinned on lane-av1lambda:
952- row("leaf single", 0),340+/// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
953- row("leaf compound", 2),341+/// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
954- row("32x32 single", 4),342+/// by default ([`warp_on`], a sequence/frame header bit and a new
955- row("32x32 compound", 6),343+/// motion_mode symbol on eligible blocks) and
956- );344+/// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
957- // lane-txrd: which types the two searches actually COMMITTED over345+/// every inter frame's superblocks now code at their own lambda
958- // this row's four encodes -- the gate could not say whether a type346+/// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
959- // search fired at all (class `gate-blind-to-feature`).347+/// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
960- const NAMES: [&str; 16] = [348+/// and the two var-tx depth searches ([`tx32_depth_search`],
961- "IDTX",349+/// [`compound_var_tx`]) are on by default, all three re-judged on the
962- "DCT_DCT",350+/// native gate's real film rows.
963- "ADST_ADST",351+/// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
964- "ADST_DCT",352+/// every block whose chroma takes it codes a different mode symbol, two
965- "DCT_ADST",353+/// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
966- "V_DCT",354+/// restores the previous streams. Re-pinned again in the same lane once
967- "H_DCT",355+/// directional luma winners searched their `angle_delta_y`
968- "FLIPADST_DCT",356+/// (`EC_AV1_ANGLE=0` restores that half).
969- "DCT_FLIPADST",357+#[test]
970- "FLIPADST_FLIPADST",358+fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
971- "ADST_FLIPADST",359+ // These are DEFAULT-PRESET pins: a speed preset switches search levers
972- "FLIPADST_ADST",360+ // off, so it legitimately moves every byte. Encode at speed 0 whatever
973- "V_ADST",361+ // `EC_AV1_SPEED` says (write guard: the preset is process-global).
974- "H_ADST",362+ let _knobs = crate::speed::knob_write();
975- "V_FLIPADST",363+ let was = crate::speed::speed();
976- "H_FLIPADST",364+ crate::speed::set_speed(0);
977- ];365+ // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
978- let name_of = |t: usize| NAMES[t];366+ // so a tree with no root `fixtures/` reported this gate green having
979- for (label, hits) in [367+ // compared nothing at all.
980- ("inter", take_inter_tx_type_hits()),368+ let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
981- ("intra", take_tx_type_hits()),369+ let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4);
982- ] {370+ // FNV-1a over the stream: a witness that every coded bit is where it
983- let total: usize = hits.iter().sum();371+ // was, which a byte count alone is not.
984- let live: Vec<String> = hits372+ let fnv = |b: &[u8]| {
985- .iter()373+ b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
986- .enumerate()374+ (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
987- .filter(|&(_, &n)| n > 0)375+ })
988- .map(|(t, &n)| {376+ };
989- format!(377+ // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
990- "{}={n} ({:.1}%)",378+ // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
991- name_of(t),379+ // of 4, its leaves at q+8 and a `show_existing_frame` header per
992- 100.0 * n as f64 / total.max(1) as f64380+ // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
993- )381+ // four frames; four pictures is one short mini-GOP, which is the
994- })382+ // shape that pays least (the ARF's own quality has no later group to
995- .collect();383+ // carry it), so this is not the BD gate's number.
996- eprintln!(384+ // Re-taken again on lane-av1cfl: the chroma search offers
997- "{name}: {label} tx_type of {total} units -- {}",385+ // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
998- live.join(" ")386+ // so every block taking either codes different syntax and different
999- );387+ // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
1000- }388+ // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
1001- let t = take_txrd_stats();389+ // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
1002- if t[0] > 0 {390+ // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
1003- eprintln!(391+ // so these four pictures code as one truncated group -- a hidden
1004- "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \392+ // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
1005- bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",393+ // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
1006- t[0],394+ // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
1007- t[1],395+ // Re-taken on lane-fintra: the sequence header sets
1008- t[3] as f64 / 64.0,396+ // `enable_filter_intra`, so every DC_PRED intra block of at most
1009- t[2],397+ // 32x32 without a luma palette carries a `use_filter_intra` flag and
1010- t[4] as f64 / 64.0,398+ // the blocks that take one code a filter-intra mode, a different
1011- 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,399+ // prediction and different coefficients -- 7321 -> 7373 at q=150 and
1012- 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,400+ // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
1013- );401+ // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
1014- eprintln!(402+ // (default pyramid `8:-32:16`, one truncated group of 8 with its
1015- "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \403+ // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
1016- flat: dsse {:+.2}%, dbits {:+.2}%)",404+ // root can code a REAL residual now (one TX_64X64 luma transform and
1017- t[5],405+ // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
1018- t[6] as f64 / 64.0,406+ // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
1019- 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,407+ // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
1020- 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,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"
1021 );608 );
609+ assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
610+ assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
1022 }611 }
612+ streams.push((filter, encoded.stream));
1023 }613 }
1024-614+ set_frame_interp(None);
1025- /// The video stream's coded size, from ffprobe.615+ for (i, (fa, a)) in streams.iter().enumerate() {
1026- pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> {616+ for (fb, b) in &streams[i + 1..] {
1027- crate::probe::dims(clip)617+ assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
1028- }618+ }
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))
1053 }619 }
1054-620+}
1055- /// The probe arms the gate's source (lane-probe, class `instrument621+
1056- /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg622+/// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
1057- /// command line and had no `-ss`, so it read film B from frame 0 -- a623+/// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
1058- /// black leader -- and coded 59 kB where the gate's own ladder point624+/// residual outright (`round_to_valid_mv` rounds it away first), so the
1059- /// coded 89 kB of the same title; every census taken through it was625+/// finest vector the encoder could commit to was a quarter pel. With the
1060- /// probe-relative. Both now call [`crate::probe::source`]; this pins that626+/// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
1061- /// the shared loader honours the seek (arming the probe's way and the627+/// non-zero component and the search's fourth stage refines to the
1062- /// gate's way gives byte-identical streams, and dropping the seek does628+/// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
1063- /// not), on a synthetic clip whose content moves over time.629+/// on arm, and -- the part that makes it a signal rather than a symbol
1064- #[test]630+/// count (class `fixture proves the symbol, not the signal`) -- that some
1065- fn the_probe_arms_the_gates_source() {631+/// of them come out ZERO, i.e. name a vector the off arm cannot code at
1066- let _knobs = crate::speed::knob_write();632+/// all. Both streams are decoded by ffmpeg AND by this crate's own
1067- let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));633+/// decoder and asserted sample-exact against the encoder's own
1068- std::fs::create_dir_all(&dir).unwrap();634+/// reconstruction, which is what proves the header bit and the symbols
1069- let clip = dir.join("testsrc2.y4m");635+/// agree.
1070- // 384x202: neither side is a multiple of 128, so the gate's centre636+#[test]
1071- // window is a real derivation and not the frame itself -- exactly the637+fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
1072- // shape film B has (3840x1608, never 3840x2160).638+ let _knobs = crate::speed::knob_write();
1073- let ok = ec_testkit::ffmpeg()639+ let (width, height) = (256usize, 128usize);
1074- .args([640+ let pictures: Vec<Picture> = (0..3)
1075- "-v",641+ .map(|i| panned_test_card(width, height, i * 3))
1076- "error",642+ .collect();
1077- "-y",643+ let mut arms = Vec::new();
1078- "-f",644+ for hp in [false, true] {
1079- "lavfi",645+ set_high_precision_mv(Some(hp));
1080- "-i",646+ let _ = crate::tile::take_hp_symbols();
1081- "testsrc2=size=384x202:rate=10",647+ let fctx = &crate::decode::FrameCtx::for_encoder();
1082- ])648+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
1083- .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])649+ .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
1084- .arg(&clip)650+ let (symbols, eighth) = crate::tile::take_hp_symbols();
1085- .status()651+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
1086- .expect("ffmpeg failed to run")652+ let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
1087- .success();653+ assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
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- };
1109 assert_eq!(654 assert_eq!(
1110- bytes(&gate),655+ ours.len(),
1111- bytes(&probe),656+ pictures.len(),
1112- "probe and gate code different bytes"657+ "hp={hp}: our decoder frame count"
1113 );658 );
1114- // The two witnesses that both halves of the arming reach ffmpeg: the659+ for (i, e) in encoded.frames.iter().enumerate() {
1115- // seek, and the crop's own offset (the film-B defect in miniature --660+ for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
1116- // the probe was reading `crop=..:568` of a 1608-high frame).661+ if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction) {
1117- let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);662+ panic!(
1118- assert_ne!(663+ "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
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}, \
1228 the encoder reconstructed {want}"664 the encoder reconstructed {want}"
1229- );665+ );
1230- }
1231 }666 }
1232 }667 }
1233- arms.push((symbols, eighth, encoded.stream));
1234 }668 }
1235- set_high_precision_mv(None);669+ arms.push((symbols, eighth, encoded.stream));
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- );
1260 }670 }
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] = [
312 std::sync::atomic::AtomicU64::new(0),312 std::sync::atomic::AtomicU64::new(0),
313 ];313 ];
314 314
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-
322 /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.315 /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
323 #[cfg(test)]316 #[cfg(test)]
324 pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {317 pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
@@ -969,7 +962,15 @@ thread_local! {
969 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };962 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
970 }963 }
971 964
972-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates965+/// 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)]
973 pub(crate) fn force_intrabc(value: Option<bool>) {974 pub(crate) fn force_intrabc(value: Option<bool>) {
974 INTRABC_FORCE.with(|c| c.set(value));975 INTRABC_FORCE.with(|c| c.set(value));
975 }976 }
@@ -1059,7 +1060,12 @@ pub(super) fn ibc_index(
1059 /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact1060 /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
1060 /// content appears at some other position, against [`intrabc_pct`]. Returns1061 /// content appears at some other position, against [`intrabc_pct`]. Returns
1061 /// the share as well, for the gate's own print.1062 /// 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) {
1063 if true_width < 4 * 64 || true_height < 2 * 64 {1069 if true_width < 4 * 64 || true_height < 2 * 64 {
1064 return (false, 0.0);1070 return (false, 0.0);
1065 }1071 }
@@ -1075,9 +1081,9 @@ pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_h
1075 && hits1081 && hits
1076 .iter()1082 .iter()
1077 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))1083 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
1078- {1084+ {
1079- matched += 1;1085+ matched += 1;
1080- }1086+ }
1081 bx += IBC_HASH;1087 bx += IBC_HASH;
1082 }1088 }
1083 by += IBC_HASH;1089 by += IBC_HASH;
@@ -1207,13 +1213,6 @@ impl Drop for Ibc {
1207 }1213 }
1208 }1214 }
1209 1215
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-
1217 /// [`crate::tile::write_dv_component`]'s static price -- the same shape as1216 /// [`crate::tile::write_dv_component`]'s static price -- the same shape as
1218 /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`1217 /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
1219 /// infers rather than codes.1218 /// infers rather than codes.
@@ -1667,19 +1666,20 @@ pub(super) fn code_square(
1667 if let Some(ibc) = ibc1666 if let Some(ibc) = ibc
1668 && let Some((dv, cost_ibc, src)) =1667 && let Some((dv, cost_ibc, src)) =
1669 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)1668 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
1670- && cost_ibc < cost {1669+ && cost_ibc < cost
1671- ibc_commit(luma, chroma, (x, y), src, side);1670+ {
1672- ibc.last_dv = Some(dv);1671+ ibc_commit(luma, chroma, (x, y), src, side);
1673- ibc.hits += 1;1672+ ibc.last_dv = Some(dv);
1674- return (1673+ ibc.hits += 1;
1675- BlockCoeffs {1674+ return (
1676- skip: true,1675+ BlockCoeffs {
1677- dv: Some(dv),1676+ skip: true,
1678- ..BlockCoeffs::default()1677+ dv: Some(dv),
1679- },1678+ ..BlockCoeffs::default()
1680- cost_ibc,1679+ },
1681- );1680+ cost_ibc,
1682- }1681+ );
1682+ }
1683 // A palette or filter-intra block's luma was recoded through `DCT_DCT`1683 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
1684 // (its levels came from `code_from_prediction`), so the searched types1684 // (its levels came from `code_from_prediction`), so the searched types
1685 // belong to a block this one no longer is.1685 // belong to a block this one no longer is.
@@ -1722,53 +1722,6 @@ pub(super) const CHROMA_MODES: [u8; 7] = [
1722 PAETH_PRED,1722 PAETH_PRED,
1723 ];1723 ];
1724 1724
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-
1772 /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`1725 /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
1773 /// switches it off, which is how the lane measured its own on/off pair).1726 /// switches it off, which is how the lane measured its own on/off pair).
1774 pub(super) fn cfl_on() -> bool {1727 pub(super) fn cfl_on() -> bool {
@@ -1834,14 +1787,6 @@ pub(crate) fn sb128_on() -> bool {
1834 }1787 }
1835 }1788 }
1836 1789
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-
1845 /// The luma loop-restoration unit size this sequence codes: a 128 superblock1790 /// The luma loop-restoration unit size this sequence codes: a 128 superblock
1846 /// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,1791 /// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
1847 /// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is1792 /// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
@@ -1863,13 +1808,6 @@ pub(crate) fn filter_intra_on() -> bool {
1863 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))1808 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
1864 }1809 }
1865 1810
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-
1873 /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --1811 /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
1874 /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.1812 /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
1875 /// Returns each plane's levels, the mode, and what the pair cost (squared1813 /// Returns each plane's levels, the mode, and what the pair cost (squared
@@ -2051,7 +1989,9 @@ pub(super) fn search_chroma(
2051 }1989 }
2052 let mut v_colors = [0u16; 8];1990 let mut v_colors = [0u16; 8];
2053 for k in 0..n {1991 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;
2055 }1995 }
2056 let candidate = crate::tile::PaletteUv {1996 let candidate = crate::tile::PaletteUv {
2057 size: pal.size,1997 size: pal.size,
@@ -2229,17 +2169,10 @@ pub(super) fn search_chroma(
2229 }2169 }
2230 }2170 }
2231 }2171 }
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- }
2238 if census_on() {2172 if census_on() {
2239 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]2173 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2240 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);2174 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2241 }2175 }
2242- UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2243 chroma[0].commit(at.x, at.y, at.side, &u);2176 chroma[0].commit(at.x, at.y, at.side, &u);
2244 chroma[1].commit(at.x, at.y, at.side, &v);2177 chroma[1].commit(at.x, at.y, at.side, &v);
2245 (2178 (
@@ -2871,53 +2804,55 @@ pub(super) fn code_square_inter(
2871 }2804 }
2872 }2805 }
2873 if let Some(new_mv) = searched_new2806 if let Some(new_mv) = searched_new
2874- && let Some(b0) = mv_residual_bits(new_mv, cbase.0) {2807+ && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
2875- ccands.push((2808+ {
2876- (new_mv, cstack.nearest_mv.1),2809+ ccands.push((
2877- mode_bits_of(3) + b0,2810+ (new_mv, cstack.nearest_mv.1),
2878- InterInfo {2811+ mode_bits_of(3) + b0,
2879- ref_frame: crate::mvstack::LAST_FRAME,2812+ InterInfo {
2880- mode: InterMode::NewNearestMv,2813+ ref_frame: crate::mvstack::LAST_FRAME,
2881- mv: new_mv,2814+ mode: InterMode::NewNearestMv,
2882- mv1: cstack.nearest_mv.1,2815+ mv: new_mv,
2883- ref1: Some(ref1),2816+ mv1: cstack.nearest_mv.1,
2884- ref_mv_idx: 0,2817+ ref1: Some(ref1),
2885- },2818+ ref_mv_idx: 0,
2886- ));2819+ },
2887- }2820+ ));
2821+ }
2888 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two2822 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
2889 // searches this leaf ran, each residual priced against `cbase`.2823 // searches this leaf ran, each residual priced against `cbase`.
2890 if let Some(mv1) = second_new2824 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+ {
2892 ccands.push((2842 ccands.push((
2893- (cstack.nearest_mv.0, mv1),2843+ (new_mv, mv1),
2894- mode_bits_of(2) + b1,2844+ mode_bits_of(7) + b0 + b1,
2895 InterInfo {2845 InterInfo {
2896 ref_frame: crate::mvstack::LAST_FRAME,2846 ref_frame: crate::mvstack::LAST_FRAME,
2897- mode: InterMode::NearestNewMv,2847+ mode: InterMode::NewNewMv,
2898- mv: cstack.nearest_mv.0,2848+ mv: new_mv,
2899 mv1,2849 mv1,
2900 ref1: Some(ref1),2850 ref1: Some(ref1),
2901 ref_mv_idx: 0,2851 ref_mv_idx: 0,
2902 },2852 },
2903 ));2853 ));
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- }
2920 }2854 }
2855+ }
2921 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));2856 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
2922 ccands.dedup_by_key(|c| c.0);2857 ccands.dedup_by_key(|c| c.0);
2923 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);2858 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(
3040 ) >= 1;2975 ) >= 1;
3041 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);2976 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
3042 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();2977 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()
3044 && let Some(pred) = obmc_prediction(2980 && let Some(pred) = obmc_prediction(
3045 grid,2981 grid,
3046 (mi_row, mi_col),2982 (mi_row, mi_col),
@@ -3052,9 +2988,10 @@ pub(super) fn code_square_inter(
3052 planes,2988 planes,
3053 (reference.width, reference.height),2989 (reference.width, reference.height),
3054 fctx,2990 fctx,
3055- ) {2991+ )
3056- candidates.push((1, pred));2992+ {
3057- }2993+ candidates.push((1, pred));
2994+ }
3058 if warp_alphabet2995 if warp_alphabet
3059 && let Some(pred) = warp_prediction(2996 && let Some(pred) = warp_prediction(
3060 grid,2997 grid,
@@ -3066,9 +3003,10 @@ pub(super) fn code_square_inter(
3066 info.ref_frame,3003 info.ref_frame,
3067 planes,3004 planes,
3068 fctx,3005 fctx,
3069- ) {3006+ )
3070- candidates.push((2, pred));3007+ {
3071- }3008+ candidates.push((2, pred));
3009+ }
3072 for (motion, pred) in candidates {3010 for (motion, pred) in candidates {
3073 let luma_o = luma.code_from_prediction(3011 let luma_o = luma.code_from_prediction(
3074 x,3012 x,
@@ -3125,136 +3063,137 @@ pub(super) fn code_square_inter(
3125 }3063 }
3126 3064
3127 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best3065 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best
3128- && cost < intra_cost {3066+ && cost < intra_cost
3129- // A compound winner commits the flat trial it was priced from:3067+ {
3130- // `commit_inter_luma`'s var-tx trial set is single-reference3068+ // A compound winner commits the flat trial it was priced from:
3131- // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.3069+ // `commit_inter_luma`'s var-tx trial set is single-reference
3132- // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`3070+ // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3133- // predicting each half-side trial from BOTH references, verified3071+ // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
3134- // byte-identical to this when its split is disabled) and MEASURED3072+ // predicting each half-side trial from BOTH references, verified
3135- // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the3073+ // byte-identical to this when its split is disabled) and MEASURED
3136- // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/3074+ // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
3137- // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A3075+ // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
3138- // compound block's residual is small enough that the four extra3076+ // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
3139- // per-unit txb_skip/eob symbols cost more ladder bytes than this3077+ // compound block's residual is small enough that the four extra
3140- // encoder's static-CDF estimate prices them at, so the local RD3078+ // per-unit txb_skip/eob symbols cost more ladder bytes than this
3141- // win does not convert. lane-av1txbits REBUILT it on top of a3079+ // encoder's static-CDF estimate prices them at, so the local RD
3142- // search that prices against the tables the frame is really3080+ // win does not convert. lane-av1txbits REBUILT it on top of a
3143- // written with (`tile::arm_pricing_cdfs`, the estimate error on3081+ // search that prices against the tables the frame is really
3144- // these very blocks measured down from +31% to +3%) and measured3082+ // written with (`tile::arm_pricing_cdfs`, the estimate error on
3145- // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/3083+ // these very blocks measured down from +31% to +3%) and measured
3146- // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the3084+ // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
3147- // same build without it. The static-CDF estimate was NOT what3085+ // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
3148- // held the compound var-tx trial back. The flat trial stays.3086+ // same build without it. The static-CDF estimate was NOT what
3149- // An OBMC winner commits the flat trial too: `commit_inter_luma`3087+ // held the compound var-tx trial back. The flat trial stays.
3150- // re-predicts each var-tx unit by plain translation, which is not3088+ // An OBMC winner commits the flat trial too: `commit_inter_luma`
3151- // the prediction this candidate was priced from.3089+ // re-predicts each var-tx unit by plain translation, which is not
3152- // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE3090+ // the prediction this candidate was priced from.
3153- // 0.05 (both rejections above were measured at 0.1, the weight3091+ // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
3154- // the lambda lane showed was 2x too heavy): a compound winner is3092+ // 0.05 (both rejections above were measured at 0.1, the weight
3155- // offered the same var-tx split, its units predicted from BOTH3093+ // the lambda lane showed was 2x too heavy): a compound winner is
3156- // references (`mc_trial_compound`). RE-MEASURED native: film3094+ // offered the same var-tx split, its units predicted from BOTH
3157- // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.43095+ // references (`mc_trial_compound`). RE-MEASURED native: film
3158- // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --3096+ // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
3159- // one row 0.2 down, two flat, short of the two-down-one-flat keep3097+ // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
3160- // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)3098+ // one row 0.2 down, two flat, short of the two-down-one-flat keep
3161- // rather than change the default on a single 0.2 row. It fires:3099+ // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
3162- // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for3100+ // rather than change the default on a single 0.2 row. It fires:
3163- // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against3101+ // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
3164- // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is3102+ // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
3165- // 1.3/1.2 down there, which is where the upgrade path is if this3103+ // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
3166- // is picked up again.3104+ // 1.3/1.2 down there, which is where the upgrade path is if this
3167- let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {3105+ // is picked up again.
3168- refs[r as usize].map(|g| {3106+ let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3169- (3107+ refs[r as usize].map(|g| {
3170- info.mv1,3108+ (
3171- (g.y.as_slice(), g.width, luma.true_width, luma.true_height),3109+ info.mv1,
3172- )3110+ (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3173- })3111+ )
3174- });3112+ })
3175- let (levels, tx_depth, dcost, luma_tx_types) =3113+ });
3176- if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {3114+ let (levels, tx_depth, dcost, luma_tx_types) =
3177- luma.commit(x, y, side, &luma_new);3115+ if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
3178- (luma_new.levels.clone(), 0, 0.0, Vec::new())3116+ luma.commit(x, y, side, &luma_new);
3179- } else {3117+ (luma_new.levels.clone(), 0, 0.0, Vec::new())
3180- commit_inter_luma(3118+ } else {
3181- luma,3119+ commit_inter_luma(
3182- (x, y),3120+ luma,
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,
3197 (x, y),3121 (x, y),
3198 side,3122 side,
3199 info.mv,3123 info.mv,
3200- [3124+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
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- }),
3225 search,3125 search,
3226- chroma_set,3126+ &luma_new,
3227- t,3127+ skip_new,
3128+ second,
3228 fctx,3129 fctx,
3229 )3130 )
3230- .unwrap_or([u_new, v_new]),
3231- None => [u_new, v_new],
3232 };3131 };
3233- chroma[0].commit(x / 2, y / 2, side / 2, &u_new);3132+ // lane-txrd: chroma follows the luma type the search just chose.
3234- chroma[1].commit(x / 2, y / 2, side / 2, &v_new);3133+ let [u_new, v_new] = match luma_tx_types.first().copied() {
3235- return (3134+ Some(t) => recode_inter_chroma(
3236- BlockCoeffs {3135+ chroma,
3237- angle_delta_y: 0,3136+ (x, y),
3238- cfl_alphas: None,3137+ side,
3239- filter_intra: None,3138+ info.mv,
3240- luma: coeffs(&levels, side),3139+ [
3241- u: coeffs(&u_new.levels, side / 2),3140+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3242- v: coeffs(&v_new.levels, side / 2),3141+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3243- mode: DC_PRED,3142+ ],
3244- uv_mode: DC_PRED,3143+ info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3245- skip: skip_new,3144+ refs[r as usize].map(|g| {
3246- eight: None,3145+ (
3247- dv: None,3146+ info.mv1,
3248- palette: None,3147+ [
3249- palette_uv: None,3148+ (
3250- tx_depth,3149+ g.u.as_slice(),
3251- luma_tx_types,3150+ g.width / 2,
3252- inter: Some(info),3151+ chroma[0].true_width,
3253- motion_mode: motion_won,3152+ chroma[0].true_height,
3254- },3153+ ),
3255- cost + dcost,3154+ (
3256- );3155+ g.v.as_slice(),
3257- }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+ }
3258 3197
3259 census_add(8, 1);3198 census_add(8, 1);
3260 if skip {3199 if skip {
crates/ec-av1/src/encode/tests.rsmodified+2382 -3366

Diff too large; view file

@@ -1,3548 +1,2564 @@
1 1
2- /// Every (site, frame type, block side) the census can be called with2+/// Every (site, frame type, block side) the census can be called with
3- /// lands in its own ten-counter bucket, inside the array (class3+/// lands in its own ten-counter bucket, inside the array (class
4- /// `enumerate-table-domain`: an off-by-one here would silently add two4+/// `enumerate-table-domain`: an off-by-one here would silently add two
5- /// sites' trials together).5+/// sites' trials together).
6- #[test]6+#[test]
7- fn the_split_census_buckets_are_distinct_and_in_bounds() {7+fn the_split_census_buckets_are_distinct_and_in_bounds() {
8- let mut seen = std::collections::BTreeSet::new();8+ let mut seen = std::collections::BTreeSet::new();
9- for site in 0..2 {9+ for site in 0..2 {
10- for key in [true, false] {10+ for key in [true, false] {
11- for side in [8usize, 16, 32, 64] {11+ for side in [8usize, 16, 32, 64] {
12- let base = super::split_census_base(site, key, side);12+ let base = super::split_census_base(site, key, side);
13- assert!(13+ assert!(
14- base + 10 <= super::SPLIT_CENSUS.len(),14+ base + 10 <= super::SPLIT_CENSUS.len(),
15- "{site} {key} {side}"15+ "{site} {key} {side}"
16- );16+ );
17- assert!(seen.insert(base), "{site} {key} {side} collides");17+ assert!(seen.insert(base), "{site} {key} {side} collides");
18- }
19 }18 }
20 }19 }
21- assert_eq!(seen.len(), 16);
22 }20 }
21+ assert_eq!(seen.len(), 16);
22+}
23 23
24- /// An [`crate::mvstack::MvStack`] with every context at zero and no24+/// An [`crate::mvstack::MvStack`] with every context at zero and no
25- /// neighbours, for the pricer tests below to fill the one band each of25+/// neighbours, for the pricer tests below to fill the one band each of
26- /// them is about.26+/// them is about.
27- /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer27+/// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
28- /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL28+/// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
29- /// against the same stack -- an offer the writer clamps prices the29+/// against the same stack -- an offer the writer clamps prices the
30- /// residual against a predictor the decoder never derives, which is the30+/// residual against a predictor the decoder never derives, which is the
31- /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER31+/// 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 is32+/// side, so the stream stays legal; here the pricer's own offer set is
33- /// enumerated, class `enumerate-table-domain`).33+/// enumerated, class `enumerate-table-domain`).
34- ///34+///
35- /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt35+/// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
36- /// r2, 2026-09-29). It replaces the clip gate36+/// 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`,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 a38+/// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
39- /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable39+/// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
40- /// while the invariant above holds, so no recipe could ever satisfy it.40+/// while the invariant above holds, so no recipe could ever satisfy it.
41- /// Deletion loses no coverage on either half:41+/// Deletion loses no coverage on either half:
42- /// * the clamp half -- this test IS the coverage, and it is strictly42+/// * the clamp half -- this test IS the coverage, and it is strictly
43- /// stronger than any clip gate: it enumerates the pricer's whole offer43+/// 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 larger44+/// 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`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 are46+/// 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 the47+/// unreachable at ANY stack size), which is why 0..=4 bounds the
48- /// domain rather than sampling it;48+/// domain rather than sampling it;
49- /// * the pixel half -- the deleted gate's own decode-vs-encoder-49+/// * the pixel half -- the deleted gate's own decode-vs-encoder-
50- /// reconstruction compare on a 1280x768 sb128 sequence is already made50+/// reconstruction compare on a 1280x768 sb128 sequence is already made
51- /// four times over, by `a_128_superblock_clip_whose_root_search_codes_51+/// four times over, by `a_128_superblock_clip_whose_root_search_codes_
52- /// 128x128_blocks_decodes_exact`,52+/// 128x128_blocks_decodes_exact`,
53- /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,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`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`55+/// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
56- /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND56+/// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
57- /// ffmpeg compare).57+/// ffmpeg compare).
58- ///58+///
59- /// MEASURED before deleting (153 clip x size x frame-count x q combinations,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 PROOF60+/// `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 offer61+/// 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 on62+/// set to `0..5` fires the counter immediately (9/2/2/1 on
63- /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,63+/// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
64- /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`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 fix65+/// 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's66+/// (`deferred(unblock: the DRL owner widens the pricer past the writer's
67- /// `start + 2` ceiling, or retires the counter)`) -- this test will go red67+/// `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.68+/// the moment either happens, which is the signal to re-open the cell.
69- ///69+///
70- /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer70+/// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
71- #[test]71+#[test]
72- fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {72+fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
73- for n in 0..=4usize {73+ for n in 0..=4usize {
74- let mut stack = bare_stack();74+ let mut stack = bare_stack();
75- for i in 0..n {75+ for i in 0..n {
76- stack.entries.push(crate::mvstack::StackEntry {76+ stack.entries.push(crate::mvstack::StackEntry {
77- mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),77+ mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
78- weight: 1,78+ weight: 1,
79- });79+ });
80- stack.drl_ctx.push(0);80+ stack.drl_ctx.push(0);
81- }81+ }
82- stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);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);83+ stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
84- stack.pred_mv = stack.nearest_mv;84+ stack.pred_mv = stack.nearest_mv;
85- // Aim the vector at each entry in turn, so every index the offer85+ // Aim the vector at each entry in turn, so every index the offer
86- // set holds is the one that wins at least once.86+ // set holds is the one that wins at least once.
87- for target in 0..n.max(1) {87+ for target in 0..n.max(1) {
88- let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);88+ let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
89- let (_, idx) =89+ let (_, idx) =
90- best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");90+ best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
91- let idx = usize::from(idx);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() {
92 assert_eq!(103 assert_eq!(
93- crate::tile::signalled_drl_idx(n, 0, idx),104+ crate::tile::signalled_drl_idx(n, 1, idx),
94 idx,105 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}",
96 );107 );
97 }108 }
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- }
110 }109 }
111 }110 }
111+}
112 112
113- pub(super) fn bare_stack() -> crate::mvstack::MvStack {113+pub(super) fn bare_stack() -> crate::mvstack::MvStack {
114- crate::mvstack::MvStack {114+ crate::mvstack::MvStack {
115- entries: Default::default(),115+ entries: Default::default(),
116- nearest_mv: (0, 0),116+ nearest_mv: (0, 0),
117- near_mv: (0, 0),117+ near_mv: (0, 0),
118- pred_mv: (0, 0),118+ pred_mv: (0, 0),
119- new_mv_ctx: 0,119+ new_mv_ctx: 0,
120- ref_mv_ctx: 0,120+ ref_mv_ctx: 0,
121- zero_mv_ctx: 0,121+ zero_mv_ctx: 0,
122- drl_ctx: Default::default(),122+ drl_ctx: Default::default(),
123- above_refs: (None, None),123+ above_refs: (None, None),
124- left_refs: (None, None),124+ left_refs: (None, None),
125- above_nbr: None,125+ above_nbr: None,
126- left_nbr: None,126+ left_nbr: None,
127- above_skip: false,127+ above_skip: false,
128- left_skip: false,128+ left_skip: false,
129- }
130 }129 }
130+}
131 131
132- /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'132+/// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
133- /// `write_compound_ref_frames` codes for a pair, each at that symbol's133+/// `write_compound_ref_frames` codes for a pair, each at that symbol's
134- /// own neighbour-derived context. Red before lane-ctx, where the pricer134+/// own neighbour-derived context. Red before lane-ctx, where the pricer
135- /// spent four constants at CDF row 0 that assumed the pair was135+/// 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 as136+/// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
137- /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.137+/// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
138- #[test]138+#[test]
139- fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {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};140+ use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
141- use crate::encode::symbol_bits as b;141+ use crate::encode::symbol_bits as b;
142- use crate::mvstack::{142+ use crate::mvstack::{
143- ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,143+ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
144- LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,144+ LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, single_ref_p1_ctx,
145- single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,145+ single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
146- single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_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()
147 };220 };
148- // (pair, unidirectional?, the tree's symbols as (table, p index,221+ let (a, a1) = above_refs;
149- // context selector, value)) -- transcribed from the writer.222+ let (l, l1) = left_refs;
150- // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.223+ let ctx_of = |sel: usize| match sel {
151- type Sym = (char, usize, usize, usize);224+ 1 => single_ref_p1_ctx(a, a1, l, l1),
152- let cases: [((i8, i8), bool, &[Sym]); 7] = [225+ 2 => single_ref_p2_ctx(a, a1, l, l1),
153- (226+ 3 => single_ref_p3_ctx(a, a1, l, l1),
154- (LAST_FRAME, LAST2_FRAME),227+ 4 => single_ref_p4_ctx(a, a1, l, l1),
155- true,228+ 5 => single_ref_p5_ctx(a, a1, l, l1),
156- &[('u', 0, 1, 0), ('u', 1, 7, 0)],229+ 6 => single_ref_p6_ctx(a, a1, l, l1),
157- ),230+ _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
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 };231 };
203- // No neighbours (every context zero), then a mixed pair that puts the232+ for (pair, unidir, symbols) in cases {
204- // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.233+ let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
205- for (above_nbr, left_nbr, above_refs, left_refs) in [234+ + b(
206- (None, None, (None, None), (None, None)),235+ &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
207- (236+ usize::from(!unidir),
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}"
251 );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+ };
252 }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}"
251+ );
253 }252 }
254 }253 }
254+}
255 255
256- /// The `skip` and `is_inter` symbols are priced at the SAME context256+/// 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 and257+/// 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-ctx258+/// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
259- /// on every neighbour configuration whose context is not zero (class259+/// on every neighbour configuration whose context is not zero (class
260- /// pricer-context-zero).260+/// pricer-context-zero).
261- #[test]261+#[test]
262- fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {262+fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
263- use crate::cdf::{INTRA_INTER, SKIP};263+ use crate::cdf::{INTRA_INTER, SKIP};
264- use crate::encode::symbol_bits as b;264+ use crate::encode::symbol_bits as b;
265- use crate::mvstack::NeighbourRef;265+ use crate::mvstack::NeighbourRef;
266- let nbr = |is_inter| NeighbourRef {266+ let nbr = |is_inter| NeighbourRef {
267- is_inter,267+ is_inter,
268- ref0: if is_inter {268+ ref0: if is_inter {
269- crate::mvstack::LAST_FRAME269+ crate::mvstack::LAST_FRAME
270- } else {270+ } else {
271- 0271+ 0
272- },272+ },
273- ref1: None,273+ ref1: None,
274- uni: false,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()
275 };289 };
276- for (above, left, above_skip, left_skip) in [290+ let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
277- (None, None, false, false),291+ let ii_ctx = crate::tile::intra_inter_ctx(
278- (Some(nbr(true)), Some(nbr(true)), true, false),292+ above.is_some(),
279- (Some(nbr(false)), Some(nbr(false)), true, true),293+ left.is_some(),
280- (Some(nbr(false)), None, false, true),294+ above.is_some_and(|n| n.is_inter),
281- (None, Some(nbr(true)), true, true),295+ left.is_some_and(|n| n.is_inter),
282- ] {296+ );
283- let stack = crate::mvstack::MvStack {297+ for v in [false, true] {
284- above_nbr: above,298+ let (got, want) = (
285- left_nbr: left,299+ super::skip_bits_at(&stack, v),
286- above_skip,300+ b(&SKIP[skip_ctx], usize::from(v)),
287- left_skip,301+ );
288- ..bare_stack()302+ assert!(
289- };303+ (got - want).abs() < 1e-9,
290- let skip_ctx = usize::from(above_skip) + usize::from(left_skip);304+ "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
291- let ii_ctx = crate::tile::intra_inter_ctx(305+ );
292- above.is_some(),306+ let (got, want) = (
293- left.is_some(),307+ super::intra_inter_bits_at(&stack, v),
294- above.is_some_and(|n| n.is_inter),308+ b(&INTRA_INTER[ii_ctx], usize::from(v)),
295- left.is_some_and(|n| n.is_inter),309+ );
310+ assert!(
311+ (got - want).abs() < 1e-9,
312+ "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
296 );313 );
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- }
315 }314 }
316 }315 }
316+}
317 317
318- /// [`super::single_ref_bits`] pays exactly what tile.rs'318+/// [`super::single_ref_bits`] pays exactly what tile.rs'
319- /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD319+/// `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 at320+/// 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 the321+/// the context that symbol's own `single_ref_p*_ctx` derives from the
322- /// block's above/left neighbours. Red before lane-pricer, where every322+/// 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.323+/// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
324- #[test]324+#[test]
325- fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {325+fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
326- use crate::cdf::SINGLE_REF as SR;326+ use crate::cdf::SINGLE_REF as SR;
327- use crate::encode::symbol_bits as b;327+ use crate::encode::symbol_bits as b;
328- use crate::mvstack::{328+ use crate::mvstack::{
329- ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,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,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,331+ single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
332- };332+ };
333- let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {333+ let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
334- above_refs,334+ above_refs,
335- left_refs,335+ left_refs,
336- above_nbr,336+ above_nbr,
337- left_nbr,337+ left_nbr,
338- ..bare_stack()338+ ..bare_stack()
339- };339+ };
340- let nbr = |ref0, ref1| {340+ let nbr = |ref0, ref1| {
341- Some(crate::mvstack::NeighbourRef {341+ Some(crate::mvstack::NeighbourRef {
342- is_inter: true,342+ is_inter: true,
343- ref0,343+ ref0,
344- ref1,344+ ref1,
345- uni: false,345+ uni: false,
346- })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),
347 };381 };
348- // (reference, the symbols `write_single_ref` emits as (p index, value))382+ for (ref_frame, symbols) in cases {
349- let cases: [(i8, &[(usize, usize)]); 7] = [383+ // Plus the `comp_mode = 0` symbol the writer codes ahead of
350- (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),384+ // the reference syntax on a `reference_select` frame.
351- (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),385+ let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
352- (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),386+ if super::reference_select() {
353- (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),387+ want += b(
354- (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),388+ &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
355- (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),389+ 0,
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}"
398 );390 );
399 }391 }
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+ );
400 }398 }
401 }399 }
400+}
402 401
403- /// lane-av1tpl2's propagated map, on the two properties every decision402+/// lane-av1tpl2's propagated map, on the two properties every decision
404- /// under it rests on: a frame the whole lookahead window repeats exactly403+/// 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 and404+/// (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 bits405+/// 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 is406+/// 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 more407+/// flat -- the factor FALLS below 1, i.e. that half is coded more
409- /// distortion-averse than the half nothing gains from.408+/// distortion-averse than the half nothing gains from.
410- /// The distortion metric itself (lane-sse): a block the true frame edge409+/// 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 that410+/// 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 past411+/// lives entirely in the padding costs nothing and a block wholly past
413- /// the edge scores zero. Before this, the search ranked modes,412+/// the edge scores zero. Before this, the search ranked modes,
414- /// transforms and partition trees on samples the display crop throws413+/// transforms and partition trees on samples the display crop throws
415- /// away -- which lane-b64b had fixed for the 64x64 root alone.414+/// away -- which lane-b64b had fixed for the 64x64 root alone.
416- #[test]415+#[test]
417- fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {416+fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
418- // A 40x40 true frame on a 64x64 padded coding surface.417+ // A 40x40 true frame on a 64x64 padded coding surface.
419- let source = vec![10u8; 64 * 64];418+ let source = vec![10u8; 64 * 64];
420- let plane = fresh_plane(&source, 64, 64, 40, 40);419+ let plane = fresh_plane(&source, 64, 64, 40, 40);
421- let mut reconstruction = vec![10u8; 64 * 64];420+ let mut reconstruction = vec![10u8; 64 * 64];
422- // Off by 190 at (50, 50) -- past the true edge in both axes.421+ // Off by 190 at (50, 50) -- past the true edge in both axes.
423- reconstruction[50 * 64 + 50] = 200;422+ reconstruction[50 * 64 + 50] = 200;
424- assert_eq!(423+ assert_eq!(
425- plane.block_sse(0, 0, 64, &reconstruction),424+ plane.block_sse(0, 0, 64, &reconstruction),
426- 0.0,425+ 0.0,
427- "padding was scored"426+ "padding was scored"
428- );427+ );
429- // Off by 10 at (39, 39) -- the last sample the decoder shows.428+ // Off by 10 at (39, 39) -- the last sample the decoder shows.
430- reconstruction[39 * 64 + 39] = 20;429+ reconstruction[39 * 64 + 39] = 20;
431- assert_eq!(430+ assert_eq!(
432- plane.block_sse(0, 0, 64, &reconstruction),431+ plane.block_sse(0, 0, 64, &reconstruction),
433- 100.0,432+ 100.0,
434- "inside was not scored"433+ "inside was not scored"
435- );434+ );
436- // A 16x16 block whose every sample is padding.435+ // A 16x16 block whose every sample is padding.
437- let block = vec![200u8; 16 * 16];436+ let block = vec![200u8; 16 * 16];
438- assert_eq!(437+ assert_eq!(
439- plane.block_sse(48, 0, 16, &block),438+ plane.block_sse(48, 0, 16, &block),
440- 0.0,439+ 0.0,
441- "a block past the edge scored"440+ "a block past the edge scored"
442- );441+ );
443- // A 16x16 block the edge cuts: 8 of its columns are inside.442+ // 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);443+ assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
445- }444+}
446 445
447- /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must446+/// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
448- /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the447+/// 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.448+/// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
450- #[test]449+#[test]
451- fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {450+fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
452- let (base, res) = (162u8, 4i32);451+ let (base, res) = (162u8, 4i32);
453- let rf = 2.0;452+ let rf = 2.0;
454- // A superblock the window leans on more than the frame average is453+ // A superblock the window leans on more than the frame average is
455- // coded FINER (lower qindex); a slack one coarser; the average one454+ // coded FINER (lower qindex); a slack one coarser; the average one
456- // exactly at the base.455+ // exactly at the base.
457- assert!(456+ assert!(
458- super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,457+ super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
459- "leaned-on SB must go finer"458+ "leaned-on SB must go finer"
460- );459+ );
461- assert!(460+ assert!(
462- super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,461+ super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
463- "idle SB must go coarser"462+ "idle SB must go coarser"
464- );463+ );
465- assert_eq!(464+ assert_eq!(
466- super::deltaq_libaom(base, rf, rf, 1.0, res),465+ super::deltaq_libaom(base, rf, rf, 1.0, res),
467- base,466+ base,
468- "the average SB moves 0"467+ "the average SB moves 0"
469- );468+ );
470- // Every offset is a whole number of steps and inside +-(res * 9 - 1).469+ // Every offset is a whole number of steps and inside +-(res * 9 - 1).
471- let max = ((res * 9 - 1) / res) * res;470+ let max = ((res * 9 - 1) / res) * res;
472- for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {471+ 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] {472+ for k in [0.5f64, 1.0, 1.5] {
474- let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));473+ let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
475- let d = q - i32::from(base);474+ let d = q - i32::from(base);
476- assert_eq!(475+ assert_eq!(
477- d % res,476+ d % res,
478- 0,477+ 0,
479- "r={r} k={k}: offset {d} is not a whole {res}-step"478+ "r={r} k={k}: offset {d} is not a whole {res}-step"
480- );479+ );
481- assert!(480+ assert!(
482- d.abs() <= max,481+ d.abs() <= max,
483- "r={r} k={k}: offset {d} past libaom's +-{max}"482+ "r={r} k={k}: offset {d} past libaom's +-{max}"
484- );483+ );
485- }
486 }484 }
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);
510 }485 }
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+}
511 525
512- /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto526+#[test]
513- /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the527+fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
514- /// shipped default, and the multiplier reaches the strength.528+ // Four 64x64 superblocks across: the shipped map forms its ratio per
515- #[test]529+ // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
516- fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {530+ // only ever produce one ratio -- and one ratio, mean-normalised, is
517- let d = crate::speed::DQ_LEVEL_K;531+ // the flat map, whatever the content underneath it.
518- assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");532+ let (w, h) = (256usize, 64usize);
519- assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);533+ let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
520- // Short and broken fields fall back per SLOT, not per spec.534+ let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
521- assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);535+ let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
522- assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);536+ assert_eq!(f.len(), 64, "16x4 cells of 16x16");
523- assert_eq!(super::DqLevel::TopArf as usize, 0);537+ for (i, &v) in f.iter().enumerate() {
524- assert_eq!(super::DqLevel::MidArf as usize, 1);538+ assert!(
525- assert_eq!(super::DqLevel::Leaf as usize, 2);539+ (v - 1.0).abs() < 1e-6,
540+ "cell {i} factor {v}, a flat map must move no lambda"
541+ );
526 }542 }
527 543
528- #[test]544+ // Left half textured, right half constant: the window saves bits
529- fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {545+ // predicting the left half and nothing at all on the right.
530- // Four 64x64 superblocks across: the shipped map forms its ratio per546+ let split: Vec<u8> = (0..w * h)
531- // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could547+ .map(|i| {
532- // only ever produce one ratio -- and one ratio, mean-normalised, is548+ if i % w < w / 2 {
533- // the flat map, whatever the content underneath it.549+ ((i * 37) % 251) as u8
534- let (w, h) = (256usize, 64usize);550+ } else {
535- let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();551+ 128
536- let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];552+ }
537- let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);553+ })
538- assert_eq!(f.len(), 64, "16x4 cells of 16x16");554+ .collect();
539- for (i, &v) in f.iter().enumerate() {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]);
540 assert!(561 assert!(
541- (v - 1.0).abs() < 1e-6,562+ lean < 1.0,
542- "cell {i} factor {v}, a flat map must move no lambda"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"
543 );568 );
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- }
572 }569 }
573 }570 }
571+}
574 572
575- /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a573+/// 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 a574+/// 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 holds575+/// 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 that576+/// `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.577+/// 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 covered578+/// 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 every579+/// 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-left580+/// block row but the first (silently wrong above-right/below-left
583- /// availability -- wrong pixels, no error).581+/// availability -- wrong pixels, no error).
584- #[test]582+#[test]
585- fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {583+fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
586- for (bw, bh) in [584+ for (bw, bh) in [
587- (16usize, 8usize),585+ (16usize, 8usize),
588- (8, 16),586+ (8, 16),
589- (32, 16),587+ (32, 16),
590- (16, 32),588+ (16, 32),
591- (64, 32),589+ (64, 32),
592- (32, 64),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),
593 ] {600 ] {
594- let (bw_log2, bh_log2) = (601+ assert_eq!(
595- (bw / 4).trailing_zeros() as usize,602+ table.len() * 8,
596- (bh / 4).trailing_zeros() as usize,603+ rows * cols,
604+ "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
597 );605 );
598- let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);606+ let mut seen = vec![0u32; table.len() * 8];
599- for (name, table) in [607+ for blk_row in 0..rows {
600- ("has_tr", rect_reach_tables(bw, bh).0),608+ for blk_col in 0..cols {
601- ("has_bl", rect_reach_tables(bw, bh).1),609+ let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
602- ] {610+ assert!(
603- assert_eq!(611+ idx < seen.len(),
604- table.len() * 8,612+ "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
605- rows * cols,613+ );
606- "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"614+ seen[idx] += 1;
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- }
618 }615 }
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- );
624 }616 }
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+ );
625 }622 }
626 }623 }
627- use super::*;624+}
628- use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};625+use super::*;
629- use crate::probe::run_with_stdin;626+use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
630-627+use crate::probe::run_with_stdin;
631- /// Every rectangular shape this decoder codes, at every position a block628+
632- /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]629+/// Every rectangular shape this decoder codes, at every position a block
633- /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`630+/// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
634- /// (`reconintra.c`) answer, whose bodies are ported below.631+/// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
635- ///632+/// (`reconintra.c`) answer, whose bodies are ported below.
636- /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):633+///
637- /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the634+/// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
638- /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)635+/// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
639- /// and 7 (below-left) of the 21 reachable positions with no gate seeing636+/// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
640- /// it. The per-shape `(len, byte sum)` fingerprints below come from the637+/// and 7 (below-left) of the 21 reachable positions with no gate seeing
641- /// oracle's own arrays, so a re-routed or truncated table fails here even638+/// it. The per-shape `(len, byte sum)` fingerprints below come from the
642- /// where the two rows happen to agree.639+/// oracle's own arrays, so a re-routed or truncated table fails here even
643- ///640+/// where the two rows happen to agree.
644- /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/641+///
645- /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the642+/// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
646- /// callers handle by predicting each transform unit as its own block.643+/// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
647- /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's644+/// callers handle by predicting each transform unit as its own block.
648- /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is645+/// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
649- /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL646+/// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
650- /// (the horizontal shapes, which those partitions never produce).647+/// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
651- #[test]648+/// (the horizontal shapes, which those partitions never produce).
652- fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {649+#[test]
653- // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so650+fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
654- // it pins the 64 reach explicitly instead of following the process's651+ // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
655- // own superblock knob (`for_encoder`), which made it red under652+ // it pins the 64 reach explicitly instead of following the process's
656- // `EC_AV1_SB128=1` for no defect of the code under test.653+ // own superblock knob (`for_encoder`), which made it red under
657- let fctx = &crate::decode::FrameCtx::new();654+ // `EC_AV1_SB128=1` for no defect of the code under test.
658- // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).655+ let fctx = &crate::decode::FrameCtx::new();
659- const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [656+ // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
660- (4, 8, 64, 9280, 64, 550),657+ const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
661- (8, 4, 64, 3712, 64, 9630),658+ (4, 8, 64, 9280, 64, 550),
662- (8, 16, 16, 2352, 16, 134),659+ (8, 4, 64, 3712, 64, 9630),
663- (16, 8, 16, 960, 16, 2400),660+ (8, 16, 16, 2352, 16, 134),
664- (16, 32, 4, 620, 4, 32),661+ (16, 8, 16, 960, 16, 2400),
665- (32, 16, 4, 32, 4, 184),662+ (16, 32, 4, 620, 4, 32),
666- (32, 64, 1, 127, 1, 0),663+ (32, 16, 4, 32, 4, 184),
667- (64, 32, 1, 19, 1, 34),664+ (32, 64, 1, 127, 1, 0),
668- (4, 16, 32, 5472, 32, 14),665+ (64, 32, 1, 19, 1, 34),
669- (16, 4, 32, 960, 32, 6464),666+ (4, 16, 32, 5472, 32, 14),
670- (8, 32, 8, 1400, 8, 2),667+ (16, 4, 32, 960, 32, 6464),
671- (32, 8, 8, 32, 8, 1136),668+ (8, 32, 8, 1400, 8, 2),
672- (16, 64, 2, 382, 2, 0),669+ (32, 8, 8, 32, 8, 1136),
673- (64, 16, 2, 4, 2, 84),670+ (16, 64, 2, 382, 2, 0),
674- ];671+ (64, 16, 2, 4, 2, 84),
675- /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for672+ ];
676- /// a block whose transform covers it whole (`row_off == col_off == 0`,673+ /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
677- /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel674+ /// a block whose transform covers it whole (`row_off == col_off == 0`,
678- /// superblock (`sb_mi_size == 16`).675+ /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
679- fn libaom_reach(676+ /// superblock (`sb_mi_size == 16`).
680- bw: usize,677+ fn libaom_reach(
681- bh: usize,678+ bw: usize,
682- x: usize,679+ bh: usize,
683- y: usize,680+ x: usize,
684- width: usize,681+ y: usize,
685- height: usize,682+ width: usize,
686- _fctx: &crate::decode::FrameCtx,683+ height: usize,
687- ) -> (bool, bool) {684+ _fctx: &crate::decode::FrameCtx,
688- let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);685+ ) -> (bool, bool) {
689- let (_bw_unit, bh_unit) = (bw / 4, bh / 4);686+ let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
690- let sb_mi_size = 16usize;687+ let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
691- let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;688+ let sb_mi_size = 16usize;
692- let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;689+ let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
693- let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;690+ let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
694- let (tr_table, bl_table) = rect_reach_tables(bw, bh);691+ let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
695- let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;692+ let (tr_table, bl_table) = rect_reach_tables(bw, bh);
696- // has_top_right: top_available && right_available, then row_off == 0.693+ let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
697- let top_right = if y == 0 || x + bw >= width {694+ // has_top_right: top_available && right_available, then row_off == 0.
698- false695+ let top_right = if y == 0 || x + bw >= width {
699- } else if blk_row_in_sb == 0 {696+ false
700- // (`col_off + tx_wide_unit < plane_bw_unit` above this is697+ } else if blk_row_in_sb == 0 {
701- // `bw_unit < bw_unit`, false for a whole-block transform.)698+ // (`col_off + tx_wide_unit < plane_bw_unit` above this is
702- true699+ // `bw_unit < bw_unit`, false for a whole-block transform.)
703- } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {700+ true
704- false701+ } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
705- } else {702+ false
706- bit(tr_table)703+ } else {
707- };704+ bit(tr_table)
708- // has_bottom_left: bottom_available && left_available, col_off == 0.705+ };
709- let bottom_left = if x == 0 || y + bh >= height {706+ // has_bottom_left: bottom_available && left_available, col_off == 0.
710- false707+ let bottom_left = if x == 0 || y + bh >= height {
711- } else if blk_col_in_sb == 0 {708+ false
712- // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)709+ } else if blk_col_in_sb == 0 {
713- (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size710+ // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
714- } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {711+ (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
715- false712+ } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
716- } else {713+ false
717- bit(bl_table)714+ } else {
718- };715+ bit(bl_table)
719- (top_right, bottom_left)716+ };
720- }717+ (top_right, bottom_left)
721- for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {718+ }
722- let (tr, bl) = rect_reach_tables(bw, bh);719+ for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
723- let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();720+ let (tr, bl) = rect_reach_tables(bw, bh);
724- assert_eq!(721+ let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
725- (tr.len(), sum(tr), bl.len(), sum(bl)),722+ assert_eq!(
726- (tr_len, tr_sum, bl_len, bl_sum),723+ (tr.len(), sum(tr), bl.len(), sum(bl)),
727- "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"724+ (tr_len, tr_sum, bl_len, bl_sum),
728- );725+ "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
729- // Two superblocks across and down, so the superblock-relative726+ );
730- // position (and not the frame position) is what decides.727+ // Two superblocks across and down, so the superblock-relative
731- for sb_y in [0usize, 64] {728+ // position (and not the frame position) is what decides.
732- for sb_x in [0usize, 64] {729+ for sb_y in [0usize, 64] {
733- for y in (sb_y..sb_y + 64).step_by(bh) {730+ for sb_x in [0usize, 64] {
734- for x in (sb_x..sb_x + 64).step_by(bw) {731+ for y in (sb_y..sb_y + 64).step_by(bh) {
735- let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);732+ for x in (sb_x..sb_x + 64).step_by(bw) {
736- let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);733+ let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
737- assert_eq!(734+ let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
738- (got.above_right, got.below_left),735+ assert_eq!(
739- want,736+ (got.above_right, got.below_left),
740- "{bw}x{bh} at ({x}, {y})"737+ want,
741- );738+ "{bw}x{bh} at ({x}, {y})"
742- }739+ );
743 }740 }
744 }741 }
745 }742 }
746 }743 }
747 }744 }
745+}
748 746
749- /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.747+/// 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 {748+pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
751- let out = run_with_stdin(749+ let out = run_with_stdin(
752- ec_testkit::ffmpeg().args([750+ ec_testkit::ffmpeg().args([
753- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",751+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
754- ]),752+ ]),
755- stream,753+ stream,
756- );754+ );
757- assert!(755+ assert!(
758- out.status.success(),756+ out.status.success(),
759- "ffmpeg refused the stream: {}",757+ "ffmpeg refused the stream: {}",
760- String::from_utf8_lossy(&out.stderr)758+ String::from_utf8_lossy(&out.stderr)
761- );759+ );
762- let (luma, chroma) = (width * height, width * height / 4);760+ let (luma, chroma) = (width * height, width * height / 4);
763- assert_eq!(761+ assert_eq!(
764- out.stdout.len(),762+ out.stdout.len(),
765- luma + 2 * chroma,763+ luma + 2 * chroma,
766- "expected one 4:2:0 frame"764+ "expected one 4:2:0 frame"
767- );765+ );
768- Picture {766+ Picture {
769- width,767+ width,
770- height,768+ height,
771- y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),769+ y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
772- u: out.stdout[luma..luma + chroma]770+ u: out.stdout[luma..luma + chroma]
773- .iter()771+ .iter()
774- .map(|&v| u16::from(v))772+ .map(|&v| u16::from(v))
775- .collect(),773+ .collect(),
776- v: out.stdout[luma + chroma..]774+ v: out.stdout[luma + chroma..]
777- .iter()775+ .iter()
778- .map(|&v| u16::from(v))776+ .map(|&v| u16::from(v))
779- .collect(),777+ .collect(),
780- }
781 }778 }
779+}
782 780
783- /// A picture with something of everything in it: a gradient, an edge, a781+/// 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 block782+/// ripple and a block of flat colour, none of them aligned to the block
785- /// grid.783+/// grid.
786- /// The in-loop filters actually FIRE and the stream still decodes to784+/// The in-loop filters actually FIRE and the stream still decodes to
787- /// exactly what the encoder kept as its reconstruction785+/// exactly what the encoder kept as its reconstruction
788- /// (gate-blind-to-feature: a filter search that always answered "off"786+/// (gate-blind-to-feature: a filter search that always answered "off"
789- /// would leave every other test just as green, and the BD gate that787+/// would leave every other test just as green, and the BD gate that
790- /// would notice is `#[ignore]`d).788+/// would notice is `#[ignore]`d).
791- ///789+///
792- /// Run:790+/// Run:
793- /// cargo test -p ec-av1 --release --lib -- \791+/// cargo test -p ec-av1 --release --lib -- \
794- /// encode::tests::the_filter_search_picks_real_filters792+/// encode::tests::the_filter_search_picks_real_filters
795- #[test]793+#[test]
796- fn the_filter_search_picks_real_filters() {794+fn the_filter_search_picks_real_filters() {
797- let _knobs = crate::speed::knob_read();795+ let _knobs = crate::speed::knob_read();
798- let fctx = &crate::decode::FrameCtx::for_encoder();796+ let fctx = &crate::decode::FrameCtx::for_encoder();
799- let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();797+ 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();798+ let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
801- let fired = encoded799+ 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
802 .frames808 .frames
803 .iter()809 .iter()
804- .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)810+ .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
805- .count();811+ .collect::<Vec<_>>()
806- assert!(812+ );
807- fired > 0,813+ // The reconstruction the encoder predicts from is the FILTERED one,
808- "no frame of this sequence chose any in-loop filtering: {:?}",814+ // and it is what a decoder of the stream produces -- byte for byte,
809- encoded815+ // frame for frame.
810- .frames816+ let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
811- .iter()817+ assert_eq!(decoded.len(), encoded.frames.len());
812- .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))818+ for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
813- .collect::<Vec<_>>()819+ assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
814- );820+ assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
815- // The reconstruction the encoder predicts from is the FILTERED one,821+ assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
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- }
825 }822 }
823+}
826 824
827- pub(super) fn test_card(width: usize, height: usize) -> Picture {825+pub(super) fn test_card(width: usize, height: usize) -> Picture {
828- let mut picture = Picture::grey(width, height);826+ let mut picture = Picture::grey(width, height);
829- for y in 0..height {827+ for y in 0..height {
830- for x in 0..width {828+ for x in 0..width {
831- let gradient = x as f64 * 200.0 / width as f64;829+ let gradient = x as f64 * 200.0 / width as f64;
832- let ripple = 30.0830+ let ripple = 30.0
833- * (x as f64 * std::f64::consts::PI / 23.0).sin()831+ * (x as f64 * std::f64::consts::PI / 23.0).sin()
834- * (y as f64 * std::f64::consts::PI / 37.0).cos();832+ * (y as f64 * std::f64::consts::PI / 37.0).cos();
835- let edge = if x > width * 3 / 7 && y > height / 3 {833+ let edge = if x > width * 3 / 7 && y > height / 3 {
836- 40.0834+ 40.0
837- } else {835+ } else {
838- 0.0836+ 0.0
839- };837+ };
840- picture.y[y * width + x] =838+ picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
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- }
850 }839 }
851- picture
852 }840 }
853-841+ for y in 0..height / 2 {
854- pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 {842+ for x in 0..width / 2 {
855- let squared: f64 = a843+ let i = y * width / 2 + x;
856- .iter()844+ picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
857- .zip(b)845+ picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
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;
865 }846 }
866- 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
867 }847 }
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+}
868 1004
869- /// lane-i64's witness: a smooth gradient is exactly the picture a whole1005+/// The lane's own end-to-end check: on screen content the detector fires,
870- /// 64x64 intra block predicts as well as four 32x32 ones, so the key1006+/// blocks really take a palette (fire count, class
871- /// frame's new root fires on most superblocks -- and what BOTH decoders1007+/// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
872- /// produce is the encoder's own reconstruction, sample for sample.1008+/// symbol this lane writes -- reconstructs exactly what the encoder did.
873- ///1009+/// The film-shaped `test_card` must NOT trip the detector, which is what
874- /// The fire count is the `gate-blind-to-feature` guard: without it every1010+/// keeps every non-screen stream byte-identical.
875- /// assert below passes on a stream that codes no whole superblock at all.1011+#[test]
876- #[test]1012+fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
877- fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {1013+ let _knobs = crate::speed::knob_read();
878- let _knobs = crate::speed::knob_read();1014+ let fctx = &crate::decode::FrameCtx::for_encoder();
879- let fctx = &crate::decode::FrameCtx::for_encoder();1015+ let (width, height) = (192usize, 96usize);
880- // 4 x 3 superblocks, all of them wholly inside the frame.1016+ let _ = crate::tile::take_palette_hits();
881- let (width, height) = (256usize, 192usize);1017+ let picture = screen_card(width, height);
882- let mut picture = Picture::grey(width, height);1018+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
883- for y in 0..height {1019+ assert!(
884- for x in 0..width {1020+ encoded.screen,
885- picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;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+ }
886 }1066 }
887- }1067+ for y in 0..height / 2 {
888- for y in 0..height / 2 {1068+ for x in 0..width / 2 {
889- for x in 0..width / 2 {1069+ let sx = (x + f * 3) % (width / 2);
890- picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;1070+ out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
891- picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;1071+ out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
1072+ }
892 }1073 }
893- }1074+ out
894- let _ = take_i64_root_hits();1075+ })
895- let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();1076+ .collect();
896- let [roots, _offered, _edge] = take_i64_root_hits();1077+ let _ = crate::tile::take_palette_hits();
897- // The counters are process-global, so another test encoding in1078+ let _ = crate::tile::take_palette_uv_hits();
898- // parallel can only ADD to them -- the per-FRAME fact is the mode1079+ let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
899- // list, which carries one entry per coded block and so exactly 121080+ let gop_hits = crate::tile::take_palette_hits();
900- // when every superblock was coded as one 64x64 intra block.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() {
901 assert_eq!(1103 assert_eq!(
902- encoded.modes.len(),1104+ ours.y, frame.reconstruction.y,
903- 12,1105+ "our decoder: GOP frame {i} luma"
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"
909 );1106 );
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");
922 }1107 }
923-1108+ {
924- /// The claim the whole encoder rests on: what a decoder produces is what1109+ let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
925- /// the encoder said it would, sample for sample, on every plane.1110+ assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
926- ///1111+ for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
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);
944 assert_eq!(1112 assert_eq!(
945- decoded.y, encoded.reconstruction.y,1113+ theirs.y, frame.reconstruction.y,
946- "{width}x{height}: luma"1114+ "ffmpeg: GOP frame {i} luma"
947 );1115 );
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::*;
2 1
3- fn test_card(width: usize, height: usize, shift: usize) -> Picture {2+use super::*;
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- }
20 3
21- /// Drives a whole stream through the facade the way a caller must since4+fn test_card(width: usize, height: usize, shift: usize) -> Picture {
22- /// it holds one picture of lookahead: every picture through5+ let mut picture = Picture::grey(width, height);
23- /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].6+ for y in 0..height {
24- fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {7+ for x in 0..width {
25- let mut packets = Vec::with_capacity(pictures.len());8+ let sx = (x + shift) % width;
26- for (i, picture) in pictures.iter().enumerate() {9+ picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
27- packets.extend(
28- enc.encode_frames(picture)
29- .unwrap_or_else(|e| panic!("picture {i}: {e}")),
30- );
31 }10 }
32- packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));11+ }
33- packets12+ for y in 0..height / 2 {
34- }13+ for x in 0..width / 2 {
35-14+ let i = y * (width / 2) + x;
36- /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden15+ picture.u[i] = ((100 + shift * 4) % 256) as u16;
37- /// counts and leaf count match the packets a real run emits, at three16+ picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
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- );
103 }17 }
104 }18 }
19+ picture
20+}
105 21
106- /// A level at its quantizer BOUND hands its unspent bytes to the levels22+/// Drives a whole stream through the facade the way a caller must since
107- /// that can still move ([[vorbis-rate-loop-windup]]'s class in the23+/// it holds one picture of lookahead: every picture through
108- /// small), and it does so AT ONCE, not once the bound level's frames are24+/// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
109- /// all coded: the loop is driven by a synthetic per-level model where the25+fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
110- /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=25526+ let mut packets = Vec::with_capacity(pictures.len());
111- /// clamp) and spends half its plan, and the leaves' target must jump to27+ for (i, picture) in pictures.iter().enumerate() {
112- /// the run's remainder with EVERY remaining hidden frame priced at that28+ packets.extend(
113- /// measured rate. The old division -- whole remainder over whole29+ enc.encode_frames(picture)
114- /// remaining weight -- handed most of the shortfall straight back to the30+ .unwrap_or_else(|e| panic!("picture {i}: {e}")),
115- /// hidden slot (which carries most of the pyramid's weight and cannot31+ );
116- /// spend it), so the leaves only saw the surplus at the end of the run,32+ }
117- /// when there was nothing left to code with it.33+ packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
118- #[test]34+ packets
119- fn a_bound_level_hands_its_unspent_bytes_to_the_others() {35+}
120- let pyramid = Pyramid::default();36+
121- let (gop, target_bytes) = (48usize, 2_000.0);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();
122 let (hidden, leaves) = gop_shape(pyramid, gop);76 let (hidden, leaves) = gop_shape(pyramid, gop);
123- let run_bytes = target_bytes * gop as f64;77+ let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
124- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);78+ assert_eq!(
125- let scale0 = rl.target[2];79+ (hidden_frames, leaves, 1),
126- let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();80+ (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
127- // The key codes exactly its plan; the first hidden frame is at the81+ "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
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
144 );82 );
145- assert!(83+ assert_eq!(
146- (rl.target[2] - want).abs() < 1e-6,84+ hidden_frames + leaves + 1,
147- "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \85+ gop,
148- give {:.3})",86+ "gop {gop}: every picture is coded exactly once"
149- rl.target[2],
150- (run_bytes - key_bytes - arf_bytes)
151- / (leaves as f64 + hidden_weight - rl.weight(offset))
152 );87 );
153- // And the re-plan stays BOUNDED: hidden levels that spend nothing at88+ // The plan adds up: one leaf's target times the run's whole
154- // all cannot run the leaves' target away.89+ // weight is the run's whole budget.
155- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);90+ let target_bytes = 2_000.0;
156- rl.update(Level::Key, 0, 100, key_bytes as usize);91+ let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
157- for &(offset, n) in &hidden {92+ let planned = loop_.target[0]
158- for _ in 0..n {93+ + loop_.target[2]
159- rl.update(Level::Arf, offset, 0, 1);94+ * (leaves as f64
160- }95+ + hidden
161- }96+ .iter()
97+ .map(|&(o, n)| n as f64 * loop_.weight(o))
98+ .sum::<f64>());
162 assert!(99 assert!(
163- rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,100+ (planned - target_bytes * gop as f64).abs() < 1.0,
164- "the re-plan is unbounded: leaf target {:.1} past {:.1}",101+ "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
165- rl.target[2],102+ target_bytes * gop as f64
166- scale0 * RateLoop::REPLAN_CLAMP
167 );103 );
168- // ... and BOTH ways: a re-plan that reached zero would stop the loop104+ }
169- // dead (`update` returns on a non-positive target).105+}
170- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);106+
171- rl.update(Level::Key, 0, 100, key_bytes as usize);107+/// A level at its quantizer BOUND hands its unspent bytes to the levels
172- for &(offset, n) in &hidden {108+/// that can still move ([[vorbis-rate-loop-windup]]'s class in the
173- for _ in 0..n {109+/// small), and it does so AT ONCE, not once the bound level's frames are
174- rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);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+ );
175 }219 }
176 }220 }
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 }221 }
184-222+}
185- /// The mini-GOP layout leaves no short tail group, and leaves the long223+
186- /// GOP the fixed rule already coded alone: 47 inter pictures are224+/// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
187- /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),225+/// in order.
188- /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).226+fn concat(packets: &[Packet]) -> Vec<u8> {
189- #[test]227+ packets.iter().flat_map(|p| p.data.clone()).collect()
190- fn the_mini_gop_layout_leaves_no_short_tail() {228+}
191- let groups = |remaining: usize, mini_gop: usize, absorb: bool| {229+
192- let (mut left, mut out) = (remaining, Vec::new());230+/// The facade's latency contract (lane-av1facade, deepened on
193- while left > 0 {231+/// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
194- let g = group_target(left, mini_gop, absorb).min(left);232+/// their picture back and return an empty packet, every later call
195- assert!(g > 0);233+/// returns the packet of the picture that many frames earlier, and
196- out.push(g);234+/// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
197- left -= g;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());
198 }339 }
199- out340+ packets.extend(enc.flush().unwrap());
200- };341+ assert_eq!(
201- // gop 48: what mini_gop 8 already coded, under either rule.342+ enc.pyramid().is_none(),
202- assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);343+ is_screen,
203- assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);344+ "{content} q={q}: the content gate read this clip the other way round"
204- // gop 12: 8 + 3 becomes one group of 11.345+ );
205- assert_eq!(groups(11, 8, false), vec![8, 3]);346+ let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
206- assert_eq!(groups(11, 8, true), vec![11]);347+ assert_eq!(
207- // A run shorter than a group is one group, as before (the 4-picture348+ (
208- // pin clip).349+ packets.iter().map(|p| p.data.len()).sum::<usize>(),
209- assert_eq!(groups(3, 8, true), vec![3]);350+ concat(&packets)
210- // No group is ever below half the shape, and none is over 1.5x it.351+ ),
211- for mini_gop in 2..=16 {352+ (sequence.stream.len(), sequence.stream.clone()),
212- for remaining in 1..=64 {353+ "{content} q={q}: the facade's stream is not the sequence path's"
213- for g in groups(remaining, mini_gop, true) {354+ );
214- assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");355+ assert_eq!(
215- assert!(356+ sequence.frames.len(),
216- g * 2 >= mini_gop || remaining < mini_gop,357+ frames,
217- "{remaining}/{mini_gop}: short tail {g}"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"
218 );373 );
219 }374 }
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+ );
220 }380 }
221 }381 }
222 }382 }
223-383+}
224- /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated384+
225- /// in order.385+/// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
226- fn concat(packets: &[Packet]) -> Vec<u8> {386+/// the caller but applied only to camera material. Over screen content
227- packets.iter().flat_map(|p| p.data.clone()).collect()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+ );
228 }580 }
229-581+}
230- /// The facade's latency contract (lane-av1facade, deepened on582+
231- /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold583+/// The configured colour properties are what `ffprobe` reports back,
232- /// their picture back and return an empty packet, every later call584+/// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
233- /// returns the packet of the picture that many frames earlier, and585+/// is the default a player assumes and the one this test would silently
234- /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets586+/// pass without wiring for (`ffprobe` reports "unknown" for the
235- /// exactly one non-empty packet per picture, `depth - 1` calls later.587+/// hardcoded "unspecified" this crate wrote before the facade existed,
236- #[test]588+/// which is a visibly different string).
237- fn one_in_one_out_delayed_by_the_lookahead_depth() {589+#[test]
238- let _knobs = crate::speed::knob_read();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] {
239 let config = EncoderConfig {940 let config = EncoderConfig {
240- width: 64,941+ width,
241- height: 64,942+ height,
242 base_q_idx: 100,943 base_q_idx: 100,
243- gop: 2,944+ gop: frames,
244 colour: Colour::Bt709Limited,945 colour: Colour::Bt709Limited,
245 tile_cols_log2: 0,946 tile_cols_log2: 0,
246 tile_rows_log2: 0,947 tile_rows_log2: 0,
247 };948 };
248- let delay = crate::encode::tpl_depth() as u64 - 1;949+ let rate = RateTarget::Bitrate {
249- let pictures = delay + 5;950+ bits_per_second,
250- let mut enc = Av1Encoder::new(config).unwrap();951+ frames_per_second: fps,
251- for t in 0..pictures {952+ };
252- let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();953+ for pyramid in [None, Some(Pyramid::default())] {
253- if t < delay {954+ let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some());
254- assert!(packet.data.is_empty(), "call {t} holds its picture back");955+ // Shared, not cloned: the 48 decoded frames are ~35 MB of
255- continue;956+ // `u16` luma+chroma, and all eight arms want the same ones.
256- }957+ let pictures = std::sync::Arc::clone(&pictures);
257- assert!(!packet.data.is_empty(), "picture {t}: empty packet");958+ // `None` is a progress ticket: THIS call returned. `Some` is
258- assert_eq!(packet.order, t - delay, "picture {t}: order");959+ // the arm's result, sent after `flush` -- which is itself a
259- }960+ // call that can spin, so it needs a ticket too, not a bare
260- let tail = enc.flush().unwrap();961+ // `join` that would block forever.
261- assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");962+ let (tx, rx) = std::sync::mpsc::channel::<Option<ArmResult>>();
262- for (i, p) in tail.iter().enumerate() {963+ let worker = std::thread::spawn(move || {
263- assert_eq!(964+ let mut enc = match pyramid {
264- p.order,965+ None => Av1Encoder::with_rate_target(config, rate).unwrap(),
265- pictures - delay + i as u64,966+ Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
266- "flushed packet {i}: order"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(),
267 );1026 );
268- assert!(!p.data.is_empty(), "flushed packet {i}: empty");
269 }1027 }
270- assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
271 }1028 }
272-1029+}
273- /// A screen-like card: hard-edged 4-pixel bands of two flat luma values1030+/// The `BytesPerFrame` controller's own windup bound: no frame's coded
274- /// with a moving block over the lower half — few colours per 16x16 block1031+/// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
275- /// at high variance, which is exactly what1032+/// clip's full range of content (so a scene cut can't be the one frame
276- /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the1033+/// that breaks the bound).
277- /// gate below runs the real detector rather than an override.1034+///
278- fn screen_card(width: usize, height: usize, shift: usize) -> Picture {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 {
279 let mut picture = Picture::grey(width, height);1176 let mut picture = Picture::grey(width, height);
280 for y in 0..height {1177 for y in 0..height {
281 for x in 0..width {1178 for x in 0..width {
282- let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };1179+ let cell = ((x + shift) / 8 + y / 8) % 2;
283- let over = y >= height / 2 && (x + shift) % width < width / 3;1180+ picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
284- picture.y[y * width + x] = if over { 128 } else { band };
285 }1181 }
286 }1182 }
287 picture1183 picture
288- }1184+ };
289-1185+ let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
290- /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on1186+ let config = EncoderConfig {
291- /// lane-av1pyrdef): the streaming facade — what the editor's export1187+ width,
292- /// drives — codes byte for byte what [`crate::encode::encode_sequence`]1188+ height,
293- /// codes, which is the path the BD gate measures. Both now drive ONE1189+ base_q_idx: 60,
294- /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the1190+ gop: 2,
295- /// identity is by construction; this pins it anyway, over both content1191+ colour: Colour::Bt709Limited,
296- /// classes the content gate splits:1192+ tile_cols_log2: 0,
297- ///1193+ tile_rows_log2: 0,
298- /// * film-like (the gate's own clip when the fixture is there, a1194+ };
299- /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the1195+ let mut enc = Av1Encoder::new(config).unwrap();
300- /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two1196+ crate::tile::reset_palette_cut_maps_written();
301- /// paths' whole streams are identical;1197+ let mut stream = Vec::new();
302- /// * screen-like: the content gate drops BOTH paths back to flat, one1198+ for packet in encode_all(&mut enc, &sources) {
303- /// packet per picture, identical frame by frame as well as whole.1199+ stream.extend_from_slice(&packet.data);
304- ///1200+ }
305- /// Never skipped, since a skipped identity gate is the defect it is meant1201+ eprintln!(
306- /// to catch.1202+ "{NAME}: {} cut colour-index maps written",
307- #[test]1203+ crate::tile::palette_cut_maps_written()
308- fn the_facade_codes_the_same_bytes_as_encode_sequence() {1204+ );
309- let _knobs = crate::speed::knob_read();1205+ assert!(
310- let frames = 12usize;1206+ crate::tile::palette_cut_maps_written() > 0,
311- let film = h264_clip_frames(640, 384, frames)1207+ "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
312- .unwrap_or_else(|| {1208+ );
313- // The probe inside already printed the ONE line naming the1209+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
314- // resolved path and the escape hatch, so this is a note about1210+ assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
315- // what runs instead — not a second SKIP.1211+ let theirs = ffmpeg_decode_planes(&stream, width, height);
316- eprintln!(" ...so the film arm runs on a synthetic card, not real film");1212+ assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
317- (0..frames).map(|t| test_card(64, 64, t)).collect()1213+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
318- });1214+ for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
319- let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();1215+ let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
320- let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");1216+ if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
321- for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {1217+ let w = if plane == "luma" { width } else { width / 2 };
322- let (width, height) = (pictures[0].width, pictures[0].height);1218+ panic!(
323- for q in [150u8, 60] {1219+ "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
324- let config = EncoderConfig {1220+ at % w,
325- width,1221+ at / w,
326- height,1222+ got[at],
327- base_q_idx: q,1223+ want[at],
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"
360 );1224 );
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- }
382 }1225 }
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+ );
383 }1233 }
384 }1234 }
385-1235+}
386- /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by1236+
387- /// the caller but applied only to camera material. Over screen content1237+/// A pyramid stream reorders pictures: the hidden `ALTREF` of each
388- /// the encoder must drop back to the flat path and code byte for byte1238+/// mini-GOP is coded before the leaves that precede it in display order,
389- /// what a flat encoder codes — that is what keeps the BD gate's screen1239+/// and a `show_existing_frame` header puts it back. This pins the shape
390- /// row identical to the flat baseline — and over non-screen content the1240+/// (one packet per source picture plus one `show_existing_frame` per
391- /// same request must still reorder (class `gate-blind-to-feature`: a gate1241+/// group, `dts` monotone, `order` NOT monotone) and then decodes the
392- /// that only checked the screen half would pass with the pyramid deleted).1242+/// whole stream through OUR decoder and through ffmpeg/dav1d and requires
393- #[test]1243+/// the two display-order outputs to agree sample for sample — the
394- fn the_content_gate_keeps_screen_streams_flat() {1244+/// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
395- let _knobs = crate::speed::knob_read();1245+/// output, or output twice, or output in the wrong position, changes the
396- let frames = 8usize;1246+/// display-order list and fails here.
397- let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();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| {
398 let config = EncoderConfig {1314 let config = EncoderConfig {
399- width: 64,1315+ width: 128,
400- height: 64,1316+ height: 128,
401 base_q_idx: 120,1317 base_q_idx: 120,
402- gop: frames,1318+ gop: 32,
403- colour: Colour::Unspecified,1319+ colour: Colour::Bt709Limited,
404 tile_cols_log2: 0,1320 tile_cols_log2: 0,
405 tile_rows_log2: 0,1321 tile_rows_log2: 0,
406 };1322 };
407- crate::encode::force_screen(Some(true));1323+ let pyramid = Pyramid {
408- let mut flat = Av1Encoder::new(config).unwrap();1324+ key_q_offset: offset,
409- let flat_packets = encode_all(&mut flat, &pictures);1325+ ..Pyramid::default()
410- let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();1326+ };
411- let gated_packets = encode_all(&mut gated, &pictures);1327+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
412- assert_eq!(1328+ let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
413- gated.pyramid(),1329+ let key = packets
414- None,1330+ .iter()
415- "the gate left a screen stream on the pyramid"1331+ .find(|p| p.level == Level::Key)
416- );1332+ .expect("key frame");
417- assert_eq!(1333+ key.data.len()
418- concat(&gated_packets),1334+ };
419- concat(&flat_packets),1335+ let (base, finer) = (key_bytes(0), key_bytes(-48));
420- "a screen stream's bytes are not the flat path's"1336+ eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
421- );1337+ assert!(
422- crate::encode::force_screen(Some(false));1338+ finer > base,
423- let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();1339+ "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
424- let kept_packets = encode_all(&mut kept, &pictures);1340+ );
425- assert_eq!(1341+}
426- kept.pyramid(),1342+
427- Some(Pyramid::default()),1343+/// lane-last2's witness: a clip whose pictures ALTERNATE between two
428- "the gate ate a film stream"1344+/// textures, so for every leaf the picture two back is an exact match and
429- );1345+/// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf
430- assert!(1346+/// chain alternates its refresh over [`LEAF_SLOTS`] and names the older
431- kept_packets.iter().any(|p| p.level == Level::Arf),1347+/// slot `LAST2_FRAME`; blocks must actually be CODED off it
432- "a non-screen stream coded no hidden frame"1348+/// ([[gate-blind-to-feature]]: a slot that is retained but never chosen
433- );1349+/// proves only that the bookkeeping compiles), the stream must decode
434- crate::encode::force_screen(None);1350+/// sample-exact through OUR decoder and through ffmpeg, and the hidden
435- }1351+/// frames must still come out in display order. With the lever OFF the
436-1352+/// same clip codes ZERO `LAST2` blocks, which is what makes the counter a
437- /// A key frame every `gop` pictures, inter otherwise — checked against1353+/// measurement of this lane and not of the reference set we already had.
438- /// what the facade itself reports, and (below) against what `ffprobe`1354+#[test]
439- /// reads back out of the coded bytes.1355+fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() {
440- #[test]1356+ let _knobs = crate::speed::knob_write();
441- fn gop_cadence_is_honored() {1357+ crate::encode::force_screen(Some(false));
442- let _knobs = crate::speed::knob_read();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));
443 let config = EncoderConfig {1364 let config = EncoderConfig {
444- width: 64,1365+ width,
445- height: 64,1366+ height,
446- base_q_idx: 100,1367+ base_q_idx: 120,
447- gop: 3,1368+ gop: 32,
448- colour: Colour::Unspecified,1369+ colour: Colour::Bt709Limited,
449 tile_cols_log2: 0,1370 tile_cols_log2: 0,
450 tile_rows_log2: 0,1371 tile_rows_log2: 0,
451 };1372 };
452- let mut enc = Av1Encoder::new(config).unwrap();1373+ let pyramid = Pyramid {
453- let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();1374+ mini_gop: 4,
454- let keys: Vec<bool> = encode_all(&mut enc, &pictures)1375+ mid_q_offset: None,
455- .iter()1376+ ..Pyramid::default()
456- .map(|p| p.key)1377+ };
457- .collect();1378+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
458- assert_eq!(keys, vec![true, false, false, true, false, false, true]);1379+ let _ = crate::encode::take_ref_frame_hits();
459- }1380+ let mut packets = Vec::new();
460-1381+ for picture in &sources {
461- fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {1382+ packets.extend(enc.encode_frames(picture).unwrap());
462- let path = std::env::temp_dir().join(format!(1383+ }
463- "ec-av1-facade-probe-{}-{}.obu",1384+ packets.extend(enc.flush().unwrap());
464- std::process::id(),1385+ let hits = crate::encode::take_ref_frame_hits();
465- std::ptr::addr_of!(stream) as usize1386+ (hits, concat(&packets), packets)
466- ));1387+ };
467- std::fs::write(&path, stream).expect("writing the probe stream");1388+ let (off_hits, off_stream, _) = run(false);
468- let out = ec_testkit::ffprobe()1389+ let (on_hits, stream, packets) = run(true);
469- .args([1390+ set_last2(None);
470- "-v",1391+ eprintln!(
471- "error",1392+ "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
472- "-f",1393+ on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
473- "obu",1394+ off_hits[1],
474- "-select_streams",1395+ off_hits[2],
475- "v:0",1396+ off_hits[4],
476- "-show_entries",1397+ off_hits[7],
477- "frame=key_frame,width,height",1398+ off_stream.len(),
478- "-of",1399+ on_hits[1],
479- "csv=p=0",1400+ on_hits[2],
480- ])1401+ on_hits[4],
481- .arg(&path).output()1402+ on_hits[7],
482- .expect("ffprobe failed to run");1403+ stream.len(),
483- let _ = std::fs::remove_file(&path);1404+ );
484- assert!(1405+ assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
485- out.status.success(),1406+ assert!(
486- "ffprobe refused the stream: {}",1407+ on_hits[2] >= 8,
487- String::from_utf8_lossy(&out.stderr)1408+ "the picture two back matches exactly and only {} blocks were coded off LAST2",
488- );1409+ on_hits[2],
489- String::from_utf8_lossy(&out.stdout)1410+ );
490- .lines()1411+
491- .map(|line| {1412+ // Display order and sample-exactness, both decoders (the same shape
492- let mut f = line.trim().split(',');1413+ // `pyramid_round_trip` gates the hidden frames with).
493- let key: u32 = f.next().unwrap().parse().unwrap();1414+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
494- let width: u32 = f.next().unwrap().parse().unwrap();1415+ assert_eq!(
495- let height: u32 = f.next().unwrap().parse().unwrap();1416+ ours.len(),
496- (key == 1, width, height)1417+ sources.len(),
497- })1418+ "our decoder's display-order count"
498- .collect()1419+ );
499- }1420+ let theirs = ffmpeg_decode_luma(&stream, width, height);
500-1421+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
501- fn ffprobe_colour(stream: &[u8]) -> String {1422+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
502- let path = std::env::temp_dir().join(format!(1423+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
503- "ec-av1-facade-colour-probe-{}-{}.obu",1424+ assert_eq!(got.len(), b.len(), "frame {i}: luma size");
504- std::process::id(),1425+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
505- std::ptr::addr_of!(stream) as usize1426+ panic!(
506- ));1427+ "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
507- std::fs::write(&path, stream).expect("writing the probe stream");1428+ at % width,
508- let out = ec_testkit::ffprobe()1429+ at / width,
509- .args([1430+ got[at],
510- "-v",1431+ b[at],
511- "error",1432+ );
512- "-f",1433+ }
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()
530 }1434 }
531-1435+ // The reordering itself is unchanged by the second leaf slot.
532- /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)1436+ let shown = packets
533- /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that1437+ .iter()
534- /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and1438+ .filter(|p| p.level == Level::ShowExisting)
535- /// coded size confirm what the facade already reported.1439+ .count();
536- #[test]1440+ let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
537- fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {1441+ assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
538- let _knobs = crate::speed::knob_read();1442+}
539- let (width, height) = (96usize, 96usize);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));
540 let config = EncoderConfig {1503 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(
789 pair: bool,789 pair: bool,
790 ) {790 ) {
791 if pair {791 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+ {
793 let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;797 let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;
794 let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)798 let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)
795 .clamp(0, p.index_max);799 .clamp(0, p.index_max);
@@ -1287,12 +1291,6 @@ thread_local! {
1287 static GRAIN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };1291 static GRAIN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1288 }1292 }
1289 1293
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-
1296 /// Copies the clean rows `*lcur..l_to` (luma) and `*ccur..c_to` (chroma) of1294 /// Copies the clean rows `*lcur..l_to` (luma) and `*ccur..c_to` (chroma) of
1297 /// `src` into `out`, advancing the cursors. [`apply_grain`]'s bands fill1295 /// `src` into `out`, advancing the cursors. [`apply_grain`]'s bands fill
1298 /// their own uninitialised destination rows with this before adding noise.1296 /// their own uninitialised destination rows with this before adding noise.
@@ -2571,16 +2569,18 @@ mod ragged_grain_tests {
2571 }2569 }
2572 for col in 0..w {2570 for col in 0..w {
2573 let mut g = sl[(i * w + col) as usize];2571 let mut g = sl[(i * w + col) as usize];
2574- if overlap && i < 22572+ if overlap
2575- && let Some((p, _, _)) = &prev {2573+ && i < 2
2576- let old = p[((i + 32) * w + col) as usize];2574+ && let Some((p, _, _)) = &prev
2577- g = if i == 0 {2575+ {
2578- old * 27 + g * 172576+ let old = p[((i + 32) * w + col) as usize];
2579- } else {2577+ g = if i == 0 {
2580- old * 17 + g * 272578+ old * 27 + g * 17
2581- };2579+ } else {
2582- g = round2(g, 5).clamp(gmin, gmax);2580+ old * 17 + g * 27
2583- }2581+ };
2582+ g = round2(g, 5).clamp(gmin, gmax);
2583+ }
2584 nl[(row * w + col) as usize] = g;2584 nl[(row * w + col) as usize] = g;
2585 }2585 }
2586 }2586 }
crates/ec-av1/src/intra.rsmodified+55 -40
@@ -152,7 +152,8 @@ impl Edges {
152 left: Option<&[u16]>,152 left: Option<&[u16]>,
153 corner: Option<u16>,153 corner: Option<u16>,
154 bw: usize,154 bw: usize,
155- bh: usize, fctx: &crate::decode::FrameCtx,155+ bh: usize,
156+ fctx: &crate::decode::FrameCtx,
156 ) -> Self {157 ) -> Self {
157 let want = bw + bh;158 let want = bw + bh;
158 // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)`159 // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)`
@@ -249,25 +250,6 @@ thread_local! {
249 static EDGE_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };250 static EDGE_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
250 }251 }
251 252
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-
271 #[allow(clippy::too_many_arguments)]253 #[allow(clippy::too_many_arguments)]
272 pub(crate) fn predict(254 pub(crate) fn predict(
273 mode: u8,255 mode: u8,
@@ -279,7 +261,8 @@ pub(crate) fn predict(
279 bh: usize,261 bh: usize,
280 enable_edge_filter: bool,262 enable_edge_filter: bool,
281 smooth_neighbor: bool,263 smooth_neighbor: bool,
282- dst: &mut [u16], fctx: &crate::decode::FrameCtx,264+ dst: &mut [u16],
265+ fctx: &crate::decode::FrameCtx,
283 ) {266 ) {
284 assert_eq!(dst.len(), bw * bh, "the destination is the block");267 assert_eq!(dst.len(), bw * bh, "the destination is the block");
285 let edges = Edges::build(above, left, corner, bw, bh, fctx);268 let edges = Edges::build(above, left, corner, bw, bh, fctx);
@@ -306,7 +289,8 @@ pub(crate) fn predict(
306 smooth_neighbor,289 smooth_neighbor,
307 n_top,290 n_top,
308 n_left,291 n_left,
309- dst, fctx,292+ dst,
293+ fctx,
310 );294 );
311 return;295 return;
312 }296 }
@@ -530,7 +514,8 @@ fn directional(
530 smooth_neighbor: bool,514 smooth_neighbor: bool,
531 n_top: usize,515 n_top: usize,
532 n_left: usize,516 n_left: usize,
533- dst: &mut [u16], fctx: &crate::decode::FrameCtx,517+ dst: &mut [u16],
518+ fctx: &crate::decode::FrameCtx,
534 ) {519 ) {
535 let (w, h) = (bw as i32, bh as i32);520 let (w, h) = (bw as i32, bh as i32);
536 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.521 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.
@@ -542,7 +527,10 @@ fn directional(
542 // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner:527 // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner:
543 // that is exactly `Edges`' own layout (lane-alloc), so take the buffers528 // that is exactly `Edges`' own layout (lane-alloc), so take the buffers
544 // rather than copying them into two fresh ones per directional block.529 // 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;
546 534
547 if enable_edge_filter && angle != 90 && angle != 180 {535 if enable_edge_filter && angle != 90 && angle != 180 {
548 if need_above && need_left && reach >= 24 {536 if need_above && need_left && reach >= 24 {
@@ -599,7 +587,10 @@ fn directional(
599 // the blend's `&dyn Fn` indirection all used to sit inside the pixel587 // the blend's `&dyn Fn` indirection all used to sit inside the pixel
600 // loop; they are per-block (per-row for the shift) constants.588 // loop; they are per-block (per-row for the shift) constants.
601 let blend = |edge: &[i32], off: i32, base: i32, shift: i32| {589 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+ )
603 };594 };
604 if angle < 90 {595 if angle < 90 {
605 let dx = dr_intra_derivative(angle);596 let dx = dr_intra_derivative(angle);
@@ -656,7 +647,12 @@ fn directional(
656 blend(above_buf, above_off, base, ((x << up_a) & 0x3F) >> 1)647 blend(above_buf, above_off, base, ((x << up_a) & 0x3F) >> 1)
657 } else {648 } else {
658 let y2 = yrow - (col as i32 + 1) * dy;649 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+ )
660 };656 };
661 *d = value.clamp(0, max) as u16;657 *d = value.clamp(0, max) as u16;
662 }658 }
@@ -673,7 +669,13 @@ fn directional(
673 /// before `dc_predictor` averages, so a slice truncated short by the true669 /// before `dc_predictor` averages, so a slice truncated short by the true
674 /// frame edge must be extended by repetition here too, not averaged over its670 /// frame edge must be extended by repetition here too, not averaged over its
675 /// own shorter length.671 /// 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 {
677 // lane-perf4: the replication is only ever *summed*, never indexed, so679 // lane-perf4: the replication is only ever *summed*, never indexed, so
678 // the extended edge is a sum rather than the `Vec<u16>` it used to be680 // the extended edge is a sum rather than the `Vec<u16>` it used to be
679 // built as (two allocations per intra block, 0.9% of a 1080p decode's681 // built as (two allocations per intra block, 0.9% of a 1080p decode's
@@ -807,7 +809,8 @@ pub(crate) fn predict_filter_intra(
807 corner: Option<u16>,809 corner: Option<u16>,
808 bw: usize,810 bw: usize,
809 bh: usize,811 bh: usize,
810- dst: &mut [u16], fctx: &crate::decode::FrameCtx,812+ dst: &mut [u16],
813+ fctx: &crate::decode::FrameCtx,
811 ) {814 ) {
812 assert_eq!(dst.len(), bw * bh, "the destination is the block");815 assert_eq!(dst.len(), bw * bh, "the destination is the block");
813 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");816 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
@@ -842,7 +845,8 @@ pub(crate) fn predict_filter_intra(
842 for k in 0..8 {845 for k in 0..8 {
843 let (r_off, c_off) = (k >> 2, k & 3);846 let (r_off, c_off) = (k >> 2, k & 3);
844 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();847 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));
846 let idx = (r + r_off) * (bw + 1) + c + c_off;850 let idx = (r + r_off) * (bw + 1) + c + c_off;
847 buffer[idx] = value;851 buffer[idx] = value;
848 }852 }
@@ -1021,7 +1025,7 @@ mod tests {
1021 /// on three seeded random edges.1025 /// on three seeded random edges.
1022 #[test]1026 #[test]
1023 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {1027 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();
1025 // xorshift64*: a seeded stream, so a failure names one (shape, mode,1029 // xorshift64*: a seeded stream, so a failure names one (shape, mode,
1026 // seed) triple that reproduces.1030 // seed) triple that reproduces.
1027 let rng = |state: &mut u64| {1031 let rng = |state: &mut u64| {
@@ -1064,9 +1068,7 @@ mod tests {
1064 let mut want = vec![0u16; bw * bh];1068 let mut want = vec![0u16; bw * bh];
1065 let mut c_above = vec![corner];1069 let mut c_above = vec![corner];
1066 c_above.extend_from_slice(&above);1070 c_above.extend_from_slice(&above);
1067- libaom_filter_intra_predictor(1071+ libaom_filter_intra_predictor(&mut want, bw, bh, &c_above, &left, mode, bd);
1068- &mut want, bw, bh, &c_above, &left, mode, bd,
1069- );
1070 let mut got = vec![0u16; bw * bh];1072 let mut got = vec![0u16; bw * bh];
1071 predict_filter_intra(1073 predict_filter_intra(
1072 mode,1074 mode,
@@ -1075,7 +1077,8 @@ mod tests {
1075 Some(corner),1077 Some(corner),
1076 bw,1078 bw,
1077 bh,1079 bh,
1078- &mut got, fctx,1080+ &mut got,
1081+ fctx,
1079 );1082 );
1080 assert_eq!(1083 assert_eq!(
1081 got, want,1084 got, want,
@@ -1087,7 +1090,11 @@ mod tests {
1087 }1090 }
1088 }1091 }
1089 crate::decode::set_bit_depth(8, fctx);1092 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+ );
1091 }1098 }
1092 1099
1093 /// Spec 7.11.2.5 divides the rect DC average exactly. A 4x16 block (a 1:41100 /// Spec 7.11.2.5 divides the rect DC average exactly. A 4x16 block (a 1:4
@@ -1126,7 +1133,7 @@ mod tests {
1126 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).1133 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).
1127 #[test]1134 #[test]
1128 fn rect_predictors_match_c_dump() {1135 fn rect_predictors_match_c_dump() {
1129- let fctx = &crate::decode::FrameCtx::new();1136+ let fctx = &crate::decode::FrameCtx::new();
1130 let expected_txt = std::fs::read_to_string(concat!(1137 let expected_txt = std::fs::read_to_string(concat!(
1131 env!("CARGO_MANIFEST_DIR"),1138 env!("CARGO_MANIFEST_DIR"),
1132 "/../../lanes/intrarect_dump.expected.txt"1139 "/../../lanes/intrarect_dump.expected.txt"
@@ -1203,7 +1210,11 @@ mod tests {
1203 let left = fill(reach, 2);1210 let left = fill(reach, 2);
1204 let corner = ((bw * 3 + bh * 5) % 256) as u16;1211 let corner = ((bw * 3 + bh * 5) % 256) as u16;
1205 1212
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+ ] {
1207 let mut dst = vec![0u16; bw * bh];1218 let mut dst = vec![0u16; bw * bh];
1208 predict(1219 predict(
1209 mode,1220 mode,
@@ -1215,7 +1226,8 @@ mod tests {
1215 bh,1226 bh,
1216 false,1227 false,
1217 false,1228 false,
1218- &mut dst, fctx,1229+ &mut dst,
1230+ fctx,
1219 );1231 );
1220 let got = if name == "DC" {1232 let got = if name == "DC" {
1221 u64::from(dst[0])1233 u64::from(dst[0])
@@ -1243,12 +1255,15 @@ mod tests {
1243 bh,1255 bh,
1244 ef,1256 ef,
1245 sn,1257 sn,
1246- &mut dst, fctx,1258+ &mut dst,
1259+ fctx,
1247 );1260 );
1248 let got = checksum(&dst);1261 let got = checksum(&dst);
1249 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));1262 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));
1250 let want = *expected.get(&key).unwrap_or_else(|| {1263 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+ )
1252 });1267 });
1253 assert_eq!(1268 assert_eq!(
1254 got, want,1269 got, want,
crates/ec-av1/src/mc.rsmodified+32 -11
@@ -515,7 +515,16 @@ mod simd {
515 c += 16;515 c += 16;
516 }516 }
517 if c < block_w {517 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+ );
519 }528 }
520 }529 }
521 }530 }
@@ -966,7 +975,17 @@ mod simd {
966 round1: u32,975 round1: u32,
967 ) {976 ) {
968 let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2");977 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+ )
970 }989 }
971 990
972 #[allow(unused_variables, clippy::too_many_arguments)]991 #[allow(unused_variables, clippy::too_many_arguments)]
@@ -981,7 +1000,17 @@ mod simd {
981 round1: u32,1000 round1: u32,
982 ) {1001 ) {
983 let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1");1002 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+ )
985 }1014 }
986 }1015 }
987 }1016 }
@@ -1533,7 +1562,6 @@ pub(crate) fn predict_with_filters_kern(
1533 1562
1534 let (h_wide, h_narrow) = h_kind.tables();1563 let (h_wide, h_narrow) = h_kind.tables();
1535 let (v_wide, v_narrow) = v_kind.tables();1564 let (v_wide, v_narrow) = v_kind.tables();
1536- note_narrow_kern(block_w, block_h, kern_w, kern_h);
1537 let h_filter = if kern_w <= 4 {1565 let h_filter = if kern_w <= 4 {
1538 &h_narrow[xfrac]1566 &h_narrow[xfrac]
1539 } else {1567 } else {
@@ -1753,11 +1781,6 @@ pub fn reset_rect_narrow_kern_hits() {
1753 RECT_NARROW_KERN_HITS.with(|c| c.set(0));1781 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
1754 }1782 }
1755 1783
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-
1761 /// Current value of [`INTER_PRED_HITS`].1784 /// Current value of [`INTER_PRED_HITS`].
1762 pub fn inter_pred_hits() -> usize {1785 pub fn inter_pred_hits() -> usize {
1763 INTER_PRED_HITS.with(|c| c.get())1786 INTER_PRED_HITS.with(|c| c.get())
@@ -2081,7 +2104,6 @@ pub(crate) fn predict_scaled_kern(
2081 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q102104 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
2082 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).2105 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
2083 let (v_wide, v_narrow) = v_kind.tables();2106 let (v_wide, v_narrow) = v_kind.tables();
2084- note_narrow_kern(block_w, block_h, kern_w, kern_h);
2085 let v_filter = if kern_h <= 4 {2107 let v_filter = if kern_h <= 4 {
2086 &v_narrow[yfrac]2108 &v_narrow[yfrac]
2087 } else {2109 } else {
@@ -2305,7 +2327,6 @@ pub(crate) fn predict_compound_intermediate_kern(
2305 }2327 }
2306 2328
2307 let (v_wide, v_narrow) = v_kind.tables();2329 let (v_wide, v_narrow) = v_kind.tables();
2308- note_narrow_kern(block_w, block_h, kern_w, kern_h);
2309 let v_filter = if kern_h <= 4 {2330 let v_filter = if kern_h <= 4 {
2310 &v_narrow[yfrac]2331 &v_narrow[yfrac]
2311 } else {2332 } else {
crates/ec-av1/src/motion_field.rsmodified+23 -33
@@ -76,18 +76,6 @@ impl MotionField {
76 }76 }
77 }77 }
78 78
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-
91 /// lane-mf: the cell grid itself (`cols`, `rows`, cells in row-major79 /// lane-mf: the cell grid itself (`cols`, `rows`, cells in row-major
92 /// order), so [`crate::decode::build_motion_field`] can fill disjoint80 /// order), so [`crate::decode::build_motion_field`] can fill disjoint
93 /// row bands of it in parallel. Cell row `r` owns `cells[r * cols..][..cols]`.81 /// row bands of it in parallel. Cell row `r` owns `cells[r * cols..][..cols]`.
@@ -126,7 +114,6 @@ impl TplField {
126 pub fn filled_cells(&self) -> usize {114 pub fn filled_cells(&self) -> usize {
127 self.cells.iter().filter(|c| c.1 != 0).count()115 self.cells.iter().filter(|c| c.1 != 0).count()
128 }116 }
129-
130 }117 }
131 118
132 /// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range119 /// 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>>(
413 400
414 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1401 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
415 402
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-
431 if let Some(last) = slot_of(LAST_FRAME) {403 if let Some(last) = slot_of(LAST_FRAME) {
432 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];404 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
433 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);405 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
@@ -554,7 +526,9 @@ pub fn add_tpl_ref_mv(
554 let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col);526 let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col);
555 if crate::envflags::env_flag!("EC_TRACE_TPL") {527 if crate::envflags::env_flag!("EC_TRACE_TPL") {
556 match probe {528 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+ ),
558 Some((m, rfo)) => eprintln!(532 Some((m, rfo)) => eprintln!(
559 "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",533 "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",
560 m.0, m.1534 m.0, m.1
@@ -655,8 +629,16 @@ mod tests {
655 for blk_row in -4isize..=16 {629 for blk_row in -4isize..=16 {
656 for blk_col in -4isize..=16 {630 for blk_col in -4isize..=16 {
657 // the spec's own derivation (7.10.2.8)631 // the spec's own derivation (7.10.2.8)
658- let pos_row = if mi_row & 1 != 0 { blk_row } else { blk_row + 1 };632+ let pos_row = if mi_row & 1 != 0 {
659- let pos_col = if mi_col & 1 != 0 { blk_col } else { blk_col + 1 };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+ };
660 let row8 = mi_row as isize + pos_row;642 let row8 = mi_row as isize + pos_row;
661 let col8 = mi_col as isize + pos_col;643 let col8 = mi_col as isize + pos_col;
662 let want = if row8 < 0 || col8 < 0 {644 let want = if row8 < 0 || col8 < 0 {
@@ -740,8 +722,16 @@ mod tests {
740 // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by722 // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by
741 // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts723 // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts
742 // the offset, landing at 8x8 cell (2, 0).724 // the offset, landing at 8x8 cell (2, 0).
743- let cand =725+ let cand = add_tpl_ref_mv(
744- add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true, false);726+ &tpl,
727+ 4,
728+ 0,
729+ 0isize,
730+ 0isize,
731+ get_relative_dist(7, 4, 2),
732+ true,
733+ false,
734+ );
745 assert!(cand.is_some(), "expected a projected temporal candidate");735 assert!(cand.is_some(), "expected a projected temporal candidate");
746 }736 }
747 737
crates/ec-av1/src/msac.rsmodified+2 -90
@@ -312,36 +312,7 @@ pub struct SymbolDecoder<'a> {
312 }312 }
313 313
314 impl Drop for SymbolDecoder<'_> {314 impl Drop for SymbolDecoder<'_> {
315- fn drop(&mut self) {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("") };
345 }316 }
346 317
347 impl<'a> SymbolDecoder<'a> {318 impl<'a> SymbolDecoder<'a> {
@@ -420,44 +391,8 @@ impl<'a> SymbolDecoder<'a> {
420 391
421 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.392 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
422 ///393 ///
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.
450 #[inline]394 #[inline]
451 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {395 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);
461 let s = self.symbol_fixed(cdf);396 let s = self.symbol_fixed(cdf);
462 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets397 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets
463 // it codes every symbol against the tables it started with, so this398 // it codes every symbol against the tables it started with, so this
@@ -467,22 +402,6 @@ impl<'a> SymbolDecoder<'a> {
467 if self.adapt {402 if self.adapt {
468 update_cdf(cdf, s);403 update_cdf(cdf, s);
469 }404 }
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- }
486 s405 s
487 }406 }
488 407
@@ -570,17 +489,11 @@ impl<'a> SymbolDecoder<'a> {
570 self.max_bits -= bits as i32;489 self.max_bits -= bits as i32;
571 }490 }
572 491
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-
580 /// Debug-only: the raw coder state (`range`, `value`) entering the next492 /// Debug-only: the raw coder state (`range`, `value`) entering the next
581 /// read, for a byte-for-byte diff against a reference decoder's own493 /// read, for a byte-for-byte diff against a reference decoder's own
582 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see494 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see
583 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.495 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.
496+ #[cfg(test)]
584 pub(crate) fn debug_state(&self) -> (u32, u32) {497 pub(crate) fn debug_state(&self) -> (u32, u32) {
585 (self.range, self.value)498 (self.range, self.value)
586 }499 }
@@ -950,4 +863,3 @@ pub(crate) mod tests {
950 );863 );
951 }864 }
952 }865 }
953-
crates/ec-av1/src/mvstack.rsmodified+171 -80
@@ -92,14 +92,6 @@ thread_local! {
92 static TMV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };92 static TMV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
93 }93 }
94 94
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-
103 thread_local! {95 thread_local! {
104 /// lane-mvtwin r1 firing counters, one per divergence this round closed.96 /// lane-mvtwin r1 firing counters, one per divergence this round closed.
105 /// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot97 /// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot
@@ -117,24 +109,6 @@ thread_local! {
117 static TILE_REACH_CLIPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };109 static TILE_REACH_CLIPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
118 }110 }
119 111
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-
138 /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV112 /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV
139 /// candidates into a block's stack (spec 7.10.2.8, only reached when the113 /// candidates into a block's stack (spec 7.10.2.8, only reached when the
140 /// frame header's own `use_ref_frame_mvs` is set): the current frame's own114 /// frame header's own `use_ref_frame_mvs` is set): the current frame's own
@@ -431,10 +405,8 @@ impl MiGrid {
431 for r in row..(row + h).min(self.rows) {405 for r in row..(row + h).min(self.rows) {
432 let c1 = (col + w).min(self.cols);406 let c1 = (col + w).min(self.cols);
433 let n = c1 - col;407 let n = c1 - col;
434- self.cells[r * self.cols + col..r * self.cols + c1]408+ self.cells[r * self.cols + col..r * self.cols + c1].copy_from_slice(&snap.0[i..i + n]);
435- .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]);
436- self.skips[r * self.cols + col..r * self.cols + c1]
437- .copy_from_slice(&snap.1[i..i + n]);
438 i += n;410 i += n;
439 }411 }
440 }412 }
@@ -860,8 +832,11 @@ fn scan_row(
860 };832 };
861 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd833 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd
862 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).834 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).
863- let col_shift: usize =835+ let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) {
864- if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 };836+ 1
837+ } else {
838+ 0
839+ };
865 let use_step_16 = bw4 >= 16;840 let use_step_16 = bw4 >= 16;
866 let end_mi = bw4.min(16);841 let end_mi = bw4.min(16);
867 let mut found = false;842 let mut found = false;
@@ -948,8 +923,11 @@ fn scan_col(
948 };923 };
949 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row924 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row
950 // under a 4-high block.925 // under a 4-high block.
951- let row_shift: usize =926+ let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) {
952- if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 };927+ 1
928+ } else {
929+ 0
930+ };
953 let use_step_16 = bh4 >= 16;931 let use_step_16 = bh4 >= 16;
954 let end_mi = bh4.min(16);932 let end_mi = bh4.min(16);
955 let mut found = false;933 let mut found = false;
@@ -1021,7 +999,13 @@ fn top_right_scan_allowed(bw4: usize, bh4: usize) -> bool {
1021 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A999 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A
1022 /// partition whose warp-sample top-right probe may answer 1 where libaom says1000 /// partition whose warp-sample top-right probe may answer 1 where libaom says
1023 /// 0; upgrade path = thread `partition` into this call.1001 /// 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 {
1025 let sb_mi_size = crate::decode::sb_mi_cur(fctx) as usize;1009 let sb_mi_size = crate::decode::sb_mi_cur(fctx) as usize;
1026 let bs0 = bw4.max(bh4);1010 let bs0 = bw4.max(bh4);
1027 if bs0 > 16 {1011 if bs0 > 16 {
@@ -1168,11 +1152,6 @@ fn clamp_mv_ref(
1168 let to_right = signed(mi_cols, bw4, mi_col);1152 let to_right = signed(mi_cols, bw4, mi_col);
1169 let to_top = -to_subpel(mi_row);1153 let to_top = -to_subpel(mi_row);
1170 let to_bottom = signed(mi_rows, bh4, mi_row);1154 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- }
1176 1155
1177 let (row, col) = mv;1156 let (row, col) = mv;
1178 (1157 (
@@ -1503,7 +1482,6 @@ pub fn find_mv_stack_with_sign_bias(
1503 force_integer_mv,1482 force_integer_mv,
1504 }) = tpl1483 }) = tpl
1505 {1484 {
1506- let mut any_hit = false;
1507 let voffset = bh4.max(2);1485 let voffset = bh4.max(2);
1508 let hoffset = bw4.max(2);1486 let hoffset = bw4.max(2);
1509 let blk_row_end = bh4.min(16);1487 let blk_row_end = bh4.min(16);
@@ -1539,12 +1517,11 @@ pub fn find_mv_stack_with_sign_bias(
1539 let mut blk_col = 0usize;1517 let mut blk_col = 0usize;
1540 while blk_col < blk_col_end {1518 while blk_col < blk_col_end {
1541 if let Some(mv) = sample(blk_row as isize, blk_col as isize) {1519 if let Some(mv) = sample(blk_row as isize, blk_col as isize) {
1542- any_hit = true;
1543 if blk_row == 0 && blk_col == 0 {1520 if blk_row == 0 && blk_col == 0 {
1544 first_sample_missing = false;1521 first_sample_missing = false;
1545 let this_gm_mv = gm_mv(gm, ref_frame);1522 let this_gm_mv = gm_mv(gm, ref_frame);
1546- first_sample_far = (mv.0 - this_gm_mv.0).abs() >= 161523+ first_sample_far =
1547- || (mv.1 - this_gm_mv.1).abs() >= 16;1524+ (mv.0 - this_gm_mv.0).abs() >= 16 || (mv.1 - this_gm_mv.1).abs() >= 16;
1548 }1525 }
1549 add_candidate(&mut candidates, mv, 2);1526 add_candidate(&mut candidates, mv, 2);
1550 }1527 }
@@ -1570,7 +1547,6 @@ pub fn find_mv_stack_with_sign_bias(
1570 continue;1547 continue;
1571 }1548 }
1572 if let Some(mv) = sample(row_off, col_off) {1549 if let Some(mv) = sample(row_off, col_off) {
1573- any_hit = true;
1574 add_candidate(&mut candidates, mv, 2);1550 add_candidate(&mut candidates, mv, 2);
1575 }1551 }
1576 }1552 }
@@ -1955,8 +1931,11 @@ fn scan_row_compound(
1955 };1931 };
1956 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd1932 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd
1957 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).1933 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).
1958- let col_shift: usize =1934+ let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) {
1959- if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 };1935+ 1
1936+ } else {
1937+ 0
1938+ };
1960 let use_step_16 = bw4 >= 16;1939 let use_step_16 = bw4 >= 16;
1961 let end_mi = bw4.min(16);1940 let end_mi = bw4.min(16);
1962 let mut found = false;1941 let mut found = false;
@@ -1982,12 +1961,24 @@ fn scan_row_compound(
1982 weight = weight.max(inc as u32);1961 weight = weight.max(inc as u32);
1983 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;1962 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
1984 }1963 }
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+ {
1986 found = true;1969 found = true;
1987 add_compound_candidate(1970 add_compound_candidate(
1988 candidates,1971 candidates,
1989- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },1972+ if info.is_global_mv0 {
1990- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },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+ },
1991 len as u32 * weight,1982 len as u32 * weight,
1992 );1983 );
1993 *newmv_count += u32::from(info.is_new_mv);1984 *newmv_count += u32::from(info.is_new_mv);
@@ -2018,8 +2009,11 @@ fn scan_col_compound(
2018 };2009 };
2019 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row2010 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row
2020 // under a 4-high block.2011 // under a 4-high block.
2021- let row_shift: usize =2012+ let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) {
2022- if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 };2013+ 1
2014+ } else {
2015+ 0
2016+ };
2023 let use_step_16 = bh4 >= 16;2017 let use_step_16 = bh4 >= 16;
2024 let end_mi = bh4.min(16);2018 let end_mi = bh4.min(16);
2025 let mut found = false;2019 let mut found = false;
@@ -2045,12 +2039,24 @@ fn scan_col_compound(
2045 weight = weight.max(inc as u32);2039 weight = weight.max(inc as u32);
2046 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;2040 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
2047 }2041 }
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+ {
2049 found = true;2047 found = true;
2050 add_compound_candidate(2048 add_compound_candidate(
2051 candidates,2049 candidates,
2052- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },2050+ if info.is_global_mv0 {
2053- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },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+ },
2054 len as u32 * weight,2060 len as u32 * weight,
2055 );2061 );
2056 *newmv_count += u32::from(info.is_new_mv);2062 *newmv_count += u32::from(info.is_new_mv);
@@ -2079,12 +2085,21 @@ fn scan_top_right_compound(
2079 if let Some(info) = grid.get(row, col)2085 if let Some(info) = grid.get(row, col)
2080 && info.is_inter2086 && info.is_inter
2081 && info.ref_frame == ref_frame.02087 && info.ref_frame == ref_frame.0
2082- && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.12088+ && info.ref_frame1 > 0
2089+ && info.ref_frame1 == ref_frame.1
2083 {2090 {
2084 add_compound_candidate(2091 add_compound_candidate(
2085 candidates,2092 candidates,
2086- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },2093+ if info.is_global_mv0 {
2087- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },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+ },
2088 CORNER_WEIGHT,2103 CORNER_WEIGHT,
2089 );2104 );
2090 *newmv_count += u32::from(info.is_new_mv);2105 *newmv_count += u32::from(info.is_new_mv);
@@ -2109,12 +2124,21 @@ fn scan_corner_compound(
2109 if let Some(info) = grid.get(row, col)2124 if let Some(info) = grid.get(row, col)
2110 && info.is_inter2125 && info.is_inter
2111 && info.ref_frame == ref_frame.02126 && info.ref_frame == ref_frame.0
2112- && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.12127+ && info.ref_frame1 > 0
2128+ && info.ref_frame1 == ref_frame.1
2113 {2129 {
2114 add_compound_candidate(2130 add_compound_candidate(
2115 candidates,2131 candidates,
2116- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },2132+ if info.is_global_mv0 {
2117- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },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+ },
2118 CORNER_WEIGHT,2142 CORNER_WEIGHT,
2119 );2143 );
2120 *newmv_count += u32::from(info.is_new_mv);2144 *newmv_count += u32::from(info.is_new_mv);
@@ -2202,9 +2226,10 @@ fn combine_compound_candidates(
2202 .copied()2226 .copied()
2203 .collect();2227 .collect();
2204 std::array::from_fn(|i| {2228 std::array::from_fn(|i| {
2205- merged.get(i).copied().unwrap_or_else(|| {2229+ merged
2206- gm_mv_candidates[side]2230+ .get(i)
2207- })2231+ .copied()
2232+ .unwrap_or_else(|| gm_mv_candidates[side])
2208 })2233 })
2209 };2234 };
2210 let side0 = side_slots(0);2235 let side0 = side_slots(0);
@@ -2345,7 +2370,6 @@ pub fn find_mv_stack_compound(
2345 force_integer_mv,2370 force_integer_mv,
2346 }) = tpl2371 }) = tpl
2347 {2372 {
2348- let mut any_hit = false;
2349 let blk_row_end = bh4.min(16);2373 let blk_row_end = bh4.min(16);
2350 let blk_col_end = bw4.min(16);2374 let blk_col_end = bw4.min(16);
2351 let step_h = if bh4 >= 16 { 4 } else { 2 };2375 let step_h = if bh4 >= 16 { 4 } else { 2 };
@@ -2379,7 +2403,6 @@ pub fn find_mv_stack_compound(
2379 let mut blk_col = 0usize;2403 let mut blk_col = 0usize;
2380 while blk_col < blk_col_end {2404 while blk_col < blk_col_end {
2381 if let Some((mv0, mv1)) = sample(blk_row as isize, blk_col as isize) {2405 if let Some((mv0, mv1)) = sample(blk_row as isize, blk_col as isize) {
2382- any_hit = true;
2383 if blk_row == 0 && blk_col == 0 {2406 if blk_row == 0 && blk_col == 0 {
2384 first_sample_missing = false;2407 first_sample_missing = false;
2385 let this_gm0 = gm_mv(gm, ref_frame.0);2408 let this_gm0 = gm_mv(gm, ref_frame.0);
@@ -2418,7 +2441,6 @@ pub fn find_mv_stack_compound(
2418 continue;2441 continue;
2419 }2442 }
2420 if let Some((mv0, mv1)) = sample(row_off, col_off) {2443 if let Some((mv0, mv1)) = sample(row_off, col_off) {
2421- any_hit = true;
2422 add_compound_candidate(&mut candidates, mv0, mv1, 2);2444 add_compound_candidate(&mut candidates, mv0, mv1, 2);
2423 }2445 }
2424 }2446 }
@@ -2691,8 +2713,16 @@ fn ref_ctx(
2691 b_set: &[i8],2713 b_set: &[i8],
2692 ) -> usize {2714 ) -> usize {
2693 let refs = [above0, above1, left0, left1];2715 let refs = [above0, above1, left0, left1];
2694- let a = refs.into_iter().flatten().filter(|r| a_set.contains(r)).count();2716+ let a = refs
2695- let b = refs.into_iter().flatten().filter(|r| b_set.contains(r)).count();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();
2696 match a.cmp(&b) {2726 match a.cmp(&b) {
2697 std::cmp::Ordering::Less => 0,2727 std::cmp::Ordering::Less => 0,
2698 std::cmp::Ordering::Equal => 1,2728 std::cmp::Ordering::Equal => 1,
@@ -2768,7 +2798,14 @@ pub(crate) fn single_ref_p5_ctx(
2768 left0: Option<i8>,2798 left0: Option<i8>,
2769 left1: Option<i8>,2799 left1: Option<i8>,
2770 ) -> usize {2800 ) -> 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+ )
2772 }2809 }
2773 2810
2774 /// `av1_get_pred_context_single_ref_p6`2811 /// `av1_get_pred_context_single_ref_p6`
@@ -2779,7 +2816,14 @@ pub(crate) fn single_ref_p6_ctx(
2779 left0: Option<i8>,2816 left0: Option<i8>,
2780 left1: Option<i8>,2817 left1: Option<i8>,
2781 ) -> usize {2818 ) -> 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+ )
2783 }2827 }
2784 2828
2785 /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,2829 /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,
@@ -2921,7 +2965,6 @@ mod tests {
2921 2965
2922 use super::*;2966 use super::*;
2923 2967
2924-
2925 /// lane-mvstack2: the mi grid is one cell per 4x4 unit of the frame and2968 /// lane-mvstack2: the mi grid is one cell per 4x4 unit of the frame and
2926 /// `find_mv_stack` walks it for every inter block, so the cell's SIZE is2969 /// `find_mv_stack` walks it for every inter block, so the cell's SIZE is
2927 /// the scan's memory traffic. `ref_frame1`/`mv1` are validity-tagged by2970 /// the scan's memory traffic. `ref_frame1`/`mv1` are validity-tagged by
@@ -3516,7 +3559,19 @@ mod tests {
3516 let (mv0, mv1) = ((2, 2), (-6, 3));3559 let (mv0, mv1) = ((2, 2), (-6, 3));
3517 grid.set(2, 1, comp_inter(mv0, mv1));3560 grid.set(2, 1, comp_inter(mv0, mv1));
3518 3561
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+ );
3520 3575
3521 // The exact-pair immediate scan lands one boosted entry; the3576 // The exact-pair immediate scan lands one boosted entry; the
3522 // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)3577 // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)
@@ -3540,7 +3595,19 @@ mod tests {
3540 grid.set(2, 1, comp_inter(mv0, mv1));3595 grid.set(2, 1, comp_inter(mv0, mv1));
3541 grid.set(3, 1, comp_inter(mv0, mv1));3596 grid.set(3, 1, comp_inter(mv0, mv1));
3542 3597
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+ );
3544 3611
3545 // Exact libaom `is_dup` port: with exactly one entry already in the3612 // Exact libaom `is_dup` port: with exactly one entry already in the
3546 // stack (the four identical-pair neighbours deduped by the3613 // stack (the four identical-pair neighbours deduped by the
@@ -3572,7 +3639,19 @@ mod tests {
3572 grid.set(4, 2, comp_inter(left.0, left.1));3639 grid.set(4, 2, comp_inter(left.0, left.1));
3573 grid.set(5, 2, comp_inter(left.0, left.1));3640 grid.set(5, 2, comp_inter(left.0, left.1));
3574 3641
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+ );
3576 3655
3577 assert_eq!(stack.entries.len(), 2);3656 assert_eq!(stack.entries.len(), 2);
3578 assert_eq!(stack.entries[0].mv0, left.0);3657 assert_eq!(stack.entries[0].mv0, left.0);
@@ -3661,7 +3740,19 @@ mod tests {
3661 },3740 },
3662 );3741 );
3663 3742
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+ );
3665 3756
3666 // The combine step (libaom's real "Handle compound reference frame3757 // The combine step (libaom's real "Handle compound reference frame
3667 // extension") zips each side's ref_id-then-ref_diff lists3758 // extension") zips each side's ref_id-then-ref_diff lists
@@ -3711,11 +3802,9 @@ mod tests {
3711 for i in 0..MAX_STACK_SIZE as i32 {3802 for i in 0..MAX_STACK_SIZE as i32 {
3712 add_candidate(&mut candidates, (i, i), 2);3803 add_candidate(&mut candidates, (i, i), 2);
3713 }3804 }
3714- let before = stack_full_drops();
3715 add_candidate(&mut candidates, (99, 99), 10_000);3805 add_candidate(&mut candidates, (99, 99), 10_000);
3716 assert_eq!(candidates.len(), MAX_STACK_SIZE);3806 assert_eq!(candidates.len(), MAX_STACK_SIZE);
3717 assert!(!candidates.iter().any(|e| e.mv == (99, 99)));3807 assert!(!candidates.iter().any(|e| e.mv == (99, 99)));
3718- assert_eq!(stack_full_drops(), before + 1);
3719 // A full stack still takes the dedup weight bump libaom applies3808 // A full stack still takes the dedup weight bump libaom applies
3720 // before the cap check.3809 // before the cap check.
3721 add_candidate(&mut candidates, (0, 0), 6);3810 add_candidate(&mut candidates, (0, 0), 6);
@@ -3782,7 +3871,9 @@ mod tests {
3782 let clamped = clamp_mv_ref((384, -320), 400, 368, 16, 16, 960, 402);3871 let clamped = clamp_mv_ref((384, -320), 400, 368, 16, 16, 960, 402);
3783 assert_eq!(clamped, (192, -320));3872 assert_eq!(clamped, (192, -320));
3784 // A block fully inside the frame keeps the wide window.3873 // 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+ );
3786 }3878 }
3787-
3788 }3879 }
crates/ec-av1/src/par.rsmodified+9 -31
@@ -86,14 +86,6 @@ pub(crate) fn filter_threads() -> usize {
86 }86 }
87 }87 }
88 88
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-
97 /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's89 /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
98 /// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the90 /// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the
99 /// entropy WRITE (`encode::write_tiles`); default 1 = the shipped91 /// entropy WRITE (`encode::write_tiles`); default 1 = the shipped
@@ -196,7 +188,10 @@ pub(crate) fn run_bands_mut<T, F>(
196 /// Carves `data` into one `&mut` slice per element range, `ranges` ascending188 /// Carves `data` into one `&mut` slice per element range, `ranges` ascending
197 /// and non-overlapping (`split_at_mut` only, so no `unsafe`). Elements outside189 /// and non-overlapping (`split_at_mut` only, so no `unsafe`). Elements outside
198 /// every range are left alone.190 /// 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]> {
200 split_bands_mut(ranges, 1, data)195 split_bands_mut(ranges, 1, data)
201 }196 }
202 197
@@ -341,12 +336,6 @@ pub(crate) fn recon_threads() -> usize {
341 }336 }
342 }337 }
343 338
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-
350 // --- lane-pool1: persistent worker pools ---------------------------------339 // --- lane-pool1: persistent worker pools ---------------------------------
351 //340 //
352 // Every threaded stage of the decoder used to spawn its threads per unit of341 // 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;
687 676
688 static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =677 static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
689 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];678 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];
690-/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or679+/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES` (the env snapshot is process-constant).
691-/// [`set_stage_times`] from a gate (the env snapshot is process-constant).
692 static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);680 static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
693 681
694 pub(crate) fn stage_times() -> bool {682 pub(crate) fn stage_times() -> bool {
@@ -702,12 +690,6 @@ pub(crate) fn stage_times() -> bool {
702 }690 }
703 }691 }
704 692
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-
711 /// A live stage measurement: added to stage `i` when it drops. `None` when693 /// A live stage measurement: added to stage `i` when it drops. `None` when
712 /// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.694 /// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.
713 pub(crate) struct Timer(usize, std::time::Instant);695 pub(crate) struct Timer(usize, std::time::Instant);
@@ -719,13 +701,9 @@ pub(crate) fn timer(i: usize) -> Option<Timer> {
719 701
720 impl Drop for Timer {702 impl Drop for Timer {
721 fn drop(&mut self) {703 fn drop(&mut self) {
722- STAGE_NS[self.0]704+ STAGE_NS[self.0].fetch_add(
723- .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);705+ self.1.elapsed().as_nanos() as u64,
706+ std::sync::atomic::Ordering::Relaxed,
707+ );
724 }708 }
725 }709 }
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(
216 dq2.clamp(-bound, bound - 1) as i32216 dq2.clamp(-bound, bound - 1) as i32
217 }217 }
218 218
219-
220 thread_local! {219 thread_local! {
221 /// lane-av1-qmatrix: transform units whose dequantisation actually220 /// lane-av1-qmatrix: transform units whose dequantisation actually
222 /// scaled at least one NONZERO level through a quantisation matrix --221 /// scaled at least one NONZERO level through a quantisation matrix --
@@ -226,18 +225,6 @@ thread_local! {
226 static QM_SCALED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };225 static QM_SCALED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
227 }226 }
228 227
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-
241 /// Dequantize a whole raster-order coefficient grid of a `side` x `side`228 /// Dequantize a whole raster-order coefficient grid of a `side` x `side`
242 /// transform.229 /// transform.
243 pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i32> {230 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! {
609 const MI_SIZE_8PX: u32 = 8;609 const MI_SIZE_8PX: u32 = 8;
610 /// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8.610 /// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8.
611 const SCALE_NUMERATOR: u32 = 8;611 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-
641 fn read_lr_unit(612 fn read_lr_unit(
642 dec: &mut SymbolDecoder,613 dec: &mut SymbolDecoder,
643 cdfs: &mut crate::cdf_state::Cdfs,614 cdfs: &mut crate::cdf_state::Cdfs,
@@ -650,12 +621,8 @@ fn read_lr_unit(
650 let t = dec.symbol(&mut cdfs.restore_switchable);621 let t = dec.symbol(&mut cdfs.restore_switchable);
651 match t {622 match t {
652 0 => UnitFilter::None,623 0 => UnitFilter::None,
653- 1 => {624+ 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)),
654- UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))625+ _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)),
655- }
656- _ => {
657- UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
658- }
659 }626 }
660 }627 }
661 RestorationType::Wiener => {628 RestorationType::Wiener => {
@@ -1181,7 +1148,7 @@ fn ab_row(
1181 /// [`ab_row`]'s AVX2 kernel.1148 /// [`ab_row`]'s AVX2 kernel.
1182 #[cfg(target_arch = "x86_64")]1149 #[cfg(target_arch = "x86_64")]
1183 mod sgr_simd {1150 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};
1185 use archmage::{X64V3Token, arcane};1152 use archmage::{X64V3Token, arcane};
1186 use std::arch::x86_64::*;1153 use std::arch::x86_64::*;
1187 1154
@@ -1461,8 +1428,8 @@ fn apply_sgrproj_stripe(
1461 }1428 }
1462 }1429 }
1463 let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, smax) as u16;1430 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] =1431+ out[(v_start as i64 + i - row0 as i64) as usize * stride
1465- out_v;1432+ + (h_start as i64 + j) as usize] = out_v;
1466 }1433 }
1467 }1434 }
1468 SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1));1435 SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1));
@@ -1582,20 +1549,27 @@ pub(crate) fn apply_loop_restoration_plane(
1582 }1549 }
1583 // Each band's RU rows write one contiguous run of `out` rows (the1550 // Each band's RU rows write one contiguous run of `out` rows (the
1584 // rows run `v_start..v_end` back to back), so a band owns its own slice.1551 // 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())1552+ let pbands: Vec<(usize, usize)> =
1586- .into_iter()1553+ crate::par::bands(rows.len(), crate::par::filter_threads())
1587- .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize))1554+ .into_iter()
1588- .collect();1555+ .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize))
1589- crate::par::run_bands_mut(&pbands, stride, fctx, out.as_mut_slice(), |lo, hi, mine, fctx| {1556+ .collect();
1590- let r_lo = rows.partition_point(|r| (r.0 as usize) < lo);1557+ crate::par::run_bands_mut(
1591- let r_hi = rows.partition_point(|r| (r.0 as usize) < hi);1558+ &pbands,
1592- for rrow in r_lo..r_hi {1559+ stride,
1593- lr_unit_row(1560+ fctx,
1594- mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,1561+ out.as_mut_slice(),
1595- plane, rrow, &rows, fctx,1562+ |lo, hi, mine, fctx| {
1596- );1563+ let r_lo = rows.partition_point(|r| (r.0 as usize) < lo);
1597- }1564+ let r_hi = rows.partition_point(|r| (r.0 as usize) < hi);
1598- });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+ );
1599 debug_assert_eq!(1573 debug_assert_eq!(
1600 rows.len(),1574 rows.len(),
1601 grid.vert_units[plane],1575 grid.vert_units[plane],
@@ -1608,8 +1582,8 @@ pub(crate) fn apply_loop_restoration_plane(
1608 let (a, b) = (v_start as usize * stride, v_end as usize * stride);1582 let (a, b) = (v_start as usize * stride, v_end as usize * stride);
1609 out[a..b].copy_from_slice(&cdef[a..b]);1583 out[a..b].copy_from_slice(&cdef[a..b]);
1610 lr_unit_row(1584 lr_unit_row(
1611- out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane,1585+ out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow,
1612- rrow, &rows, fctx,1586+ &rows, fctx,
1613 );1587 );
1614 }1588 }
1615 }1589 }
crates/ec-av1/src/stream/mod.rsmodified+6 -61
@@ -29,15 +29,6 @@ use crate::decode;
29 use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};29 use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};
30 use crate::encode::Picture;30 use crate::encode::Picture;
31 31
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-
41 /// Decode every frame in a raw AV1 OBU stream, in coding order.32 /// Decode every frame in a raw AV1 OBU stream, in coding order.
42 ///33 ///
43 /// A key frame becomes the reference for the inter frames that follow it,34 /// A key frame becomes the reference for the inter frames that follow it,
@@ -767,7 +758,7 @@ impl StreamDecoder {
767 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {758 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
768 let value = promise.wait()?;759 let value = promise.wait()?;
769 let shown_picture = value.pixels.wait()?;760 let shown_picture = value.pixels.wait()?;
770- let output = if grain.apply_grain && !no_grain() {761+ let output = if grain.apply_grain {
771 std::sync::Arc::new(crate::film_grain::apply_grain(762 std::sync::Arc::new(crate::film_grain::apply_grain(
772 &shown_picture,763 &shown_picture,
773 &grain,764 &grain,
@@ -814,7 +805,7 @@ impl StreamDecoder {
814 }805 }
815 picture806 picture
816 };807 };
817- let output = if header.film_grain.apply_grain && !no_grain() {808+ let output = if header.film_grain.apply_grain {
818 // lane-hbd10 r1: grain synthesis is bit-depth generic809 // lane-hbd10 r1: grain synthesis is bit-depth generic
819 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).810 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
820 let bit_depth = parser811 let bit_depth = parser
@@ -987,7 +978,7 @@ impl StreamDecoder {
987 }978 }
988 }979 }
989 }980 }
990- let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);981+ let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
991 emit_seq += 1;982 emit_seq += 1;
992 pictures_decoded += 1;983 pictures_decoded += 1;
993 let shown = header.show_frame;984 let shown = header.show_frame;
@@ -1155,7 +1146,6 @@ impl StreamDecoder {
1155 seq,1146 seq,
1156 snap,1147 snap,
1157 decode_idx,1148 decode_idx,
1158- shown_idx,
1159 // lane-twostage publishes a frame's meta at its tile1149 // lane-twostage publishes a frame's meta at its tile
1160 // boundary instead of after its filters, so a consumer1150 // boundary instead of after its filters, so a consumer
1161 // parses over its producer's filter tail. It is ON by1151 // parses over its producer's filter tail. It is ON by
@@ -1195,7 +1185,7 @@ impl StreamDecoder {
1195 // Grain is synthesised for OUTPUT only: a hidden frame is1185 // Grain is synthesised for OUTPUT only: a hidden frame is
1196 // reported to the sink clean, exactly as the inline path1186 // reported to the sink clean, exactly as the inline path
1197 // below reports it (spec 7.18.3.1).1187 // 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 {
1199 std::sync::Arc::new(crate::film_grain::apply_grain(1189 std::sync::Arc::new(crate::film_grain::apply_grain(
1200 &picture,1190 &picture,
1201 &header.film_grain,1191 &header.film_grain,
@@ -1259,16 +1249,7 @@ impl StreamDecoder {
1259 stored_cdfs,1249 stored_cdfs,
1260 motion_field,1250 motion_field,
1261 seg_map: decoded_seg_map,1251 seg_map: decoded_seg_map,
1262- } = decode_frame(1252+ } = decode_frame(fctx, &header, &tile_bufs, seq, snap, pictures_decoded, None)?;
1263- fctx,
1264- &header,
1265- &tile_bufs,
1266- seq,
1267- snap,
1268- pictures_decoded,
1269- pictures_shown,
1270- None,
1271- )?;
1272 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");1253 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
1273 pictures_decoded += 1;1254 pictures_decoded += 1;
1274 // lane-pool1: one allocation, then every slot store and the output1255 // lane-pool1: one allocation, then every slot store and the output
@@ -1319,7 +1300,7 @@ impl StreamDecoder {
1319 decode::note_fwd_kf();1300 decode::note_fwd_kf();
1320 }1301 }
1321 if header.show_frame {1302 if header.show_frame {
1322- let output = if header.film_grain.apply_grain && !no_grain() {1303+ let output = if header.film_grain.apply_grain {
1323 let mc_identity = seq.mc_identity;1304 let mc_identity = seq.mc_identity;
1324 std::sync::Arc::new(crate::film_grain::apply_grain(1305 std::sync::Arc::new(crate::film_grain::apply_grain(
1325 &picture,1306 &picture,
@@ -1502,16 +1483,6 @@ impl<'a> RefSnapshot<'a> {
1502 header.mi_cols as usize,1483 header.mi_cols as usize,
1503 )1484 )
1504 });1485 });
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- }
1515 Self {1486 Self {
1516 refpix,1487 refpix,
1517 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),1488 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
@@ -1572,7 +1543,6 @@ fn decode_frame(
1572 seq: SeqFlags,1543 seq: SeqFlags,
1573 snap: RefSnapshot<'_>,1544 snap: RefSnapshot<'_>,
1574 decode_idx: usize,1545 decode_idx: usize,
1575- shown_idx: usize,
1576 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.1546 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1577 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,1547 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1578 ) -> Result<FrameOutput> {1548 ) -> Result<FrameOutput> {
@@ -1990,34 +1960,9 @@ fn decode_frame(
1990 };1960 };
1991 let started_from = initial_cdfs.clone();1961 let started_from = initial_cdfs.clone();
1992 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.1962 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1993- decode::set_coeff_trace_frame(decode_idx);
1994 // lane-t900 r9: one line per DECODE-order frame naming the header1963 // lane-t900 r9: one line per DECODE-order frame naming the header
1995 // fields a desync cliff is usually keyed on (frame type, base q,1964 // fields a desync cliff is usually keyed on (frame type, base q,
1996 // primary_ref, the 7 ref slots, refresh mask, order hints).1965 // 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- }
2021 1966
2022 let order_hint_bits = seq.order_hint_bits;1967 let order_hint_bits = seq.order_hint_bits;
2023 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint1968 // 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] =
19 /// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.19 /// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
20 /// A gate asserts it non-zero so it cannot pass on a stream that never cuts20 /// A gate asserts it non-zero so it cannot pass on a stream that never cuts
21 /// one (class `gate-blind-to-feature`).21 /// 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);
23 24
24 /// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).25 /// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
25 pub fn palette_cut_maps_written() -> usize {26 pub fn palette_cut_maps_written() -> usize {
@@ -1334,16 +1335,6 @@ pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
1334 /// arming calls, not frames: a multi-tile frame arms one worker per tile.1335 /// arming calls, not frames: a multi-tile frame arms one worker per tile.
1335 pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];1336 pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
1336 1337
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-
1347 /// The pricer census (`pricer_census_on`): for every transform block the tile1338 /// The pricer census (`pricer_census_on`): for every transform block the tile
1348 /// writer really codes, the bits it spent against the bits [`coeff_bits`]1339 /// writer really codes, the bits it spent against the bits [`coeff_bits`]
1349 /// prices those very levels at -- the search's rate term measured against the1340 /// 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 {
1998 /// # Errors1989 /// # Errors
1999 /// Returns an error when `diff` needs eighth-pel precision in a frame coded1990 /// Returns an error when `diff` needs eighth-pel precision in a frame coded
2000 /// without `allow_high_precision_mv`.1991 /// 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<()> {
2002 debug_assert_ne!(diff, 0);1997 debug_assert_ne!(diff, 0);
2003 let hp_frame = high_precision_mv();1998 let hp_frame = high_precision_mv();
2004 let sign = diff < 0;1999 let sign = diff < 0;
@@ -2176,18 +2171,13 @@ pub(super) static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
2176 std::sync::atomic::AtomicUsize::new(0),2171 std::sync::atomic::AtomicUsize::new(0),
2177 ];2172 ];
2178 2173
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-
2185 /// Bumps the two histograms for one coded inter block.2174 /// Bumps the two histograms for one coded inter block.
2186 /// How many blocks this process wrote whose search-chosen `ref_mv_idx` the2175 /// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
2187 /// write-time stack could not carry, so the writer signalled a SMALLER index2176 /// write-time stack could not carry, so the writer signalled a SMALLER index
2188 /// (lane-sb128b). Every one of these used to price its residual against a2177 /// (lane-sb128b). Every one of these used to price its residual against a
2189 /// predictor the decoder never derives.2178 /// 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);
2191 2181
2192 /// Counts one clamped DRL index whose predictor differs from the one the2182 /// Counts one clamped DRL index whose predictor differs from the one the
2193 /// search asked for -- the harmful case, and the only one a witness can see.2183 /// 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) {
2214 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);2204 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2215 }2205 }
2216 2206
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-
2229 /// Writes the DRL index of one block: the loop the decoder runs (spec2207 /// Writes the DRL index of one block: the loop the decoder runs (spec
2230 /// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one2208 /// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
2231 /// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to2209 /// `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(
2713 + usize::from(neighbours.left_skip[mi_r]);2691 + usize::from(neighbours.left_skip[mi_r]);
2714 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);2692 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
2715 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);2693 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
2716- write_delta_q(2694+ write_delta_q(&mut enc, cdfs, (mi_r, mi_c), !sb128_armed(), block.skip);
2717- &mut enc,
2718- cdfs,
2719- (mi_r, mi_c),
2720- !sb128_armed(),
2721- block.skip,
2722- );
2723 let ii_ctx = intra_inter_ctx(2695 let ii_ctx = intra_inter_ctx(
2724 has_above,2696 has_above,
2725 has_left,2697 has_left,
crates/ec-av1/src/tile/mod.rsmodified+0 -49
@@ -1275,13 +1275,6 @@ fn filter_intra_armed() -> bool {
1275 static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =1275 static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
1276 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];1276 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
1277 1277
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-
1285 /// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for1278 /// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
1286 /// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every1279 /// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
1287 /// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=1280 /// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
@@ -1347,13 +1340,6 @@ fn note_intrabc(dv: (i32, i32)) {
1347 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);1340 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1348 }1341 }
1349 1342
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-
1357 thread_local! {1343 thread_local! {
1358 /// This frame header's own `reference_select` bit (spec 5.9.22), armed1344 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
1359 /// the same way `arm_sign_bias` arms the sign-bias table rather than1345 /// 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) {
1415 static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =1401 static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1416 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];1402 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
1417 1403
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-
1425 /// What the 3-symbol `motion_mode` symbol costs, in bits, against the same1404 /// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
1426 /// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --1405 /// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
1427 /// which alphabet a block reads is `motion_mode_allowed`'s own choice1406 /// 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] =
1726 static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =1705 static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
1727 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];1706 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1728 1707
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-
1742 /// Per-SIZE fire counts of [`write_compound_block`], indexed by1708 /// Per-SIZE fire counts of [`write_compound_block`], indexed by
1743 /// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a1709 /// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
1744 /// 32x32-only tool, so the share by size is what says whether the leaf1710 /// 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] {
1746 static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =1712 static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
1747 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];1713 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1748 1714
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-
1755 /// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and1715 /// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
1756 /// below). The frame-wide histogram above cannot say whether a mode reaches1716 /// below). The frame-wide histogram above cannot say whether a mode reaches
1757 /// the leaves at all, which is exactly the question every leaf compound step1717 /// 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] {
1761 static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =1721 static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
1762 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];1722 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
1763 1723
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-
1772 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side1724 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
1773 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /1725 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
1774 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that1726 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
@@ -2493,7 +2445,6 @@ pub fn split_dc_key_frame_tile(
2493 mod syntax;2445 mod syntax;
2494 pub use self::syntax::*;2446 pub use self::syntax::*;
2495 2447
2496-
2497 mod blocks;2448 mod blocks;
2498 pub use self::blocks::*;2449 pub use self::blocks::*;
2499 mod leaf;2450 mod leaf;