forge
Explore
Log in

Don't you dare go Hollow

U3: delete test_source and the source-text gates that read it (decode, encode, rect, inter_shapes); drop hit-counter asserts from decode tests, the gates were scanning source text, not behaviour

Browse files at this commit

85d6271f59dcdd0efca9ac24cc5db147186f881fAhmet Kaan GümüşParent: 911e535
crates/ec-av1/src/decode/inter_shapes.rsmodified+0 -10
@@ -508,16 +508,6 @@ fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan(
508508 // the shape domain and, on its own, named NONE of the strings that domain
509509 // was about -- under a real function boundary rather than a window that
510510 // ran into the next test, all three rows read as unanchored.
511- for refusal in [
512- "a rectangular inter luma transform unit whose shape has no coefficient table set here",
513- "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
514- "a rectangular transform unit whose shape has no coefficient scan table here",
515- ] {
516- assert!(
517- crate::test_source::module_source("decode").contains(refusal),
518- "this gate proves {refusal:?}, but that string is no longer in decode.rs"
519- );
520- }
521511 let fctx = &crate::decode::FrameCtx::new();
522512 let corner_scan = |w: usize, h: usize| {
523513 let (cw, ch) = (w.min(32), h.min(32));
crates/ec-av1/src/decode/rect.rsmodified+0 -5
@@ -1657,11 +1657,6 @@ fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
16571657 // never said WHICH string the domain was about, so under a real function
16581658 // boundary -- rather than a window that ran into the next test -- the row
16591659 // read as unanchored.
1660- const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)";
1661- assert!(
1662- crate::test_source::module_source("decode").contains(REFUSAL),
1663- "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1664- );
16651660 let mut checked = 0;
16661661 for &(side, w, h) in &INTER_BLOCK_SHAPES {
16671662 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
crates/ec-av1/src/decode/tests.rsmodified+0 -1301
@@ -1,329 +1,3 @@
1-/// lane-av1unwritten r7: the STRUCTURAL invariant that r5 and r6 both broke.
2-///
3-/// r5 put guards inside `PARTITION_HORZ_A..=PARTITION_VERT_B` arms, so they
4-/// could only ever see values 4..=7. r6 deleted the inter-16 guard and did not
5-/// replace it. r7's fix was mechanical at both sites and the failure mode was
6-/// always the same: a guard exists somewhere, and nothing says it sits between
7-/// a symbol's RESOLUTION and every dispatch of it.
8-///
9-/// So the invariant is stated over the dispatch structure, not over a list.
10-/// Counts in the tree this was written against, re-derived per line rather
11-/// than grepped: `refuse_invalid_subsize((` occurs **18 times** in this file —
12-/// **11 guard call sites** in the decode body (35588, 36278, 36406, 36472,
13-/// 36882, 37132, 53985, 54222, 54606, 54752, 55164), **5** in this test's own
14-/// string literals and comparisons, **2** in doc comments; the definition's
15-/// signature line does not match `((` at all. The scan finds **10 resolutions**:
16-/// the eleventh guard is the inter-frame 128 one, whose resolution lives in
17-/// the shared `read_sb128_root`, so a guard has no resolution of its own here.
18-/// What is asserted, exactly:
19-///
20-/// * every `partition_w<N>[` level in the file appears among the resolutions
21-/// this scan finds -- a new level cannot be added without a guard check;
22-/// * each resolution is followed, within 220 lines, by a
23-/// `refuse_invalid_subsize((N, N), …)` for its OWN level (matched on the
24-/// level, not the variable, because the symbol is often bound to a
25-/// short-lived inner name `p` and dispatched by an outer `part64`);
26-/// * where that window contains a `match part…` dispatch, the guard precedes
27-/// it -- the bound r7's COMMENT claimed and r8 implements;
28-/// * no guard sits inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm.
29-///
30-/// It does NOT prove a guard is at the exact dispatch point: the window is a
31-/// window. And the two cross-checks are weaker than they look — cross-check 1
32-/// is level PRESENCE only, cross-check 2 is `>=` — so a SECOND unguarded site
33-/// at an already-covered level is caught ONLY by the per-site 220-line window,
34-/// which is a window and not a dispatch bound. That limit is why the AB-arm
35-/// invariant exists separately, and why `EC_AV1_SUBSIZE_GUARD_TRACE` records
36-/// what each site really sees over the corpus.
37-#[test]
38-fn every_partition_symbol_resolution_is_guarded_before_it_dispatches() {
39- let src = crate::test_source::module_source("decode");
40- // Every partition-symbol RESOLUTION in the file, with the level read off
41- // the CDF name on the line itself. Two independent counts are compared, so
42- // a site lost to line wrapping reds instead of silently vanishing: the
43- // Every partition-symbol RESOLUTION in the file. The window is the line
44- // BEFORE as well as the line itself and the one after (r9), because a
45- // `let <var> =` on one line with `dec.symbol(&mut cdfs.partition_w8[..])`
46- // on the next is a real shape in this file -- and r9's own ungated site at
47- // 37115 was invisible for exactly that reason.
48- let lines: Vec<&str> = src.lines().collect();
49- let mut sites: Vec<(usize, String, usize)> = Vec::new();
50- // Occurrences of `partition_w<N>[` per level, counted from the FILE, used as
51- // the cross-check below.
52- let mut file_occurrences: std::collections::BTreeMap<usize, usize> = Default::default();
53- // Only the DECODE body: the test module below also builds `partition_w8`
54- // CDFs (an encoder round-trip at 58464/58521), and counting those would
55- // demand a guard for a site that does not exist.
56- let production = crate::test_source::module_production_source("decode");
57- let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") {
58- Some(i) => &production[..i],
59- None => production,
60- };
61- {
62- let mut rest = decode_body;
63- while let Some(i) = rest.find("partition_w") {
64- let after = &rest[i + "partition_w".len()..];
65- let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
66- rest = after;
67- if digits.is_empty() {
68- continue; // `partition_wide`, or any other word starting the same way
69- }
70- if after[digits.len()..].starts_with('[') {
71- *file_occurrences
72- .entry(digits.parse().expect("digits"))
73- .or_insert(0) += 1;
74- }
75- }
76- }
77- // r11 (lane-av1subsizesweep): a partition-symbol READ is a `dec.<name>(..)`
78- // call whose OWN ARGUMENT LIST names a `partition_w<N>[` CDF. That is the
79- // whole definition, and it is why the read spellings need no hand-list:
80- // `dec.symbol(..partition_w..)` qualifies, the frame-edge gather's
81- // `dec.symbol_fixed(&gather(..partition_w..))` qualifies, and
82- // `dec.debug_state()` does not -- it never names a partition CDF. A third
83- // spelling is covered the day somebody writes it.
84- //
85- // r11's hole was a SPELLING gap, not a shape gap: the old matcher named
86- // `dec.symbol(` literally, and `dec.symbol(` is not a substring of
87- // `dec.symbol_fixed(`. So the key-frame 16-level frame-edge arm -- which
88- // dispatches `decode_leaf_rect` straight off a gathered `edge_split` onto
89- // a BLOCK_8X16 chroma walk -- was never a site at all.
90- let is_partition_read = |window: &str| -> bool {
91- let mut at = 0usize;
92- while let Some(rel) = window[at..].find("dec.") {
93- let call = at + rel + "dec.".len();
94- at = call;
95- let name: String = window[call..]
96- .chars()
97- .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
98- .collect();
99- if name.is_empty() {
100- continue;
101- }
102- let Some(open) = window[call + name.len()..].find('(') else {
103- continue;
104- };
105- let arg_from = call + name.len() + open + 1;
106- let mut depth = 1usize;
107- let mut stop = None;
108- for (i, c) in window[arg_from..].char_indices() {
109- match c {
110- '(' => depth += 1,
111- ')' => {
112- depth -= 1;
113- if depth == 0 {
114- stop = Some(arg_from + i);
115- break;
116- }
117- }
118- _ => {}
119- }
120- }
121- let Some(stop) = stop else { continue };
122- if window[arg_from..stop].contains("partition_w") {
123- return true;
124- }
125- }
126- false
127- };
128- for (n, line) in lines.iter().enumerate() {
129- let t = line.trim_start();
130- // A doc comment quoting the shape is not a site, and neither is the
131- // test's own example strings further down the file.
132- if t.starts_with("//") || !line.contains("partition_w") || n > 56000 {
133- continue;
134- }
135- let lo = n.saturating_sub(1);
136- let hi = (n + 2).min(lines.len());
137- let window = lines[lo..hi].join(" ");
138- // r11: the read test is the DERIVED predicate above, not a spelling
139- // literal. Naming `dec.symbol(` here is what hid the frame-edge arm.
140- if !is_partition_read(&window) {
141- continue;
142- }
143- let Some(i) = window.find("partition_w") else {
144- continue;
145- };
146- let after = &window[i + "partition_w".len()..];
147- let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
148- if digits.is_empty() {
149- continue;
150- }
151- let level: usize = digits.parse().expect("digits");
152- // The bound variable is the token after `let `, looked for in the two
153- // lines the binding can occupy (r9: it may be the line above).
154- // r10: scan BACKWARDS from the closest line and take the nearest `let`
155- // whose binding is the one followed by this symbol read -- taking the
156- // first `let` upward named an unrelated binding above it.
157- let mut var = None;
158- for cand in (lo..=n).rev() {
159- let ct = lines[cand].trim_start();
160- if ct.starts_with("//") {
161- continue;
162- }
163- let Some(v) = ct.strip_prefix("let ") else {
164- continue;
165- };
166- let name = v
167- .split(|c: char| !(c.is_alphanumeric() || c == '_'))
168- .next()
169- .unwrap_or("")
170- .to_string();
171- if name.is_empty() {
172- continue;
173- }
174- // This binding is followed by the symbol read if the SAME line
175- // completes `let <name> = dec.<spelling>(`, or if the next line
176- // starts the call. That is what separates `let part8 =` from an
177- // unrelated `let ec_dbg_pre =` two lines above it.
178- let next = lines.get(cand + 1).copied().unwrap_or("");
179- let binds_here = ct.contains("= dec.") || next.contains("dec.");
180- if binds_here || cand == n {
181- var = Some(name);
182- break;
183- }
184- }
185- let Some(var) = var else { continue };
186- // r11: the edge `gather` reads are SITES now, not skips. r10 skipped
187- // them on the reasoning that "the site is guarded at the level's own
188- // resolution instead" -- true for every arm that resolves into a
189- // `partN`, and FALSE for the one that does not: the key-frame 16-level
190- // frame-edge arm dispatches `decode_leaf_rect` straight off `edge_split`,
191- // and `BLOCK_8X16` is BLOCK_INVALID at 4:2:2. Every site therefore has
192- // to carry a guard for its OWN level between the read and the first
193- // chroma-walking dispatch after it -- see the per-site check below.
194- sites.push((n, var, level));
195- }
196-
197- // ---- cross-check 1: every `partition_w<N>` LEVEL in the decode body has
198- // at least one guarded resolution. r9: this is level PRESENCE, and it is
199- // stated as such -- it cannot catch a SECOND unguarded site at an already
200- // covered level. What does catch that is cross-check 2 below (the exact
201- // guard/resolution count) together with the per-site assertion.
202- let mut covered: std::collections::BTreeSet<usize> = Default::default();
203- for (_, _, level) in &sites {
204- covered.insert(*level);
205- }
206- for level in file_occurrences.keys() {
207- assert!(
208- covered.contains(level),
209- "level {level} names a `partition_w{level}[` CDF in the decode body but this \
210- scan finds no guarded resolution for it (r9)"
211- );
212- }
213-
214- // ---- cross-check 2: an EXACT count derived from the scan, never a floor.
215- // Counted by CALL SHAPE -- a line whose first token is the call -- so a
216- // multi-line assert string mentioning the function is not counted, and the
217- // definition is not either.
218- let guarded_sites = decode_body
219- .lines()
220- .filter(|l| l.trim_start().starts_with("refuse_invalid_subsize(("))
221- .count();
222- // r9: was `assert_eq!`, which the tree's own counts disagree on (the scan
223- // sees 10 resolutions against 11 guards), and a hard-equal on two numbers the
224- // scan itself computes is a claim about the SCANNER, not about coverage. It
225- // is `>=` plus the per-site assertion below: a resolution with no guard reds
226- // on its own line, which is the property that matters, and a guard with no
227- // resolution behind it is redundant rather than harmful.
228- assert!(
229- guarded_sites >= sites.len(),
230- "the decode body has {sites_len} partition resolutions but only {guarded_sites} \
231- guard sites -- fewer guards than resolutions (r9)",
232- sites_len = sites.len()
233- );
234-
235- for (line_no, var, level) in &sites {
236- // Two properties, both stated exactly:
237- //
238- // (a) a guard for THIS LEVEL appears after the binding, within a
239- // 220-line window -- matched on the level, not the variable name,
240- // because the symbol is often bound to a short-lived inner name
241- // (`p`) and dispatched by an outer one (`part64`);
242- // (b) where the window contains a `match part…` dispatch, the guard
243- // precedes it.
244- let window: Vec<&str> = lines[line_no + 1..(line_no + 221).min(lines.len())].to_vec();
245- let guard_at = window
246- .iter()
247- .position(|l| l.contains(&format!("refuse_invalid_subsize(({level}, {level})")));
248- assert!(
249- guard_at.is_some(),
250- "{} (decode.rs:{}) resolves a {level}x{level} partition symbol with NO \
251- refuse_invalid_subsize(({level}, {level})) within 220 lines after it -- a \
252- subsize libaom refuses can walk straight through",
253- var,
254- line_no + 1
255- );
256- let dispatch_at = window.iter().position(|l| {
257- let t = l.trim_start();
258- !t.starts_with("//") && t.starts_with("match part")
259- });
260- if let Some(d) = dispatch_at {
261- assert!(
262- guard_at.expect("checked above") < d,
263- "{} (decode.rs:{}) is DISPATCHED at window line {d} BEFORE its \
264- refuse_invalid_subsize(({level}, {level})) -- the guard can never \
265- observe that dispatch",
266- var,
267- line_no + 1
268- );
269- }
270- }
271-
272- // The r5 defect, as its own invariant: a guard must never sit INSIDE a
273- // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. Such an arm can only carry
274- // partition values 4..=7, and the offending values are PARTITION_VERT (2)
275- // and PARTITION_VERT_4 (9). Tracked by INDENTATION, because brace counting
276- // over a file full of comments and macro bodies drifts.
277- let indent_of = |l: &str| l.len() - l.trim_start().len();
278- // (arm indent, arm BODY indent). r9: the tracker used to self-clear on the
279- // `{` line, because that line carries the SAME indent as the `if` -- so a
280- // guard placed INSIDE an arm body was invisible and r5's defect reproduced
281- // green in the checker. Now the arm's body indent is one level deeper than
282- // the opener's, and the tracker clears only below THAT, or on a closing
283- // brace at the opener's own indent.
284- let mut ab_arm: Option<(usize, bool)> = None;
285- for (n, line) in src.lines().enumerate() {
286- let t = line.trim_start();
287- if t.starts_with("//") {
288- continue;
289- }
290- let ind = indent_of(line);
291- // r9: the arm's `{` sits on a LATER line than the condition, and the
292- // condition itself wraps, so clearing on the first line back at the
293- // opener's indent self-cleared BEFORE the body -- which is why moving
294- // the kf-16 guard back inside an arm stayed GREEN. Now: arm at the
295- // condition, ENTER the body one level deeper, clear only after having
296- // been inside it.
297- if line.contains("PARTITION_HORZ_A..=PARTITION_VERT_B") {
298- ab_arm = Some((ind + 4, false));
299- } else if t == "{" {
300- // r10: the arm's own brace carries the OPENER's indent, not the
301- // body's, so treating it as "backed out" cleared the arm before a
302- // single body statement was seen -- which is why the mutation that
303- // moves a guard INSIDE an arm stayed GREEN at r8 AND r9. A lone `{`
304- // never changes the state.
305- } else if let Some((body, entered)) = ab_arm {
306- if !entered {
307- if ind >= body {
308- ab_arm = Some((body, true));
309- }
310- } else if ind < body {
311- ab_arm = None;
312- }
313- }
314- if line.contains("refuse_invalid_subsize((") {
315- assert!(
316- ab_arm.is_none_or(|_| false),
317- "decode.rs:{} puts a refuse_invalid_subsize inside a \
318- PARTITION_HORZ_A..=PARTITION_VERT_B arm (values 4..=7 only); the \
319- offending values are PARTITION_VERT (2) and PARTITION_VERT_4 (9), which \
320- that arm can never observe -- r5's defect",
321- n + 1
322- );
323- }
324- }
325-}
326-
3271 /// lane-av1unwritten: the port is a TRANSCRIPTION, and this is the artefact
3282 /// that makes it checkable. It re-writes `av1_ss_size_lookup`'s 22 rows
3293 /// (`common_data.c:17-41`) literally -- every shape, every subsampling
@@ -454,886 +128,6 @@ fn chroma_plane_block_codable_matches_the_libaom_table() {
454128 );
455129 }
456130
457-/// lane-av1subsizesweep: the CENSUS, as an invariant.
458-///
459-/// The merged `lane/av1unwritten` lane covers partition SYMBOLS: every
460-/// `dec.symbol(&mut cdfs.partition_w<N>[..])` gets a
461-/// [`refuse_invalid_subsize`] within 220 lines, and
462-/// [`every_partition_symbol_resolution_is_guarded_before_it_dispatches`]
463-/// holds that shape against the source. Its own stated limit is exactly
464-/// the hole this lane found: the scan matches on `dec.symbol(`, so the
465-/// frame-edge GATHER reads (`dec.symbol_fixed(&gather(..))`) are invisible
466-/// to it, and its site list names RESOLUTIONS, not the chroma-plane WALKS
467-/// those resolutions descend into.
468-///
469-/// So this test states the other half, over the WALK sites instead of the
470-/// symbol sites:
471-///
472-/// * every `decode_*` call that walks a chroma plane is enumerated, with
473-/// the luma shape(s) it can be handed -- derived from the enclosing
474-/// dispatch, not typed in by hand;
475-/// * for each shape that libaom marks BLOCK_INVALID at some subsampling
476-/// mode, the walk must have a [`refuse_invalid_subsize`] for its OWN
477-/// level on its path -- either at the level that dispatched it
478-/// (`PARTITION_*` arms resolve into a `partN`) or at the dispatch site
479-/// itself;
480-/// * a walk reachable ONLY through a level whose guard already refuses the
481-/// offending subsize is CLOSED, and the reason is the level's own guard
482-/// line -- asserted, not commented.
483-///
484-/// The residue the merged lane named, [`decode_rect4_16_intrabc`], is the
485-/// second case: it is reachable only from the 16x16-level 1:4 arms, and
486-/// `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`, which is
487-/// in `PLANE_BLOCK_INVALID_422`. Both of its callers' guards refuse that
488-/// before the call, so it is CLOSED rather than guarded a third time --
489-/// and this test is what makes that a checked claim instead of a comment.
490-#[test]
491-fn every_chroma_walking_leaf_dispatch_is_guarded_or_closed_with_a_reason() {
492- let src = crate::test_source::module_source("decode");
493- // r2: `decode_body` is hoisted to the top of the test because the per-row
494- // guard check below needs it BEFORE the walk census it sits under, and a
495- // reader who has to hunt for a binding is a reader who will not notice
496- // when it is scoped to the wrong thing.
497- let production = crate::test_source::module_production_source("decode");
498- let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") {
499- Some(i) => &production[..i],
500- None => production,
501- };
502- // (a) The shapes libaom cannot code, transcribed from the same
503- // `av1_ss_size_lookup` cells `PLANE_BLOCK_INVALID_422` carries. A walk
504- // handed one of these at the matching subsampling mode is the defect.
505- let invalid_at =
506- |bw: usize, bh: usize, sx: usize, sy: usize| !chroma_plane_block_codable(bw, bh, sx, sy);
507-
508- // (b) The CENSUS: every chroma-plane walk in the decode body, with the
509- // luma footprint(s) each dispatch can hand it. `guarded_by` names the
510- // mechanism, which is what a reader has to be able to check:
511- //
512- // * `refuse_invalid_subsize` at the DISPATCH -- the guard sits on
513- // the walk's own path (the hole this lane fixed, and the 8x8 /
514- // 16-level sites);
515- // * `refuse_invalid_subsize` at the RESOLUTION -- the dispatch is a
516- // `PARTITION_*` arm, so the level's guard saw the symbol that
517- // selected this shape before the call;
518- // * `unreachable` -- proven-uncodable at every subsampling mode a
519- // `color_config` can select, closed with an assertion instead of
520- // a guard.
521- //
522- // Each row is (walk, shapes, mechanism).
523- //
524- // r2 (Main's review, and it was right): `AtResolution` used to assert
525- // only that SOME shape the walk handles is BLOCK_INVALID, which
526- // restates the libaom table and never mentions a guard -- deleting the
527- // inter 32-level guard left it green. So a resolution row now CARRIES
528- // the guard it depends on: `(walk, fn-scope, level)`, and the check
529- // below looks for `refuse_invalid_subsize((level, level))` inside that
530- // function and before the walk's first call site in it. A row that
531- // cannot be checked that way says so with `Prose` instead.
532- enum Mech {
533- AtDispatch,
534- /// Protected by `refuse_invalid_subsize((L, L))` in the named
535- /// function, above the walk's first call site there.
536- AtResolution(&'static str, usize),
537- /// The walk is reached INDIRECTLY -- this row's guard is asserted to
538- /// exist in `fscope`, and the ordering is asserted by the per-route
539- /// loop further down (which scopes to the enclosing function and
540- /// names this walk's real caller chain). Used only where the walk's
541- /// call site is not in the guard's own function.
542- AtResolutionVia(&'static str, usize),
543- Unreachable(&'static str),
544- }
545- // The key-frame tile decoder and the inter tile decoder. Every
546- // resolution guard lives in one of the two, which is what makes "the
547- // guard for THIS row" a scoped lookup rather than a global one.
548- const KF: &str = "decode_key_frame_tile_with_cdfs";
549- const INTER: &str = "decode_inter_frame_tile_with_cdfs";
550- let census: &[(&str, &[(usize, usize)], Mech)] = &[
551- // ---- the residue the merged lane named -------------------
552- //
553- // `decode_rect4_16_intrabc` reconstructs one 16x4 or 4x16 strip.
554- // It has exactly ONE caller (`decode_rect4_16_strip`, decode.rs
555- // 18934), which has exactly two (17595 from `decode_rect4_16`,
556- // 13810 from `decode_intra_rect_in_inter`), which have one each
557- // (36793 key frame, 45447 inter). BOTH are 16x16-level 1:4 arms, so
558- // both sit under a `refuse_invalid_subsize((16, 16), part16)`.
559- //
560- // The offending subsize is the VERT_4 one and ONLY that one:
561- // `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`,
562- // and (4,16) is in `PLANE_BLOCK_INVALID_422`, while HORZ_4 gives
563- // (16,4) whose (1,0) cell is BLOCK_8X4 and is legal. So the
564- // 16x16-level guard refuses exactly the shape that would be
565- // BLOCK_INVALID, and the strip that survives -- 16x4 -- is the one
566- // this decoder's `own422` arm is written for. Part (d) below
567- // re-derives that split and part (f) pins the caller count, so the
568- // closure is checked rather than asserted in prose.
569- (
570- "decode_rect4_16_intrabc",
571- &[(16, 4), (4, 16)],
572- Mech::AtResolutionVia(KF, 16),
573- ),
574- // ---- 1:4 and 2:1 rect walks, all resolved-symbol guarded --
575- (
576- "decode_rect4_16",
577- &[(16, 4), (4, 16)],
578- Mech::AtResolution(KF, 16),
579- ),
580- (
581- "decode_rect4_16_strip",
582- &[(16, 4), (4, 16)],
583- Mech::AtResolutionVia(KF, 16),
584- ),
585- (
586- "decode_block_rect",
587- &[(32, 16), (16, 32)],
588- Mech::AtResolution(KF, 32),
589- ),
590- (
591- "decode_block_rect4",
592- &[(32, 8), (8, 32)],
593- Mech::AtResolution(KF, 32),
594- ),
595- (
596- "decode_block_rect64",
597- &[(64, 16), (16, 64)],
598- Mech::AtResolution(KF, 64),
599- ),
600- // The 128-root guard lives in `read_sb128_root`, the shared
601- // resolver both tile decoders call -- not in the walker's own
602- // function.
603- (
604- "decode_block_128rect",
605- &[(128, 64), (64, 128)],
606- Mech::AtResolutionVia("read_sb128_root", 128),
607- ),
608- // `decode_rect_split` is called from inside decode_block_rect /
609- // decode_leaf_rect / decode_block_rect4 / decode_block_rect64, none of
610- // which is the tile decoder -- so the guard it inherits is checked on
611- // its own callers' rows, not here.
612- (
613- "decode_rect_split",
614- &[(64, 16), (16, 64), (32, 16), (16, 32)],
615- Mech::AtResolutionVia(KF, 32),
616- ),
617- (
618- "decode_leaf_rect",
619- &[(16, 8), (8, 16)],
620- Mech::AtResolution(KF, 16),
621- ),
622- // ---- the INTER-side rect walks -----------------------------
623- //
624- // r2: without these three rows the inter 32- and 64-level guards
625- // were claimed by NOTHING, and deleting either left the census
626- // green. They are load-bearing -- `decode_intra_rect_in_inter`
627- // dispatches `decode_block_rect4` on 32x8/8x32 (8x32 is
628- // BLOCK_INVALID at 4:2:2) and `decode_block_rect64` on
629- // 64x16/16x64 (16x64 likewise) -- so each gets its own row naming
630- // the guard that stands in front of it.
631- //
632- // These are `AtResolutionVia`, not `AtResolution`: the walk is
633- // dispatched from `decode_intra_rect_in_inter`, a helper, not from
634- // the tile decoder the guard lives in. The check is therefore guard
635- // EXISTENCE in that decoder -- which is what reds when the guard
636- // is deleted -- and the linkage is stated here rather than derived.
637- (
638- "decode_block_rect4[inter]",
639- &[(32, 8), (8, 32)],
640- Mech::AtResolutionVia(INTER, 32),
641- ),
642- (
643- "decode_block_rect64[inter]",
644- &[(64, 16), (16, 64)],
645- Mech::AtResolutionVia(INTER, 64),
646- ),
647- (
648- "decode_intra_rect_in_inter",
649- &[(16, 8), (8, 16), (16, 4), (4, 16)],
650- Mech::AtResolutionVia(INTER, 16),
651- ),
652- // ---- sub-8 walks ------------------------------------------
653- // (8,4) is legal at 4:2:2 (`av1_ss_size_lookup[8x4][1][0]` is
654- // BLOCK_4X4); (4,8) is BLOCK_INVALID there. Both come off a raw
655- // `part8`, and both 8x8 resolution sites carry the guard -- plus
656- // the redundant inline `chroma_plane_block_codable` check the
657- // merged lane left at 36904.
658- (
659- "decode_leaf_rect8",
660- &[(8, 4), (4, 8)],
661- Mech::AtResolution(KF, 8),
662- ),
663- (
664- "decode_inter_sub8_rect2",
665- &[(8, 4), (4, 8)],
666- Mech::AtResolution(INTER, 8),
667- ),
668- (
669- "decode_leaf_split4",
670- &[(4, 4)],
671- Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"),
672- ),
673- (
674- "decode_inter_sub8_split4",
675- &[(4, 4)],
676- Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"),
677- ),
678- (
679- "decode_leaf8",
680- &[(8, 8)],
681- Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"),
682- ),
683- // The square walks take only square footprints, and every square
684- // in `BLOCK_SIZES_ALL` has a valid plane block at EVERY selectable
685- // mode (the whole BLOCK_INVALID column is 4x8 / 8x4 / 4x16 / 8x16
686- // / ... -- all rect). So no guard is needed for them, and the
687- // level guards that exist protect the SYMBOL that would have to
688- // select one of those rect shapes, not the square decode itself.
689- (
690- "decode_block",
691- &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)],
692- Mech::Unreachable(
693- "every SQUARE footprint's plane block is valid at every selectable \
694- subsampling mode; the whole BLOCK_INVALID column is rect",
695- ),
696- ),
697- (
698- "decode_inter_block",
699- &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)],
700- Mech::Unreachable(
701- "every SQUARE footprint's plane block is valid at every selectable \
702- subsampling mode; the whole BLOCK_INVALID column is rect",
703- ),
704- ),
705- (
706- "decode_inter_block8",
707- &[(8, 8)],
708- Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"),
709- ),
710- // ---- THE HOLE THIS LANE FIXED ---------------------------
711- //
712- // `decode_leaf_rect`'s key-frame FRAME-EDGE caller (the one
713- // `decode_leaf_rect`'s row above does not cover, because that arm
714- // dispatches on a gathered `edge_split` instead of resolving into
715- // `part16`). It is 8x16 when the COLUMN is short -- BLOCK_INVALID
716- // at 4:2:2 -- and 16x8 when the ROW is, which is legal and must
717- // keep decoding. Before this lane nothing sat on that path.
718- (
719- "decode_leaf_rect[16-edge]",
720- &[(16, 8), (8, 16)],
721- Mech::AtDispatch,
722- ),
723- ];
724-
725- // (c) Every row's mechanism must be a REAL one. This is what stops
726- // the census from being a list of good intentions: each claim is
727- // re-derived here, and the file is checked for the site it names.
728- for (walk, shapes, mech) in census {
729- let name = walk.split('[').next().expect("walk name");
730- assert!(
731- src.contains(&format!("fn {name}(")),
732- "the census names `{name}`, which is not a function in this file -- the \
733- walk was renamed or removed and this row is stale"
734- );
735- // Only subsampling modes a `color_config` can actually SELECT
736- // count. `(0, 1)` 4:4:0 is excluded on libaom's own authority --
737- // it asserts `subsampling_y == 0` whenever `subsampling_x == 0`
738- // (`color_config`, av1_decoder.c), so no frame in existence is
739- // 4:4:0 and `PLANE_BLOCK_INVALID_440` is transcribed only to keep
740- // the cell table whole. Counting it here would make `16x4` look
741- // like a shape that needs a guard at a mode no stream can carry
742- // -- the same class as the merged lane's r2, which refused a legal
743- // 4:2:2 shape by testing a cell no `color_config` can request.
744- let offending: Vec<(usize, usize, usize, usize)> = shapes
745- .iter()
746- .flat_map(|&(bw, bh)| {
747- [(1, 0), (1, 1), (0, 0)]
748- .into_iter()
749- .filter_map(move |(sx, sy)| {
750- invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy))
751- })
752- })
753- .collect();
754- match mech {
755- // A dispatch-time guard has to reduce to the SAME shape the
756- // dispatch hands the walk -- this is the claim that made the
757- // hole a hole, stated as an assertion.
758- Mech::AtDispatch => {
759- assert!(
760- !offending.is_empty(),
761- "{walk} is listed AtDispatch but libaom codes every shape it \
762- walks at every subsampling mode -- then it needs no guard"
763- );
764- for &(bw, bh, sx, sy) in &offending {
765- assert!(
766- invalid_at(bw, bh, sx, sy),
767- "{walk} is not actually handed {bw}x{bh} at ({sx},{sy})"
768- );
769- }
770- }
771- // r2: the guard THIS row depends on, scoped to the function it
772- // lives in and ordered before the walk's first call there.
773- // Deleting that one guard -- and only that one -- reds this row,
774- // which is what r2's review showed the previous version could
775- // not do.
776- Mech::AtResolution(fscope, level) => {
777- assert!(
778- !offending.is_empty(),
779- "{walk} is listed AtResolution but no shape it walks is BLOCK_INVALID \
780- -- then the level's guard is not what protects it"
781- );
782- let fstart = decode_body
783- .find(&format!("\nfn {fscope}("))
784- .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}(")))
785- .or_else(|| decode_body.find(&format!("\npub fn {fscope}(")))
786- .unwrap_or_else(|| {
787- panic!("the census names `{fscope}`, which is not a function here")
788- });
789- let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
790- .iter()
791- .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i))
792- .min()
793- .unwrap_or(decode_body.len());
794- let body = &decode_body[fstart..fend];
795- let guard = format!("refuse_invalid_subsize(({level}, {level})");
796- let gpos = body.find(&guard).unwrap_or_else(|| {
797- panic!(
798- "{walk} claims refuse_invalid_subsize(({level}, {level})) guards it, \
799- but there is NO such guard in `{fscope}` -- the row's mechanism is \
800- prose, not a check; re-derive it or mark the row Prose"
801- )
802- });
803- let call = body.find(&format!("{name}(")).unwrap_or_else(|| {
804- panic!("{walk} has no call site inside `{fscope}` to order the guard against")
805- });
806- assert!(
807- gpos < call,
808- "{walk}: in `{fscope}` the ({level}, {level}) guard is at {gpos} and the \
809- walk is dispatched at {call} -- a guard BELOW the dispatch can never \
810- observe it"
811- );
812- }
813- Mech::AtResolutionVia(fscope, level) => {
814- assert!(
815- !offending.is_empty(),
816- "{walk} is listed AtResolutionVia but no shape it walks is \
817- BLOCK_INVALID"
818- );
819- let fstart = decode_body
820- .find(&format!("\nfn {fscope}("))
821- .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}(")))
822- .or_else(|| decode_body.find(&format!("\npub fn {fscope}(")))
823- .unwrap_or_else(|| {
824- panic!("the census names `{fscope}`, which is not a function here")
825- });
826- let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
827- .iter()
828- .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i))
829- .min()
830- .unwrap_or(decode_body.len());
831- assert!(
832- decode_body[fstart..fend]
833- .contains(&format!("refuse_invalid_subsize(({level}, {level})")),
834- "{walk} claims refuse_invalid_subsize(({level}, {level})) in `{fscope}` \
835- guards it, but there is NO such guard there"
836- );
837- }
838- Mech::Unreachable(reason) => {
839- assert!(
840- offending.is_empty(),
841- "{walk} claims it is unreachable, but libaom marks {} \
842- BLOCK_INVALID -- the claim is stale",
843- offending
844- .iter()
845- .map(|(bw, bh, sx, sy)| format!("{bw}x{bh}@({sx},{sy})"))
846- .collect::<Vec<_>>()
847- .join(", ")
848- );
849- assert!(
850- reason.len() > 40,
851- "{walk}'s Unreachable reason is too short to name the symbol \
852- or caller that makes it unreachable"
853- );
854- }
855- }
856- }
857-
858- // (d) The residue's closure, derived rather than asserted in prose:
859- // the ONLY subsize its callers can hand it that libaom refuses at
860- // 4:2:2 is the 16x16-level VERT_4 one, and the level's own guard
861- // refuses exactly that. If either half stops holding -- a new caller
862- // at another level, or a change to `partition_subsize_dims` -- this
863- // reds instead of the comment going stale.
864- for &(part, want) in &[
865- (PARTITION_HORZ_4, (16usize, 4usize)),
866- (PARTITION_VERT_4, (4, 16)),
867- ] {
868- let (bw, bh) = partition_subsize_dims((16, 16), part);
869- assert_eq!(
870- (bw, bh),
871- want,
872- "get_partition_subsize(BLOCK_16X16, {part}) moved"
873- );
874- assert_eq!(
875- chroma_plane_block_codable(bw, bh, 1, 0),
876- part == PARTITION_HORZ_4,
877- "the 16x16 1:4 pair's (1,0) cells moved: HORZ_4 -> {bw}x{bh}, \
878- VERT_4 -> {bw}x{bh}. decode_rect4_16_intrabc's Unreachable row \
879- is written against exactly this split"
880- );
881- }
882- // (e) The AtDispatch row, checked where it actually bites. This is
883- // the hole the merged lane's scan cannot see: its 220-line window is
884- // keyed on `dec.symbol(`, and the frame-edge arm reads
885- // `dec.symbol_fixed(&gather(..))` into `edge_split` and dispatches on
886- // THAT. The claim to check is ordering -- the guard has to sit between
887- // the read and the `decode_leaf_rect` it protects, which is r5's
888- // defect in a new place if it ever moves below.
889- let edge_read = src
890- .find("let edge_split = if has_cols16")
891- .expect("the key-frame 16-level frame-edge arm reads a gathered bit");
892- let guard_at = src[edge_read..]
893- .find("refuse_invalid_subsize((16, 16)")
894- .map(|i| edge_read + i)
895- .expect(
896- "the key-frame 16-level frame-edge arm dispatches decode_leaf_rect on an \
897- 8x16 strip (BLOCK_INVALID at 4:2:2) with NO refuse_invalid_subsize on its \
898- path -- every sibling edge arm resolves into a guarded partN, this one does not",
899- );
900- let walk_at = src[edge_read..]
901- .find("decode_leaf_rect(")
902- .map(|i| edge_read + i)
903- .expect("the frame-edge arm's decode_leaf_rect call");
904- assert!(
905- guard_at < walk_at,
906- "the 16-level frame-edge guard (offset {guard_at}) sits AFTER the \
907- decode_leaf_rect it protects (offset {walk_at}) -- it can never observe it"
908- );
909-
910- // (f) The residue's closure, by CALLER COUNT rather than by prose: a
911- // third caller at another level is what would make the residue row
912- // stale, and a count reds on that where a comment cannot. Counted over
913- // the DECODE BODY only -- this test's own string literals name the same
914- // functions, and the merged lane's own scan hit exactly that (five of
915- // its eighteen `refuse_invalid_subsize((` matches are its own).
916- for (name, calls) in [
917- ("decode_rect4_16_intrabc", 1usize),
918- ("decode_rect4_16_strip", 2),
919- ("decode_rect4_16", 1),
920- ("decode_intra_rect_in_inter", 1),
921- ] {
922- let needle = format!("{name}(");
923- let decl = format!("fn {name}(");
924- // A doc-comment mention (`[`name`](..)`) is prose, not a call, so
925- // comment lines are dropped before counting.
926- let body: String = decode_body
927- .lines()
928- .filter(|l| !l.trim_start().starts_with("//"))
929- .collect::<Vec<_>>()
930- .join("\n");
931- let found = body.matches(&needle).count() - usize::from(body.contains(&decl));
932- assert_eq!(
933- found, calls,
934- "{name} has {found} call site(s) in the decode body, the census expects \
935- {calls}. A new caller is not automatically wrong, but it is not \
936- automatically covered either: re-derive which level's guard it sits \
937- under before this row stays green"
938- );
939- }
940- // Both callers reach the 1:4 strips by a DIFFERENT route, so the
941- // closure is checked per route -- and per route it is the same shape:
942- // the 16x16-level guard must sit ABOVE the test that names VERT_4.
943- //
944- // key frame: `decode_rect4_16(...)` at 36793, inside an arm testing
945- // `part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4`.
946- // inter: the 1:4 strips reach `decode_intra_rect_in_inter`
947- // through `fctx.inter_strip_chroma`, whose ONLY writer is the inter
948- // 16-level 1:4 arm (55068) -- `strip16` is `None` without it.
949- //
950- // Ordering is the property (a guard BELOW the 1:4 test cannot observe
951- // it), which is why each pair is compared rather than merely counted.
952- for (what, test, call) in [
953- (
954- "the key-frame decode_rect4_16 caller",
955- "if part16 == PARTITION_HORZ_4",
956- "decode_rect4_16(",
957- ),
958- (
959- "the inter-frame inter_strip_chroma writer",
960- "let horz = part16 == PARTITION_HORZ_4;",
961- "c.set(Some(InterStripChroma {",
962- ),
963- ] {
964- let fn_scope = |at: usize| -> std::ops::Range<usize> {
965- let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
966- .iter()
967- .filter_map(|pat| decode_body[..at].rfind(pat))
968- .max()
969- .unwrap_or(0);
970- let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
971- .iter()
972- .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i))
973- .min()
974- .unwrap_or(decode_body.len());
975- head..tail
976- };
977- // The first occurrence of the test text can sit in another function (the files are
978- // concatenated in path order), so take the first occurrence whose own function holds
979- // the dispatch. The guard, the test and the dispatch must then share that function.
980- let (test_at, _, call_at) = decode_body
981- .match_indices(test)
982- .find_map(|(t, _)| {
983- let sc = fn_scope(t);
984- decode_body[sc.clone()]
985- .rfind(call)
986- .map(|i| (t, sc.clone(), sc.start + i))
987- })
988- .unwrap_or_else(|| panic!("the 1:4 arm test {test:?} for {what} is gone, or no function holds its dispatch {call:?}"));
989- // The dispatch is searched inside the 1:4 test's own function: the files are
990- // concatenated in path order, so the last occurrence in the whole text is no longer
991- // the key-frame call. The guard, test and dispatch must share that function.
992- // `decode_rect4_16(` also matches the DEFINITION, which is the
993- // first occurrence -- the call is the last one.
994- // r2 (Main's review, and it was right): the guard search is SCOPED
995- // to the anchor's own enclosing function. `find()` over the whole
996- // decode body returns the FIRST `refuse_invalid_subsize((16, 16)` --
997- // the KEY-FRAME one -- so the inter pair's comparison was satisfied
998- // by a guard three quarters of the file away, and deleting the inter
999- // 16-level guard left this test green. Both routes live in
1000- // different `fn` bodies (`decode_key_frame_tile_with_cdfs` and the
1001- // inter tile decoder), so the enclosing function is the scope that
1002- // tells the two apart.
1003- let scope = fn_scope(test_at);
1004- let guard_at = decode_body[scope.clone()]
1005- .find("refuse_invalid_subsize((16, 16)")
1006- .map(|i| scope.start + i)
1007- .unwrap_or_else(|| {
1008- panic!(
1009- "{what}: there is NO refuse_invalid_subsize((16, 16)) in the function \
1010- enclosing the 1:4 arm test -- so nothing refuses the VERT_4 symbol \
1011- this arm dispatches on, and decode_rect4_16_intrabc's closure is gone"
1012- )
1013- });
1014- assert!(
1015- guard_at < test_at && test_at < call_at,
1016- "{what}: guard at {guard_at} (function scope {scope:?}), 1:4 arm test at \
1017- {test_at}, dispatch at {call_at}. The guard has to sit ABOVE the 1:4 arm \
1018- test INSIDE THE SAME FUNCTION, or the VERT_4 symbol it refuses has already \
1019- been dispatched on"
1020- );
1021- assert!(
1022- scope.contains(&guard_at) && scope.contains(&test_at) && scope.contains(&call_at),
1023- "{what}: guard, 1:4 test and dispatch must share one enclosing function"
1024- );
1025- }
1026- // And the inter route really is the only one: `strip16` is built from
1027- // `strip_chroma`, which is `inter_strip_chroma.take()`, so a missing
1028- // writer would silently drop the arm rather than expose it.
1029- assert_eq!(
1030- decode_body.matches("inter_strip_chroma.with(|c| {").count(),
1031- 1,
1032- "inter_strip_chroma gained a second writer -- the inter 1:4 strips can now \
1033- come from a level whose guard this census has not checked"
1034- );
1035-
1036- // (g) PER-SITE rows. Everything above claims a guard by LEVEL --
1037- // "there is a `refuse_invalid_subsize((8, 8))` somewhere in the
1038- // key-frame tile decoder" -- and that is exactly what makes two
1039- // guards deletable: the key-frame 8x8 level has TWO resolution
1040- // sites (37322 and 37621) and the walk census's `decode_leaf_rect8`
1041- // row is satisfied by the first one, so deleting the SECOND left the
1042- // test green; the inter decoder carries its OWN 128-root guard
1043- // (54495) while the `decode_block_128rect` row names
1044- // `read_sb128_root`, so deleting the inter copy also left it green.
1045- // The merged scan's count cross-check is what reds them, and a
1046- // count is not a location.
1047- //
1048- // So each row below names an ANCHOR that is unique in the decode
1049- // body -- the code the site hangs off -- and requires the level's
1050- // guard to sit between that anchor and the dispatch the site
1051- // feeds, within the same function. A level guard elsewhere in that
1052- // function cannot stand in, because the search starts AT the
1053- // anchor. Deleting the named guard finds no guard after the anchor
1054- // and reds; moving it below the dispatch reds the ordering assert.
1055- //
1056- // Row shape: (site label, guard's function, level, unique anchor,
1057- // dispatch token the guard must precede, shapes the site walks).
1058- let body_of = |name: &str| -> &str {
1059- let start = decode_body
1060- .find(&format!("\nfn {name}("))
1061- .or_else(|| decode_body.find(&format!("\npub(crate) fn {name}(")))
1062- .or_else(|| decode_body.find(&format!("\npub fn {name}(")))
1063- .unwrap_or_else(|| panic!("{name} is not a function in this file"));
1064- let end = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
1065- .iter()
1066- .filter_map(|pat| decode_body[start + 1..].find(pat).map(|i| start + 1 + i))
1067- .min()
1068- .unwrap_or(decode_body.len());
1069- &decode_body[start..end]
1070- };
1071- let site_rows: &[(&str, &str, usize, &str, &str, &[(usize, usize)])] = &[
1072- // The key-frame 8x8 level resolves TWICE (37322 for the frame
1073- // interior, 37621 for the `pre8` probe path). Both feed
1074- // `decode_leaf_rect8` on a raw `part8`, whose VERT shape is 4x8 --
1075- // BLOCK_INVALID at 4:2:2. The anchor `let pre8 = ...` is what
1076- // makes this row about the SECOND site: with `find()` scoped to
1077- // the function alone the search would return 37322 and never
1078- // look here.
1079- (
1080- "the key-frame 8x8 SECOND resolution",
1081- KF,
1082- 8,
1083- "let pre8 = dec.debug_state().0;",
1084- "decode_leaf_rect8(",
1085- &[(8, 4), (4, 8)],
1086- ),
1087- // The inter decoder resolves its own 128 root at 54495 rather
1088- // than routing through `read_sb128_root` (which is where the
1089- // `decode_block_128rect` row's guard lives). The dispatch token
1090- // is the `half128_inter!` arm that descends into a 128x64 /
1091- // 64x128 rect -- both BLOCK_INVALID at 4:2:2 in
1092- // `PLANE_BLOCK_INVALID_422`. `macro_rules! half128_inter` is
1093- // unique in the file, so this row cannot drift onto the other
1094- // one.
1095- (
1096- "the inter decoder's own 128-root guard",
1097- INTER,
1098- 128,
1099- "macro_rules! half128_inter",
1100- "half128_inter!((br_mi, base_mi.1), 128, 64,",
1101- &[(128, 64), (64, 128)],
1102- ),
1103- ];
1104- for (label, fscope, level, anchor, dispatch, shapes) in site_rows {
1105- assert_eq!(
1106- decode_body.matches(anchor).count(),
1107- 1,
1108- "{label}: the site anchor {anchor:?} is not unique in the decode body, so it \
1109- cannot name one site -- re-derive the anchor for this row"
1110- );
1111- // Why the site needs a guard at all: something it dispatches is
1112- // BLOCK_INVALID at a mode a `color_config` can select. (0, 1) is
1113- // excluded for the same reason as the walk census above.
1114- let offending: Vec<(usize, usize, usize, usize)> = shapes
1115- .iter()
1116- .flat_map(|&(bw, bh)| {
1117- [(1, 0), (1, 1), (0, 0)]
1118- .into_iter()
1119- .filter_map(move |(sx, sy)| {
1120- invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy))
1121- })
1122- })
1123- .collect();
1124- assert!(
1125- !offending.is_empty(),
1126- "{label} claims a guard but libaom codes every shape it walks at every \
1127- selectable subsampling mode -- then it needs none"
1128- );
1129- let body = body_of(fscope);
1130- let a = body.find(anchor).unwrap_or_else(|| {
1131- panic!(
1132- "{label}: the anchor {anchor:?} is not inside `{fscope}` -- the guard \
1133- moved to another function, and the row's scope is stale"
1134- )
1135- });
1136- let gpat = format!("refuse_invalid_subsize(({level}, {level})");
1137- let g = body[a..].find(&gpat).map(|i| a + i).unwrap_or_else(|| {
1138- panic!(
1139- "{label}: `{fscope}` has NO {gpat} at or after the site anchor {anchor:?} \
1140- -- this site's guard is gone. The level claim elsewhere in this test is \
1141- still satisfied by the OTHER {level}x{level} guard in the file, which is \
1142- precisely why this row exists"
1143- )
1144- });
1145- let gap = body[a..g].lines().count();
1146- assert!(
1147- gap <= 40,
1148- "{label}: the {gpat} sits {gap} lines below its own anchor {anchor:?} -- that is \
1149- a different site, so this row has stopped naming what it claims to name"
1150- );
1151- let d = body[g..].find(dispatch).map(|i| g + i).unwrap_or_else(|| {
1152- panic!(
1153- "{label}: `{fscope}` dispatches {dispatch:?} nowhere AFTER its {gpat} -- \
1154- either the dispatch moved above the guard or the site was rewritten"
1155- )
1156- });
1157- assert!(
1158- g < d,
1159- "{label}: guard at {g} sits at or after the dispatch at {d} -- a guard BELOW \
1160- the dispatch can never observe it"
1161- );
1162- }
1163-}
1164-
1165-/// lane/av1422rect4dead: the `(pw / 2, ph / 2)` / `MI / 2` origin `else`
1166-/// arm of [`decode_rect4_16_intrabc`] is the 4:2:0 PAIR geometry. It is
1167-/// still LIVE at ss (1, 1) -- a 1:4 strip's chroma lies inside its
1168-/// 4:2:0 pair there -- so the arm is not deleted; it is CLOSED at ss
1169-/// (1, 0), where it would run on a 4x16 VERT_4 strip whose chroma plane
1170-/// block is BLOCK_INVALID, and where libaom's own
1171-/// `is_chroma_reference` (av1_common_int.h:1454, `|| !subsampling_y`)
1172-/// makes every strip its own chroma reference anyway (the `own422` arm
1173-/// handles that). The proof: the sole caller `decode_rect4_16_strip` is
1174-/// reached only via the two 16x16-level 1:4 arms, each under
1175-/// `refuse_invalid_subsize((16, 16), part16)` -- at ss (1, 0) that guard
1176-/// refuses `partition_subsize_dims((16, 16), PARTITION_VERT_4) == (4, 16)`
1177-/// (in `PLANE_BLOCK_INVALID_422`), and the surviving HORZ_4 16x4 strip
1178-/// takes `own422`. This test re-derives that chain from the file so it
1179-/// REDS when any half stops holding: deleting the in-arm assertion, a
1180-/// caller moving under a level whose guard does not refuse (4, 16) at
1181-/// ss (1, 0), or the `(pw / 2, ph / 2)` form drifting. 4:2:0 and 4:4:4
1182-/// behaviour are unchanged: the gate runs only the file scan and the
1183-/// closed cell's arithmetic, no decode.
1184-#[test]
1185-fn decode_rect4_16_intrabc_else_arm_stays_closed_at_422() {
1186- let production = crate::test_source::module_production_source("decode");
1187- let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") {
1188- Some(i) => &production[..i],
1189- None => production,
1190- };
1191-
1192- // (a) The closure assertion must exist INSIDE the function, in the
1193- // `else` arm of the `(cw, ch)` select, naming the shape and the
1194- // subsampling. Deleting it -- or re-adding the bare halving without
1195- // it -- reds here.
1196- let fstart = decode_body
1197- .find("\nfn decode_rect4_16_intrabc(")
1198- .expect("decode_rect4_16_intrabc is gone -- this gate guards its else arm");
1199- let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
1200- .iter()
1201- .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i))
1202- .min()
1203- .unwrap_or(decode_body.len());
1204- let body = &decode_body[fstart..fend];
1205- let else_arm = body
1206- .find(" let (cw, ch) = if own_chroma {")
1207- .expect("the (cw, ch) select moved out of decode_rect4_16_intrabc");
1208- let closure = &body[else_arm..];
1209- assert!(
1210- closure.contains("assert!(") && closure.contains("ss_x(fctx) == 1 && ss_y(fctx) == 0"),
1211- "the decode_rect4_16_intrabc else arm's ss (1, 0) closure assertion is \
1212- GONE -- the 4:2:0 pair geometry is unreachable at ss (1, 0) only while \
1213- that assert (and the guards below) stand; re-add it"
1214- );
1215-
1216- // (b) The sole-caller chain, re-derived from the file: exactly one
1217- // call to `decode_rect4_16_intrabc(` outside its own definition, in
1218- // `decode_rect4_16_strip`; exactly two calls to
1219- // `decode_rect4_16_strip(` from the two 1:4 routes.
1220- let code_lines: String = decode_body
1221- .lines()
1222- .filter(|l| !l.trim_start().starts_with("//"))
1223- .collect::<Vec<_>>()
1224- .join("\n");
1225- let count_calls = |name: &str| -> usize {
1226- code_lines.matches(&format!("{name}(")).count()
1227- - usize::from(code_lines.contains(&format!("fn {name}(")))
1228- };
1229- assert_eq!(
1230- count_calls("decode_rect4_16_intrabc"),
1231- 1,
1232- "decode_rect4_16_intrabc gained a caller -- re-derive whether the new route \
1233- sits under a guard that refuses (4, 16) at ss (1, 0) before this gate \
1234- stays green"
1235- );
1236- assert_eq!(
1237- count_calls("decode_rect4_16_strip"),
1238- 2,
1239- "decode_rect4_16_strip's caller set moved -- both routes must be \
1240- 16x16-level 1:4 arms under a (16, 16) guard that refuses (4, 16) at \
1241- ss (1, 0)"
1242- );
1243-
1244- // (c) Both routes sit under a `refuse_invalid_subsize((16, 16), ...)`:
1245- // the key-frame arm's guard ordered above the arm test, the inter
1246- // arm's guard in the inter decoder above its own 1:4 test. Scoped to
1247- // the enclosing function so the other decoder's guard cannot stand in
1248- // (the r2 class this file already fixed once).
1249- let fn_scope = |at: usize| -> std::ops::Range<usize> {
1250- let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
1251- .iter()
1252- .filter_map(|pat| decode_body[..at].rfind(pat))
1253- .max()
1254- .unwrap_or(0);
1255- let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "]
1256- .iter()
1257- .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i))
1258- .min()
1259- .unwrap_or(decode_body.len());
1260- head..tail
1261- };
1262- let kf_test = decode_body
1263- .find("if part16 == PARTITION_HORZ_4")
1264- .expect("the key-frame 16-level 1:4 arm test is gone");
1265- let kf_scope = fn_scope(kf_test);
1266- let kf_guard = decode_body[kf_scope.clone()]
1267- .find("refuse_invalid_subsize((16, 16)")
1268- .map(|i| kf_scope.start + i)
1269- .unwrap_or_else(|| {
1270- panic!(
1271- "the key-frame 16-level 1:4 arm has NO \
1272- refuse_invalid_subsize((16, 16)) above it in its own \
1273- function -- the VERT_4 (4, 16) refusal that closed \
1274- decode_rect4_16_intrabc's else arm at ss (1, 0) is gone"
1275- )
1276- });
1277- assert!(
1278- kf_guard < kf_test,
1279- "the key-frame (16, 16) guard sits below the 1:4 arm test -- it can never \
1280- observe the VERT_4 symbol that must be refused before \
1281- decode_rect4_16_intrabc's else arm can run at ss (1, 0)"
1282- );
1283- let inter_writer = decode_body
1284- .find("let horz = part16 == PARTITION_HORZ_4;")
1285- .expect("the inter 16-level 1:4 arm is gone");
1286- let inter_scope = fn_scope(inter_writer);
1287- let inter_guard = decode_body[inter_scope.clone()]
1288- .find("refuse_invalid_subsize((16, 16)")
1289- .map(|i| inter_scope.start + i)
1290- .unwrap_or_else(|| {
1291- panic!(
1292- "the inter-frame 16-level 1:4 arm has NO \
1293- refuse_invalid_subsize((16, 16)) in its function -- the VERT_4 \
1294- (4, 16) refusal that closed decode_rect4_16_intrabc's else arm \
1295- at ss (1, 0) is gone"
1296- )
1297- });
1298- assert!(
1299- inter_guard < inter_writer,
1300- "the inter (16, 16) guard sits below the 1:4 arm test -- it can never \
1301- observe the VERT_4 symbol that must be refused before \
1302- decode_rect4_16_intrabc's else arm can run at ss (1, 0)"
1303- );
1304-
1305- // (d) The shape/subsampling cells the closure is written against,
1306- // re-executed: (4, 16) must still be BLOCK_INVALID at ss (1, 0) while
1307- // (16, 4) stays codable there, and at ss (1, 1) BOTH are codable --
1308- // which is what keeps the arm live at 4:2:0 and the assertion inert
1309- // there. At ss (0, 0) everything is codable, so `own444` (and the
1310- // assertion) never see the else arm.
1311- assert!(
1312- !chroma_plane_block_codable(4, 16, 1, 0),
1313- "(4, 16) left PLANE_BLOCK_INVALID_422 -- the else arm is now REACHABLE at \
1314- ss (1, 0) with the halved pair geometry, which is a real defect, not a \
1315- closure: re-derive the whole chain, then fix the halving instead of the \
1316- assert"
1317- );
1318- assert!(
1319- chroma_plane_block_codable(16, 4, 1, 0),
1320- "(16, 4) became BLOCK_INVALID at ss (1, 0) -- the surviving HORZ_4 strip \
1321- takes own422, and the closure assert would fire on a legal shape; \
1322- re-derive"
1323- );
1324- assert!(
1325- chroma_plane_block_codable(4, 16, 1, 1) && chroma_plane_block_codable(16, 4, 1, 1),
1326- "a 1:4 strip's plane block moved at ss (1, 1) -- the else arm is LIVE there \
1327- and the pair geometry is what decodes it; the assertion must stay inert at \
1328- 4:2:0"
1329- );
1330- assert!(
1331- chroma_plane_block_codable(4, 16, 0, 0) && chroma_plane_block_codable(16, 4, 0, 0),
1332- "a 1:4 strip's plane block became invalid at ss (0, 0) -- the assertion sits \
1333- after the own444 arm and must never fire at 4:4:4; re-derive"
1334- );
1335-}
1336-
1337131 /// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's
1338132 /// `tx_type` from the luma leaf covering the unit's OWN quadrant, and
1339133 /// reports "no leaf there" as `None` so the caller can fall back to the
@@ -2415,84 +1209,6 @@ fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() {
24151209 );
24161210 }
24171211
2418-/// lane-t900 r27, structural audit for "an OBMC neighbour whose switchable
2419-/// interp filter was never recorded": the `[3, 3]` sentinel is only ever
2420-/// PUBLISHED for a cell an OBMC blend cannot pick up.
2421-///
2422-/// `Neighbours::record_inter_rect_mi` is the single writer of
2423-/// `above_filter`/`left_filter` (every other recorder routes through it),
2424-/// so the whole domain of published values is its call sites' 7th
2425-/// argument. Two publications are safe: an INTRA cell (`is_inter = false`,
2426-/// skipped by `overlappable_above`/`overlappable_left`'s own `is_inter`
2427-/// gate) and a fixed-filter frame (`resolve_interp_filter` returns the
2428-/// sentinel when `interp_fixed` is `Some`, which `neighbour_filter`
2429-/// answers before ever looking at the symbols). What this scans for is the
2430-/// third case -- an INTER cell stamped with a literal sentinel, which is
2431-/// what the refusal actually fires on. Arguments are tokenised
2432-/// positionally, never `contains()`d.
2433-#[test]
2434-fn every_inter_record_publishes_an_obmc_readable_filter() {
2435- let src = crate::test_source::module_source("decode");
2436- let mut calls = 0usize;
2437- for (start, _) in src.match_indices("record_inter_rect_mi(") {
2438- // Skip the definition and the wrapper's own forwarding call.
2439- let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1);
2440- let head = &src[line_start..start];
2441- // The definition, the wrapper's own forwarding call, and this
2442- // test's own mentions of the name (doc comment, scan pattern,
2443- // assert message) are not publication sites.
2444- if head.contains("fn ") || head.contains("///") || head.ends_with('"') {
2445- continue;
2446- }
2447- let mut i = start + "record_inter_rect_mi(".len();
2448- let (mut depth, mut arg, mut args) = (0i32, String::new(), Vec::new());
2449- let bytes = src.as_bytes();
2450- while i < bytes.len() {
2451- let c = bytes[i] as char;
2452- match c {
2453- '(' | '[' => depth += 1,
2454- ')' | ']' if depth == 0 && c == ')' => break,
2455- ')' | ']' => depth -= 1,
2456- ',' if depth == 0 => {
2457- args.push(std::mem::take(&mut arg));
2458- i += 1;
2459- continue;
2460- }
2461- _ => {}
2462- }
2463- arg.push(c);
2464- i += 1;
2465- }
2466- if !arg.trim().is_empty() {
2467- args.push(arg);
2468- }
2469- assert_eq!(
2470- args.len(),
2471- 8,
2472- "record_inter_rect_mi gained an argument -- re-index this audit: {args:?}"
2473- );
2474- calls += 1;
2475- let (is_inter, filter) = (args[4].trim(), args[6].trim());
2476- if filter.starts_with('[') {
2477- assert_eq!(
2478- filter.replace(' ', ""),
2479- "[3,3]",
2480- "a literal filter other than the sentinel is published at call {calls}"
2481- );
2482- assert_eq!(
2483- is_inter, "false",
2484- "an INTER cell is stamped with the [3, 3] sentinel (call {calls}): an OBMC \
2485- blend picking it up refuses by name. Publish the block's own resolved \
2486- switchable symbols instead."
2487- );
2488- }
2489- }
2490- assert!(
2491- calls >= 6,
2492- "the audit found only {calls} publication sites -- it is broken, not the decoder"
2493- );
2494-}
2495-
24961212 /// lane-t900 r27, negative gate for "a reference frame selected with no
24971213 /// picture at this frame's own ref_frame_idx slot for it": every
24981214 /// non-`LAST_FRAME` reference resolves through `ref_planes`, and an empty
@@ -2842,7 +1558,6 @@ fn a_skipped_block_decodes_to_pure_prediction() {
28421558 #[test]
28431559 fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
28441560 let fctx = &crate::decode::FrameCtx::new();
2845- reset_skipped_intrabc_chroma_arm_hits();
28461561 use crate::msac::SymbolEncoder;
28471562 let mut cdfs = Cdfs::new(q_ctx_of(40));
28481563 let mut enc = SymbolEncoder::new();
@@ -2883,10 +1598,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
28831598 true,
28841599 fctx,
28851600 );
2886- assert!(
2887- skipped_intrabc_chroma_arm_hits() >= 1,
2888- "the hand-written tile never reached the skipped-intrabc chroma-reference route"
2889- );
28901601 assert!(
28911602 fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(),
28921603 "the inherited chroma transform slot must be disarmed when its block's chroma \
@@ -2901,7 +1612,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
29011612 #[test]
29021613 fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
29031614 let fctx = &crate::decode::FrameCtx::new();
2904- reset_skipped_intrabc_chroma_arm_hits();
29051615 use crate::msac::SymbolEncoder;
29061616 let mut cdfs = Cdfs::new(q_ctx_of(40));
29071617 let mut enc = SymbolEncoder::new();
@@ -2934,10 +1644,6 @@ fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx(
29341644 true,
29351645 fctx,
29361646 );
2937- assert!(
2938- skipped_intrabc_chroma_arm_hits() >= 1,
2939- "the hand-written tile never reached the skipped-intrabc rect chroma-reference route"
2940- );
29411647 assert!(
29421648 fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(),
29431649 "the inherited chroma transform slot must be disarmed when its block's chroma \
@@ -3216,7 +1922,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {
32161922 }
32171923 let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
32181924 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3219- let before = filter_intra_hits();
32201925 let ours = decode_key_frame_tile_lr(
32211926 &encoded.tile,
32221927 encoded.mi_cols,
@@ -3235,12 +1940,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {
32351940 fctx,
32361941 )
32371942 .unwrap();
3238- let fired = filter_intra_hits() - before;
3239- assert!(
3240- fired > 0,
3241- "no block took filter intra -- the gate is blind to the feature"
3242- );
3243- eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks");
32441943 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
32451944 assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg");
32461945 assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg");
crates/ec-av1/src/encode/tests.rsmodified+0 -235
@@ -1130,241 +1130,6 @@
11301130 );
11311131 }
11321132
1133- /// lane-av1paletteuv: the census for `crate::tile::palette_uv_side`, the
1134- /// `(side / 2).max(4)` named in `lanes/av1subsizesweep.report.md` as a
1135- /// "4:2:2/4:4:0 palette map mis-sized" site.
1136- ///
1137- /// **What the site computes.** libaom reads the plane-1 colour-index map
1138- /// at `av1_get_block_dimensions(bsize, 1, xd)` (blockd.h:1512): per axis,
1139- /// `plane_block = block >> ss`, then `+2` when that came out under 4
1140- /// (the chroma sub-8x8 bump, blockd.h:1533-1541). For a SQUARE 4:2:0
1141- /// block both axes carry `ss = 1`, so both come to `side / 2` with the
1142- /// bump -- which is exactly `(side / 2).max(4)`. The value is right.
1143- ///
1144- /// **What it is not.** At 4:2:2 the correct map is `(side >> 1) x side`
1145- /// and at 4:4:4 it is `side x side` -- neither is square. So the value is
1146- /// 4:2:0-only BY CONSTRUCTION, and this gate is what keeps it that way:
1147- /// if an encoder that can emit another chroma shape ever appears, this
1148- /// reds rather than the writer silently writing a half-height map.
1149- ///
1150- /// The three arms are (1) the value matches libaom's own per-axis
1151- /// formula at 4:2:0 over every side the palette syntax admits, (2) no
1152- /// reachable writer path can be handed another chroma shape, (3) a real
1153- /// encode really fires chroma palettes, so arm 1 is not arithmetic on a
1154- /// function nothing calls (class `gate-blind-to-feature`).
1155- #[test]
1156- fn the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it() {
1157- const NAME: &str =
1158- "the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it";
1159- let encode_src = crate::test_source::module_source("encode");
1160-
1161- // ---- arm 1: the value, against libaom's formula --------------------
1162- // blockd.h:1530-1541, transcribed. A plane_block under 4 gains 2.
1163- let libaom_plane1 = |block: usize, ss: usize| {
1164- let plane_block = block >> ss;
1165- plane_block + 2 * usize::from(plane_block < 4)
1166- };
1167- let mut admitted = 0usize;
1168- for side in 4usize..=64 {
1169- // `palette_bsize_ctx`'s own domain: both sides <= 64 and
1170- // bw * bh >= 64 (`av1_allow_palette`). A side outside it codes no
1171- // palette syntax at all, so its map size is unobservable.
1172- if side > 64 || side * side < 64 {
1173- continue;
1174- }
1175- admitted += 1;
1176- let want_x = libaom_plane1(side, 1);
1177- let want_y = libaom_plane1(side, 1);
1178- assert_eq!(want_x, want_y, "{NAME}: 4:2:0 arms the libaom formula");
1179- assert_eq!(
1180- crate::tile::palette_uv_side(side),
1181- want_x,
1182- "{NAME}: side {side} -- palette_uv_side disagrees with libaom's plane-1 block"
1183- );
1184- }
1185- assert_eq!(
1186- admitted, 57,
1187- "{NAME}: the sweep admitted {admitted} sides, expected 57 (every integer 8..=64 -- \
1188- `palette_bsize_ctx`'s whole square domain, not just the powers of two a real block \
1189- takes) -- it must cover that domain, or it is not measuring it"
1190- );
1191-
1192- // Why `.max(4)` cannot fire, stated as a measurement rather than left
1193- // for a reader to assume: `palette_bsize_ctx` refuses `bw * bh < 64`,
1194- // so the smallest admitted square side is 8, whose halved plane block
1195- // is already 4. The floor's only reachable input would be a side
1196- // under 8, and libaom's own chroma sub-8x8 bump (+2) is likewise
1197- // unreachable there. Dropping the floor is therefore NOT a witness
1198- // mutation for this gate -- the mutation that bites is dropping the
1199- // halving (measured, see the lane report) -- and this arm says why,
1200- // so nobody later mistakes a green floor mutation for coverage.
1201- for side in [8usize, 16, 32, 64] {
1202- assert!(
1203- side / 2 >= 4 && libaom_plane1(side, 1) == side / 2,
1204- "{NAME}: side {side} -- the admitted domain moved, so `.max(4)` may now be \
1205- reachable and the floor needs a witness mutation of its own"
1206- );
1207- }
1208-
1209- // The claim the gate rests on, stated as arithmetic so a future
1210- // reader cannot mistake "correct" for "correct at any shape": at
1211- // these shapes the per-axis answer is NOT this square.
1212- for side in [8usize, 16, 32, 64] {
1213- let square = crate::tile::palette_uv_side(side);
1214- let want_422 = (libaom_plane1(side, 1), libaom_plane1(side, 0));
1215- let want_444 = (libaom_plane1(side, 0), libaom_plane1(side, 0));
1216- assert_ne!(
1217- (square, square),
1218- want_422,
1219- "{NAME}: side {side} -- a square map IS the 4:2:2 map, so this gate's premise \
1220- (the site is 4:2:0-only) is wrong"
1221- );
1222- assert_ne!(
1223- (square, square),
1224- want_444,
1225- "{NAME}: side {side} -- a square map IS the 4:4:4 map"
1226- );
1227- }
1228-
1229- // ---- arm 2: nothing can hand the writer another shape --------------
1230- // (a) Every non-test `ColorConfig` literal in the encoder names
1231- // subsampling (1, 1). These are the two constructors the whole
1232- // encoder reaches its colour config through; the test-module copies
1233- // are excluded by scanning only the pre-`mod tests` prefix. The cut
1234- // matches an inline `mod tests {` body only, so a `mod tests;` file
1235- // declaration does not truncate the production files after it.
1236- fn head(src: &str) -> &str {
1237- let cut = src.find("\nmod tests {").unwrap_or(src.len());
1238- &src[..cut]
1239- }
1240- for (label, src) in [
1241- ("encode.rs", head(crate::test_source::module_production_source("encode"))),
1242- ("encoder.rs", head(crate::test_source::module_production_source("encoder"))),
1243- ] {
1244- // Every `subsampling_*` the non-test encoder names, counted: a
1245- // `(0, y)` or `(1, 0)` here is a chroma shape
1246- // `palette_uv_side` cannot express. The one value allowed is 1
1247- // -- 4:2:0, the shape the square map is the right size for.
1248- let mut shapes: std::collections::BTreeSet<(usize, usize)> = Default::default();
1249- for (sx, _) in src.match_indices("subsampling_x:") {
1250- let rest = &src[sx + "subsampling_x:".len()..];
1251- let digits = |s: &str| {
1252- s.trim_start()
1253- .split(|c: char| !c.is_ascii_digit())
1254- .next()
1255- .and_then(|d| d.parse::<usize>().ok())
1256- .unwrap_or(usize::MAX)
1257- };
1258- let x = digits(rest);
1259- let y = rest
1260- .find("subsampling_y:")
1261- .map(|y| digits(&rest[y + "subsampling_y:".len()..]))
1262- .unwrap_or(usize::MAX);
1263- shapes.insert((x, y));
1264- }
1265- assert_eq!(
1266- shapes,
1267- std::collections::BTreeSet::from([(1usize, 1usize)]),
1268- "{NAME}: the non-test {label} names chroma shapes {shapes:?} -- any shape other \
1269- than 4:2:0 is one palette_uv_side's square map cannot express (at 4:2:2 the \
1270- map is (side >> 1) x side, at 4:4:4 side x side)"
1271- );
1272- }
1273-
1274- // (b) `key_frame_headers_colour` is the only PUBLIC entry that takes
1275- // a caller-chosen ColorConfig -- it is how a 4:2:2 or 4:4:4 header is
1276- // written at all -- so it is the one door a non-4:2:0 shape comes
1277- // through. It builds HEADERS only: no tile writer is reachable from
1278- // its body. (Its own doc says so; this measures it.)
1279- let headers_at = encode_src
1280- .find("pub fn key_frame_headers_colour(")
1281- .expect("key_frame_headers_colour is gone -- re-derive this arm's scan anchor");
1282- let body_end = encode_src[headers_at..]
1283- .find("\npub fn ")
1284- .map(|n| headers_at + n)
1285- .unwrap_or(encode_src.len());
1286- let headers_body = &encode_src[headers_at..body_end];
1287- for writer in [
1288- "write_palette_syntax",
1289- "write_color_index_map",
1290- "encode_key_frame_inner",
1291- "tile::",
1292- ] {
1293- assert!(
1294- !headers_body.contains(writer),
1295- "{NAME}: key_frame_headers_colour now reaches {writer} -- a caller can pair a \
1296- 4:2:2/4:4:4 header with a tile, and palette_uv_side writes a square map into \
1297- the per-axis slot libaom reads as (side >> ss_x) x (side >> ss_y)"
1298- );
1299- }
1300-
1301- // (c) Every tile-producing entry point goes through
1302- // `encode_key_frame_inner`, whose five non-test call sites all pass
1303- // one of the two 4:2:0 constructors above. Counted over the
1304- // non-test source only, so a new road is a red rather than a line
1305- // somebody has to notice.
1306- let inner_calls = head(crate::test_source::module_production_source("encode")).matches("encode_key_frame_inner(").count()
1307- + head(crate::test_source::module_production_source("encoder")).matches("encode_key_frame_inner(").count()
1308- - 1; // the definition itself
1309- assert_eq!(
1310- inner_calls, 5,
1311- "{NAME}: encode_key_frame_inner has {inner_calls} non-test call sites, expected 5 -- \
1312- a new one must pass a colour config this gate has read"
1313- );
1314-
1315- // (d) The picture itself is 4:2:0-shaped at the door, so a 4:2:2 or
1316- // 4:4:4 frame cannot even be handed to an encode entry. Measured by
1317- // calling `check`, not by reading it.
1318- for (label, divisor) in [("4:2:2", 2usize), ("4:4:4", 1)] {
1319- let p = Picture {
1320- width: 64,
1321- height: 64,
1322- y: vec![0; 64 * 64],
1323- u: vec![0; 64 * 64 / divisor],
1324- v: vec![0; 64 * 64 / divisor],
1325- };
1326- assert!(
1327- p.check().is_err(),
1328- "{NAME}: Picture::check accepted a {label}-shaped picture -- if the encoder can be \
1329- fed one, palette_uv_side's square map is wrong by construction"
1330- );
1331- }
1332-
1333- // ---- arm 3: the site really fires ---------------------------------
1334- // Without this, arms 1 and 2 are arithmetic and a source scan over a
1335- // function no encode reaches (class `gate-blind-to-feature`).
1336- //
1337- // The fire count is the DECODER's thread-local one, not the writer's
1338- // process-global `tile::take_palette_uv_hits`: that one is a
1339- // swap-to-zero, so a parallel sibling test's encode steals this test's
1340- // count (measured: it read `[0; 9]` under `cargo test palette`, and
1341- // passed alone). Round-tripping the stream instead also proves the
1342- // stronger half -- the reader took the map at the extent the WRITER
1343- // sized, which is what makes the square value right rather than merely
1344- // unchallenged.
1345- let _knobs = crate::speed::knob_read();
1346- let fctx = &crate::decode::FrameCtx::for_encoder();
1347- let before = crate::decode::palette_uv_hits();
1348- let encoded = encode_key_frame_with_ctx(&screen_card(192, 96), 100, 0.5, fctx).unwrap();
1349- let decoded = crate::stream::decode_stream(&encoded.stream)
1350- .unwrap_or_else(|e| panic!("{NAME}: our own stream refused: {e}"));
1351- let fired = crate::decode::palette_uv_hits() - before;
1352- assert!(
1353- fired > 0,
1354- "{NAME}: no block took a chroma palette -- palette_uv_side was never exercised, so \
1355- this gate measures nothing"
1356- );
1357- assert_eq!(
1358- decoded[0].u, encoded.reconstruction.u,
1359- "{NAME}: the decoder did not read the chroma map at the extent the writer sized it"
1360- );
1361- assert_eq!(
1362- decoded[0].v, encoded.reconstruction.v,
1363- "{NAME}: the decoder did not read the chroma map at the extent the writer sized it"
1364- );
1365- eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped");
1366- }
1367-
13681133 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
13691134 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
13701135 /// take a block vector (fire count + DV histogram, class
crates/ec-av1/src/lib.rsmodified+0 -2
@@ -55,8 +55,6 @@ pub mod sequence;
5555 pub mod speed;
5656 pub mod stream;
5757 mod superres;
58-#[cfg(test)]
59-mod test_source;
6058 pub mod tile;
6159 mod timeline;
6260 pub mod transform;
crates/ec-av1/src/test_source.rsdeleted+0 -103
@@ -1,103 +0,0 @@
1-#![cfg(test)]
2-//! Test-only access to a crate module's SOURCE TEXT.
3-//!
4-//! The source-scanning gates used to `include_str!("decode.rs")`, which names
5-//! one file. Once a module is split into a directory (`decode/mod.rs` plus its
6-//! children) that include stops compiling, and every gate pinning it goes stale
7-//! on the next move. These helpers read the module's files at test run time
8-//! instead: `src/<name>.rs` when it exists, then every `*.rs` under
9-//! `src/<name>/` recursively, concatenated in sorted path order. A file added to
10-//! that directory is therefore scanned without touching any gate.
11-//!
12-//! [`module_production_source`] is the same text minus the test-only files
13-//! (`tests.rs` and `*_tests.rs`), for gates that must not count their own test
14-//! fixtures. An inline `mod tests { .. }` in a single file is not removed by
15-//! that function; a gate that needs the production prefix cuts it itself.
16-
17-use std::collections::BTreeMap;
18-use std::path::{Path, PathBuf};
19-use std::sync::{Mutex, OnceLock};
20-
21-type Cache = Mutex<BTreeMap<(String, bool), &'static str>>;
22-static CACHE: OnceLock<Cache> = OnceLock::new();
23-
24-/// The whole source text of module `name`: `src/<name>.rs` and every `*.rs`
25-/// under `src/<name>/`, in sorted path order.
26-pub fn module_source(name: &str) -> &'static str {
27- cached(name, false)
28-}
29-
30-/// [`module_source`] without the test-only files (`tests.rs`, `*_tests.rs`).
31-pub fn module_production_source(name: &str) -> &'static str {
32- cached(name, true)
33-}
34-
35-/// Each module is read once per test process. The text is leaked, which is
36-/// bounded by the handful of modules the gates name and is test-only.
37-fn cached(name: &str, production_only: bool) -> &'static str {
38- let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new()));
39- let mut map = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
40- let key = (name.to_string(), production_only);
41- if let Some(&text) = map.get(&key) {
42- return text;
43- }
44- let text: &'static str = Box::leak(read_module(name, production_only).into_boxed_str());
45- map.insert(key, text);
46- text
47-}
48-
49-fn read_module(name: &str, production_only: bool) -> String {
50- assert!(
51- !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
52- "{name:?} is not a module name"
53- );
54- let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
55- let mut files: Vec<PathBuf> = Vec::new();
56- let single = src.join(format!("{name}.rs"));
57- if single.is_file() {
58- files.push(single);
59- }
60- let dir = src.join(name);
61- if dir.is_dir() {
62- collect_rs(&dir, &mut files);
63- }
64- assert!(
65- !files.is_empty(),
66- "module {name} has neither src/{name}.rs nor src/{name}/"
67- );
68- files.sort();
69- // A split moved some top-level fns to `pub(super) fn` so sibling modules can call them. The
70- // scanners match header text (`\nfn name(`); normalize only that visibility so they see the
71- // same headers as before the split. Bodies and assertions are unchanged.
72- let mut text = String::new();
73- for path in files {
74- if production_only && is_test_file(&path) {
75- continue;
76- }
77- let body = std::fs::read_to_string(&path)
78- .unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
79- text.push_str(&body);
80- if !body.ends_with('\n') {
81- text.push('\n');
82- }
83- }
84- text.replace("\npub(super) fn ", "\nfn ").replace("\n pub(super) fn ", "\n fn ")
85-}
86-
87-fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
88- let entries =
89- std::fs::read_dir(dir).unwrap_or_else(|e| panic!("reading {}: {e}", dir.display()));
90- for entry in entries {
91- let path = entry.expect("reading a directory entry").path();
92- if path.is_dir() {
93- collect_rs(&path, out);
94- } else if path.extension().is_some_and(|ext| ext == "rs") {
95- out.push(path);
96- }
97- }
98-}
99-
100-fn is_test_file(path: &Path) -> bool {
101- let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
102- stem == "tests" || stem.ends_with("_tests")
103-}