forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tests.rs3854 lines, 163.8 KiBHistoryRawDownload
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]
38fn 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
327/// lane-av1unwritten: the port is a TRANSCRIPTION, and this is the artefact
328/// that makes it checkable. It re-writes `av1_ss_size_lookup`'s 22 rows
329/// (`common_data.c:17-41`) literally -- every shape, every subsampling
330/// pair, the real BLOCK_INVALID markers -- and asserts
331/// [`chroma_plane_block_codable`] agrees cell for cell. A predicate that
332/// hardcodes the wrong cell (this lane's first version marked BLOCK_16X4 at
333/// 4:2:2 invalid; the table says `BLOCK_8X4`) reds here, not in a corpus
334/// that happens not to carry the shape.
335#[test]
336fn chroma_plane_block_codable_matches_the_libaom_table() {
337 // (width, height, [ss_x=0][ss_y=0], [0][1], [1][0], [1][1]); `None` is
338 // BLOCK_INVALID.
339 const I: Option<(usize, usize)> = None;
340 let table: &[(usize, usize, [Option<(usize, usize)>; 4])] = &[
341 (
342 4,
343 4,
344 [Some((4, 4)), Some((4, 4)), Some((4, 4)), Some((4, 4))],
345 ),
346 (4, 8, [Some((4, 8)), Some((4, 4)), I, Some((4, 4))]),
347 (8, 4, [Some((8, 4)), I, Some((4, 4)), Some((4, 4))]),
348 (
349 8,
350 8,
351 [Some((8, 8)), Some((8, 4)), Some((4, 8)), Some((4, 4))],
352 ),
353 (8, 16, [Some((8, 16)), Some((8, 8)), I, Some((4, 8))]),
354 (16, 8, [Some((16, 8)), I, Some((8, 8)), Some((4, 4))]),
355 (
356 16,
357 16,
358 [Some((16, 16)), Some((8, 16)), Some((8, 8)), Some((4, 8))],
359 ),
360 (16, 32, [Some((16, 32)), Some((16, 16)), I, Some((8, 16))]),
361 (32, 16, [Some((32, 16)), I, Some((16, 16)), Some((16, 8))]),
362 (
363 32,
364 32,
365 [
366 Some((32, 32)),
367 Some((16, 32)),
368 Some((16, 16)),
369 Some((16, 8)),
370 ],
371 ),
372 (32, 64, [Some((32, 64)), Some((32, 32)), I, Some((16, 32))]),
373 (64, 32, [Some((64, 32)), I, Some((32, 32)), Some((32, 16))]),
374 (
375 64,
376 64,
377 [
378 Some((64, 64)),
379 Some((32, 64)),
380 Some((32, 32)),
381 Some((32, 16)),
382 ],
383 ),
384 (
385 64,
386 128,
387 [Some((64, 128)), Some((64, 64)), I, Some((32, 64))],
388 ),
389 (
390 128,
391 64,
392 [Some((128, 64)), I, Some((64, 64)), Some((64, 32))],
393 ),
394 (
395 128,
396 128,
397 [
398 Some((128, 128)),
399 Some((64, 128)),
400 Some((64, 64)),
401 Some((64, 32)),
402 ],
403 ),
404 (4, 16, [Some((4, 16)), Some((4, 8)), I, Some((4, 8))]),
405 (16, 4, [Some((16, 4)), I, Some((8, 4)), Some((8, 4))]),
406 (8, 32, [Some((8, 32)), Some((8, 16)), I, Some((4, 16))]),
407 (32, 8, [Some((32, 8)), I, Some((16, 8)), Some((16, 4))]),
408 (16, 64, [Some((16, 64)), Some((16, 32)), I, Some((8, 32))]),
409 (64, 16, [Some((64, 16)), I, Some((32, 16)), Some((32, 8))]),
410 (
411 128,
412 256,
413 [
414 Some((128, 256)),
415 Some((64, 256)),
416 Some((64, 128)),
417 Some((64, 64)),
418 ],
419 ),
420 (
421 256,
422 128,
423 [
424 Some((256, 128)),
425 Some((128, 256)),
426 Some((128, 64)),
427 Some((128, 64)),
428 ],
429 ),
430 ];
431 for &(w, h, cells) in table {
432 for sx in 0..2usize {
433 for sy in 0..2usize {
434 let want_codable = cells[sx * 2 + sy].is_some();
435 assert_eq!(
436 chroma_plane_block_codable(w, h, sx, sy),
437 want_codable,
438 "av1_ss_size_lookup[{w}x{h}][{sx}][{sy}] is {:?} in libaom \
439 (common_data.c) but our predicate says the opposite",
440 cells[sx * 2 + sy]
441 );
442 }
443 }
444 }
445 // The two cells an earlier, hand-picked predicate got wrong: both are
446 // LEGAL at 4:2:2, and libaom's own encoder emits the 16x4 one.
447 assert!(
448 chroma_plane_block_codable(16, 4, 1, 0),
449 "16x4 at 4:2:2 is BLOCK_8X4"
450 );
451 assert!(
452 !chroma_plane_block_codable(32, 8, 0, 1),
453 "32x8 at 4:4:0 is BLOCK_INVALID"
454 );
455}
456
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]
491fn 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]
1185fn 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
1337/// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's
1338/// `tx_type` from the luma leaf covering the unit's OWN quadrant, and
1339/// reports "no leaf there" as `None` so the caller can fall back to the
1340/// block-level type. Both halves are load-bearing: the 128 mu-chunk tail,
1341/// the 4:4:4 four-unit arms and `read_inter_rect_chroma` all read the
1342/// `None` arm as "this block coded a single luma unit".
1343#[test]
1344fn covering_leaf_tx_type_picks_the_leaf_under_the_unit_or_reports_none() {
1345 use TxType::*;
1346 // A 32x64 strip's five-leaf tree, in decode order: one 32x32 leaf
1347 // over mi rows 0..8, then 16x16 leaves. (row, col) are MI relative
1348 // to the block, (tw, th) are PIXELS, MI == 4.
1349 let leaves = [
1350 (0usize, 0usize, 32usize, 32usize, Idtx),
1351 (8, 0, 16, 16, VDct),
1352 (8, 4, 16, 16, DctDct),
1353 (12, 0, 16, 16, HDct),
1354 (12, 4, 16, 16, VDct),
1355 ];
1356 // The TOP chroma unit (its own mi cell (0,0)) sits over the 32x32
1357 // leaf; the LOWER one (mi (8,0)) over the first 16x16 leaf. The
1358 // block-level type is the first leaf's, so only the second read
1359 // differs -- exactly the condition the gate's DIFF counter counts.
1360 assert_eq!(covering_leaf_tx_type(&leaves, (0, 0)), Some(Idtx));
1361 assert_eq!(covering_leaf_tx_type(&leaves, (8, 0)), Some(VDct));
1362 // Interior cells resolve the same leaf as the cell's top-left: the
1363 // lookup is a rectangle containment test, not a raster position.
1364 assert_eq!(covering_leaf_tx_type(&leaves, (11, 3)), Some(VDct));
1365 assert_eq!(covering_leaf_tx_type(&leaves, (12, 4)), Some(VDct));
1366 // The bottom-right corner of the last leaf, and the mi cell just
1367 // past the block's own extent, must not fall into a neighbour.
1368 assert_eq!(covering_leaf_tx_type(&leaves, (15, 7)), Some(VDct));
1369 assert_eq!(covering_leaf_tx_type(&leaves, (16, 0)), None);
1370 assert_eq!(covering_leaf_tx_type(&leaves, (0, 8)), None);
1371 // A block with no var-tx tree (one coded luma unit) has no leaves at
1372 // all: the caller's block-level fallback is the answer, and the
1373 // resolver must say so rather than guess.
1374 assert_eq!(covering_leaf_tx_type(&[], (0, 0)), None);
1375}
1376
1377/// lane-av1422warp r33: the OBMC pair-merge snap must move the READ to
1378/// libaom's position, not the reported offset.
1379///
1380/// libaom `obmc.h:44-46`:
1381/// ```c
1382/// if (mi_step == 1) {
1383/// above_mi_col &= ~1; // snap the INDEX, unconditional
1384/// above_mi = prev_row_mi + above_mi_col + 1; // read at snap + 1
1385/// mi_step = 2;
1386/// }
1387/// ```
1388/// and the relative offset handed to
1389/// `av1_setup_build_prediction_by_above_pred` is
1390/// `above_mi_col - mi_col` **after** the snap, which is `-1` at an odd
1391/// `mi_col`. An earlier fix clamped the snapped INDEX to `mi_col` to
1392/// stop that subtraction underflowing, which silenced the underflow and
1393/// in exchange read the neighbour one column RIGHT of libaom's and then
1394/// stepped past the block's own right edge.
1395///
1396/// The grid here carries DISTINGUISHABLE neighbours at the pair's even
1397/// half, its odd half, and the column to the right of the pair, so the
1398/// test fails if the walk reads any position but the odd half. It is the
1399/// snapped READ this pins -- and no stream in the corpus exercises it
1400/// (a1.obu's 1338 traced OBMC neighbours are byte-identical before and
1401/// after the fix, because its 4-wide pair never starts on an odd edge),
1402/// so nothing else covers this branch.
1403#[test]
1404fn the_obmc_pair_merge_snap_reads_libaoms_neighbour_not_one_to_the_right() {
1405 const NAME: &str = "the_obmc_pair_merge_snap_reads_libaoms_neighbour_not_one_to_the_right";
1406 // `ref_frame` 1 == LAST_FRAME, which is what `is_inter` consumers
1407 // expect; the MV makes each cell individually identifiable.
1408 let cell = |mv: (i16, i16), size: u8| MiInfo {
1409 is_inter: true,
1410 ref_frame: 1,
1411 ref_frame1: 0,
1412 mv,
1413 mv1: (0, 0),
1414 is_new_mv: true,
1415 size,
1416 size_h: size,
1417 is_global_mv0: false,
1418 is_global_mv1: false,
1419 };
1420 const EVEN: (i16, i16) = (10, 10);
1421 const ODD: (i16, i16) = (20, 20);
1422 const RIGHT: (i16, i16) = (30, 30);
1423
1424 // --- the above walk, at an ODD `mi_col` ---
1425 let mut grid = crate::mvstack::MiGrid::new(16, 16);
1426 // The block under test sits at mi_col 5; the neighbour row is 4.
1427 // A 4-wide inter cell at the ODD half (5) is what forces
1428 // `mi_step == 1` and therefore the pair merge.
1429 grid.set(4, 4, cell(EVEN, 1));
1430 grid.set(4, 5, cell(ODD, 1));
1431 grid.set(4, 6, cell(RIGHT, 4)); // one column RIGHT of the pair
1432 // `bw4 == 2` so `AOMMIN(xd->width, mi_step)` is the pair's own 2
1433 // rather than clipped to a 1-wide block's 1.
1434 let nb = overlappable_above(&grid, 5, 5, 2, 16, 4);
1435 assert!(
1436 !nb.is_empty(),
1437 "{NAME}: the above walk found no neighbour at all"
1438 );
1439 let (off4, span4, info, src4) = nb[0];
1440 assert_eq!(
1441 info.mv, ODD,
1442 "{NAME}: the above pair merge read the wrong neighbour -- libaom \
1443 snaps the column and reads snap+1, which is the ODD half"
1444 );
1445 assert_ne!(
1446 info.mv, RIGHT,
1447 "{NAME}: the clamp moved the snapped index onto mi_col, so the \
1448 walk read one column RIGHT of libaom"
1449 );
1450 assert_eq!(src4, 0, "{NAME}: the read column's relative offset");
1451 assert_eq!(span4, 2, "{NAME}: the pair steps over BOTH halves");
1452 // libaom's `above_mi_col - mi_col` is -1 here; this tuple is
1453 // `usize`, so the reported offset saturates to 0 rather than
1454 // wrapping to `usize::MAX`. The snap is what the read depends on.
1455 assert_eq!(
1456 off4, 0,
1457 "{NAME}: the reported offset must saturate, not wrap"
1458 );
1459
1460 // --- the left walk, at an ODD `mi_row`: the same shape ---
1461 let mut grid = crate::mvstack::MiGrid::new(16, 16);
1462 grid.set(4, 4, cell(EVEN, 1));
1463 grid.set(5, 4, cell(ODD, 1));
1464 grid.set(6, 4, cell(RIGHT, 4));
1465 let nb = overlappable_left(&grid, 5, 5, 2, 16, 4);
1466 assert!(
1467 !nb.is_empty(),
1468 "{NAME}: the left walk found no neighbour at all"
1469 );
1470 let (off4, span4, info, src4) = nb[0];
1471 assert_eq!(
1472 info.mv, ODD,
1473 "{NAME}: the left pair merge read the wrong neighbour -- libaom \
1474 snaps the row and reads snap+1, which is the ODD half"
1475 );
1476 assert_ne!(
1477 info.mv, RIGHT,
1478 "{NAME}: the clamp moved the snapped row onto mi_row, so the walk \
1479 read one row BELOW libaom"
1480 );
1481 assert_eq!(src4, 0, "{NAME}: the read row's relative offset");
1482 assert_eq!(span4, 2, "{NAME}: the pair steps over BOTH halves");
1483 assert_eq!(
1484 off4, 0,
1485 "{NAME}: the reported offset must saturate, not wrap"
1486 );
1487}
1488
1489/// lane-twostage: the reference bank these gates decode against --
1490/// `LAST_FRAME` alone, already in hand (`ref_frame` index 1).
1491fn last_only(reference: &Picture) -> RefPix<'_> {
1492 let mut refs: [Option<&Picture>; 8] = [None; 8];
1493 refs[1] = Some(reference);
1494 RefPix::ready(refs)
1495}
1496
1497/// lane-av1422stripwrite: the reference chroma shape is read back off the
1498/// stored plane's own sample count, so the counts the PRODUCER writes
1499/// (`round_ss` crops, `decode.rs:25806`) must route back to the shape
1500/// they came from. A floor half-width here passes every even-width case
1501/// -- the pinned fixture's 256-wide frame included -- and silently drops
1502/// every odd-width 4:2:2 reference into the 4:2:0 arm, which is the
1503/// exact defect this lane fixed, one dimension over. So the table below
1504/// is driven off `round_ss`, not off hand-written numbers, and sweeps
1505/// odd and even widths.
1506///
1507/// lane-av1odd440: the 4:2:0 arm's expectation is the PRODUCER's crop,
1508/// `round_ss(w, 1) x round_ss(h, 1)`, not the `(w / 2, h / 2)` floor it
1509/// used to name -- the floor under-declares every odd-dimension 4:2:0
1510/// reference, which is the shape the pinned `420_odd65x65_key.obu` cell
1511/// finally makes reachable (see [`ref_chroma_shape`]). For every EVEN
1512/// size the two spellings are the same number, so the arms that were
1513/// already correct are unchanged by the edit.
1514#[test]
1515fn a_reference_chroma_sample_count_routes_back_to_its_own_format() {
1516 for w in [2usize, 3, 4, 5, 8, 9, 16, 17, 64, 65, 128, 129] {
1517 for h in [2usize, 3, 4, 5, 8, 9, 64, 65, 144, 145] {
1518 let cases = [
1519 ("4:4:4", round_ss(w, 0) * round_ss(h, 0), (w, h)),
1520 (
1521 "4:2:2",
1522 round_ss(w, 1) * round_ss(h, 0),
1523 (round_ss(w, 1), h),
1524 ),
1525 (
1526 "4:2:0",
1527 round_ss(w, 1) * round_ss(h, 1),
1528 (round_ss(w, 1), round_ss(h, 1)),
1529 ),
1530 ];
1531 for (name, len, want) in cases {
1532 assert_eq!(
1533 ref_chroma_shape(len, w, h),
1534 want,
1535 "{name} reference of {w}x{h} (chroma {len} samples) \
1536 must route back to its own shape"
1537 );
1538 }
1539 }
1540 }
1541}
1542
1543/// lane-av1422stripwrite: the whole point of the 4:2:2 arm is that it
1544/// claims the frame's FULL chroma height -- that is what stops every
1545/// chroma MC sourcing a row at or past the midpoint from being clamped
1546/// against `true_height`. Pinned on the t422 shape.
1547#[test]
1548fn a_422_reference_claims_the_full_chroma_height() {
1549 // 256x144 luma at ss (1, 0): chroma is 128 wide and 144 rows tall.
1550 let (cw, ch) = ref_chroma_shape(round_ss(256, 1) * 144, 256, 144);
1551 assert_eq!((cw, ch), (128, 144));
1552 // The bug's own signature: 72 rows claimed for 144 rows held.
1553 assert!(
1554 ch > 144 / 2,
1555 "a 4:2:2 reference must not claim half its rows"
1556 );
1557}
1558
1559/// [`last_only`] plus `GOLDEN_FRAME` (index 4 of the name-keyed array)
1560/// and `ALTREF_FRAME` (index 7, the frame two back, which the encoder
1561/// keeps in the slot the current frame refreshes): what a frame this
1562/// encoder writes needs, since its blocks may name any of the three.
1563fn last_golden_altref<'a>(
1564 last: &'a Picture,
1565 golden: &'a Picture,
1566 altref: Option<&'a Picture>,
1567) -> RefPix<'a> {
1568 let mut refs: [Option<&Picture>; 8] = [None; 8];
1569 refs[1] = Some(last);
1570 refs[4] = Some(golden);
1571 refs[7] = altref;
1572 RefPix::ready(refs)
1573}
1574
1575/// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and
1576/// a pre-resolved damping shift instead of a bounds-testing closure and a
1577/// per-tap `msb`. Both replacements must be value-identical to the spec
1578/// forms they came from, over the whole strength/damping/diff domain.
1579#[test]
1580fn cdef_gather_and_shifted_constrain_match_the_spec_forms() {
1581 for damping in 3..=9i32 {
1582 for threshold in 1..=64i32 {
1583 let shift = super::cdef_constrain_shift(threshold, damping);
1584 for diff in -300..=300i32 {
1585 assert_eq!(
1586 super::cdef_constrain(diff, threshold, damping),
1587 super::cdef_constrain_shifted(diff, threshold, shift),
1588 "diff={diff} threshold={threshold} damping={damping}"
1589 );
1590 }
1591 }
1592 }
1593 // `cdef_gather`'s interior fast path and its bounds-testing slow path
1594 // must agree with the per-sample closure the filter used to call, at
1595 // every block position including the three that straddle the crop.
1596 let (stride, tw, th) = (24usize, 21usize, 19usize);
1597 let src: Vec<u16> = (0..stride * 24).map(|i| (i * 7 % 1024) as u16).collect();
1598 for &(ox, oy, bw, bh) in &[(0, 0, 8, 8), (8, 8, 8, 8), (16, 16, 8, 8), (4, 12, 4, 4)] {
1599 let bstride = bw + 2 * super::CDEF_BORDER;
1600 let mut win = vec![0i16; bstride * (bh + 2 * super::CDEF_BORDER)];
1601 super::cdef_gather(&src, stride, tw, th, ox, oy, bw, bh, &mut win);
1602 for r in -(super::CDEF_BORDER as i32)..(bh + super::CDEF_BORDER) as i32 {
1603 for c in -(super::CDEF_BORDER as i32)..(bw + super::CDEF_BORDER) as i32 {
1604 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
1605 let want = if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
1606 super::CDEF_VERY_LARGE as i16
1607 } else {
1608 src[ny as usize * stride + nx as usize] as i16
1609 };
1610 let got = win[(r + super::CDEF_BORDER as i32) as usize * bstride
1611 + (c + super::CDEF_BORDER as i32) as usize];
1612 assert_eq!(got, want, "({ox},{oy}) r={r} c={c}");
1613 }
1614 }
1615 }
1616}
1617
1618/// lane-cdef: the row-at-a-time direction search (and its AVX2 twin) must
1619/// be value-identical to a literal transcription of libaom
1620/// `cdef_find_dir_c`'s per-sample accumulation, over random windows at
1621/// every bit depth -- including the `CDEF_VERY_LARGE` sentinel rows a
1622/// crop-straddling 8x8 gathers.
1623#[test]
1624fn cdef_find_dir_matches_the_per_sample_reference() {
1625 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
1626 fn reference(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
1627 let mut partial = [[0i64; 15]; 8];
1628 for i in 0..8i64 {
1629 for j in 0..8i64 {
1630 let s = i64::from(
1631 win[(i as usize + super::CDEF_BORDER) * bstride
1632 + j as usize
1633 + super::CDEF_BORDER],
1634 );
1635 let x = (s >> coeff_shift) - 128;
1636 partial[0][(i + j) as usize] += x;
1637 partial[1][(i + j / 2) as usize] += x;
1638 partial[2][i as usize] += x;
1639 partial[3][(3 + i - j / 2) as usize] += x;
1640 partial[4][(7 + i - j) as usize] += x;
1641 partial[5][(3 - i / 2 + j) as usize] += x;
1642 partial[6][j as usize] += x;
1643 partial[7][(i / 2 + j) as usize] += x;
1644 }
1645 }
1646 let mut cost = [0i64; 8];
1647 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
1648 #[allow(clippy::needless_range_loop)]
1649 for i in 0..8usize {
1650 cost[2] += partial[2][i] * partial[2][i];
1651 cost[6] += partial[6][i] * partial[6][i];
1652 }
1653 cost[2] *= DIV_TABLE[8];
1654 cost[6] *= DIV_TABLE[8];
1655 for i in 0..7usize {
1656 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
1657 * DIV_TABLE[i + 1];
1658 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
1659 * DIV_TABLE[i + 1];
1660 }
1661 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
1662 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
1663 for i in (1..8).step_by(2) {
1664 for j in 0..5usize {
1665 cost[i] += partial[i][3 + j] * partial[i][3 + j];
1666 }
1667 cost[i] *= DIV_TABLE[8];
1668 for j in 0..3usize {
1669 cost[i] += (partial[i][j] * partial[i][j]
1670 + partial[i][10 - j] * partial[i][10 - j])
1671 * DIV_TABLE[2 * j + 2];
1672 }
1673 }
1674 let (mut best_cost, mut best_dir) = (0i64, 0usize);
1675 for (i, &c) in cost.iter().enumerate() {
1676 if c > best_cost {
1677 best_cost = c;
1678 best_dir = i;
1679 }
1680 }
1681 (
1682 best_dir,
1683 ((best_cost - cost[(best_dir + 4) & 7]) >> 10) as i32,
1684 )
1685 }
1686 let mut rng = 0x0bad_c0de_dead_beefu64;
1687 let mut next = move || {
1688 rng ^= rng << 13;
1689 rng ^= rng >> 7;
1690 rng ^= rng << 17;
1691 rng
1692 };
1693 let bstride = 8 + 2 * super::CDEF_BORDER;
1694 for &(bit_depth, coeff_shift) in &[(8u8, 0i32), (10, 2), (12, 4)] {
1695 let smax = (1u64 << bit_depth) - 1;
1696 for trial in 0..256 {
1697 let sentinels = trial % 4;
1698 let mut win = [0i16; 256];
1699 for (k, w) in win[..bstride * bstride].iter_mut().enumerate() {
1700 let (r, c) = (k / bstride, k % bstride);
1701 *w = if sentinels > 0
1702 && (r < sentinels
1703 || c < sentinels
1704 || r + sentinels >= bstride
1705 || c + sentinels >= bstride)
1706 {
1707 super::CDEF_VERY_LARGE as i16
1708 } else {
1709 (next() % (smax + 1)) as i16
1710 };
1711 }
1712 let want = reference(&win, bstride, coeff_shift);
1713 assert_eq!(
1714 super::cdef_find_dir(&win, bstride, coeff_shift),
1715 want,
1716 "bd={bit_depth} trial={trial}"
1717 );
1718 let partial = super::cdef_find_dir_partials(&win, bstride, coeff_shift);
1719 #[cfg(target_arch = "x86_64")]
1720 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
1721 let simd = super::cdef::cdef_find_dir_partials_dispatch(&win, bstride, coeff_shift);
1722 assert_eq!(simd, partial, "bd={bit_depth} trial={trial} partials");
1723 }
1724 }
1725 }
1726}
1727
1728/// The CDEF filter with a summoned AVX2 token, so the AVX2 kernel is reached
1729/// by a safe call: the token runs `filter_block_avx2`, its absence the scalar form (the same split `cdef_filter_block` uses).
1730#[cfg(target_arch = "x86_64")]
1731#[allow(clippy::too_many_arguments)]
1732fn cdef_filter_block_under_test(
1733 src: &[i16],
1734 dst: &mut [u16],
1735 stride: usize,
1736 ox: usize,
1737 oy: usize,
1738 bw: usize,
1739 bh: usize,
1740 pri_strength: i32,
1741 sec_strength: i32,
1742 dir: usize,
1743 pri_damping: i32,
1744 sec_damping: i32,
1745 enable_primary: bool,
1746 enable_secondary: bool,
1747 coeff_shift: i32,
1748 smax: i32,
1749) {
1750 if let Some(t) = archmage::X64V3Token::summon() {
1751 return super::cdef_simd::filter_block_avx2(
1752 t, src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,
1753 pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,
1754 );
1755 }
1756 super::cdef_filter_block_scalar(
1757 src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,
1758 pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,
1759 )
1760}
1761
1762/// lane-perf7 step 1: the AVX2 CDEF kernel must be value-identical to
1763/// [`super::cdef_filter_block_scalar`] over the whole input domain --
1764/// every direction, every enable pair, both block shapes, the 8/10/12-bit
1765/// strength and damping ranges, and windows that mix real samples with
1766/// the `CDEF_VERY_LARGE` out-of-frame sentinel (which must stay out of
1767/// the max clamp).
1768#[test]
1769#[cfg(target_arch = "x86_64")]
1770fn cdef_simd_kernel_matches_the_scalar_filter() {
1771 if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 {
1772 eprintln!("SKIP cdef simd: no avx2");
1773 return;
1774 }
1775 let mut rng = 0x1234_5678_9abc_def0u64;
1776 let mut next = move || {
1777 rng ^= rng << 13;
1778 rng ^= rng >> 7;
1779 rng ^= rng << 17;
1780 rng
1781 };
1782 for &(bit_depth, coeff_shift) in &[(8u8, 0i32), (10, 2), (12, 4)] {
1783 let smax = (1i32 << bit_depth) - 1;
1784 for &(bw, bh) in &[(8usize, 8usize), (4, 4)] {
1785 let bstride = bw + 2 * super::CDEF_BORDER;
1786 let rows = bh + 2 * super::CDEF_BORDER;
1787 let stride = bw + 5;
1788 for trial in 0..64 {
1789 // Every fourth window seeds sentinels, in a growing
1790 // border ring, so the straddling-block case is covered.
1791 let sentinels = trial % 4;
1792 // 256 entries, as `cdef_band`'s own scratch is: the
1793 // kernel taps the window in place and reads past the last
1794 // sample into the zeroed tail.
1795 let mut win: Vec<i16> = (0..rows * bstride)
1796 .map(|k| {
1797 let (r, c) = (k / bstride, k % bstride);
1798 if sentinels > 0
1799 && (r < sentinels
1800 || c < sentinels
1801 || r + sentinels >= rows
1802 || c + sentinels >= bstride)
1803 {
1804 super::CDEF_VERY_LARGE as i16
1805 } else {
1806 (next() % (smax as u64 + 1)) as i16
1807 }
1808 })
1809 .collect();
1810 win.resize(256, 0);
1811 for dir in 0..8usize {
1812 for &pri in &[0i32, 1, 3, 15] {
1813 for &sec in &[0i32, 1, 2, 4] {
1814 for &damping in &[3i32, 5, 6, 9] {
1815 let (pri, sec) = (pri << coeff_shift, sec << coeff_shift);
1816 let (ep, es) = (pri != 0, sec != 0);
1817 if !ep && !es {
1818 continue;
1819 }
1820 let seed: Vec<u16> =
1821 (0..stride * (bh + 2)).map(|k| (k % 97) as u16).collect();
1822 let mut a = seed.clone();
1823 let mut b = seed;
1824 super::cdef_filter_block_scalar(
1825 &win,
1826 &mut a,
1827 stride,
1828 1,
1829 1,
1830 bw,
1831 bh,
1832 pri,
1833 sec,
1834 dir,
1835 damping,
1836 damping,
1837 ep,
1838 es,
1839 coeff_shift,
1840 smax,
1841 );
1842 cdef_filter_block_under_test(
1843 &win,
1844 &mut b,
1845 stride,
1846 1,
1847 1,
1848 bw,
1849 bh,
1850 pri,
1851 sec,
1852 dir,
1853 damping,
1854 damping,
1855 ep,
1856 es,
1857 coeff_shift,
1858 smax,
1859 );
1860 assert_eq!(
1861 a, b,
1862 "bd={bit_depth} bw={bw} trial={trial} dir={dir} \
1863 pri={pri} sec={sec} damping={damping}"
1864 );
1865 }
1866 }
1867 }
1868 }
1869 }
1870 }
1871 }
1872}
1873
1874/// lane-perf8: the AVX2 deblock kernel must be sample-identical to
1875/// [`super::filter_edge`] over the whole input domain -- every bit depth,
1876/// every filter length, every level and sharpness, and sample patterns
1877/// that put each of `mask`, `flat` and `flat2` on both sides of its
1878/// threshold (uniform, flat-with-step, small-noise and full-range
1879/// random), on both edge directions.
1880#[test]
1881#[cfg(target_arch = "x86_64")]
1882fn deblock_simd_kernel_matches_the_scalar_filter() {
1883 let fctx = &crate::decode::FrameCtx::new();
1884 if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 {
1885 eprintln!("SKIP deblock simd: no avx2");
1886 return;
1887 }
1888 let mut rng = 0x9e37_79b9_7f4a_7c15u64;
1889 let mut next = move || {
1890 rng ^= rng << 13;
1891 rng ^= rng >> 7;
1892 rng ^= rng << 17;
1893 rng
1894 };
1895 let (stride, rows) = (64usize, 64usize);
1896 for &bd in &[8u8, 10, 12] {
1897 super::set_bit_depth(bd, fctx);
1898 let smax = (1u64 << bd) - 1;
1899 for pattern in 0..4u32 {
1900 for trial in 0..8 {
1901 let seed: Vec<u16> = (0..stride * rows)
1902 .map(|k| {
1903 let base = ((k / stride) as u64 * 7 + trial) % (smax + 1);
1904 (match pattern {
1905 // Uniform-ish: every mask and both flats pass.
1906 0 => base,
1907 // A step across the edge column/row.
1908 1 => (base + if k % stride >= 32 { smax / 2 } else { 0 }) % (smax + 1),
1909 // Small noise: flat passes at 8-bit, not always higher.
1910 2 => (base + next() % 4) % (smax + 1),
1911 _ => next() % (smax + 1),
1912 }) as u16
1913 })
1914 .collect();
1915 for &len in &[4u8, 6, 8, 14] {
1916 for &level in &[0i32, 1, 7, 23, 40, 63] {
1917 for sharpness in 0..8u8 {
1918 for &vertical in &[true, false] {
1919 let (base, outer, tap) = if vertical {
1920 (32 * stride + 32, stride as isize, 1isize)
1921 } else {
1922 (32 * stride + 32, 1isize, stride as isize)
1923 };
1924 let mut a = seed.clone();
1925 for g in 0..4usize {
1926 let b = if vertical {
1927 base + 4 * g * stride
1928 } else {
1929 base + 4 * g
1930 };
1931 super::filter_edge(
1932 &mut a, b, outer, tap, len, level, sharpness, fctx,
1933 );
1934 }
1935 let mut b = seed.clone();
1936 assert!(super::filter_edge16(
1937 &mut b, base, stride, vertical, len, level, sharpness, fctx,
1938 ));
1939 assert_eq!(
1940 a, b,
1941 "bd={bd} pattern={pattern} trial={trial} len={len} \
1942 level={level} sharp={sharpness} vert={vertical}"
1943 );
1944 }
1945 }
1946 }
1947 }
1948 }
1949 }
1950 }
1951 super::set_bit_depth(8, fctx);
1952}
1953
1954/// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce
1955/// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`
1956/// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue
1957/// was one 64x64 inter superblock whose 32x32 chroma units are
1958/// `EXT_TX_SET_DCT_IDTX`, where IDTX survives and we forced `DCT_DCT`.
1959#[test]
1960fn an_inter_chroma_transform_narrows_its_inherited_tx_type_to_its_own_set() {
1961 let fctx = &crate::decode::FrameCtx::new();
1962 use TxType::*;
1963 // EXT_TX_SET_DCTONLY: `tx_size_sqr_up > TX_32X32`.
1964 set_inter_tx_mode(true, false, true, fctx);
1965 assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 64, 64, fctx), DctDct);
1966 // EXT_TX_SET_DCT_IDTX at exactly TX_32X32 -- the residue's case.
1967 assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 32, 32, fctx), Idtx);
1968 assert_eq!(
1969 reduce_inherited_chroma_tx_type(AdstAdst, 32, 32, fctx),
1970 DctDct
1971 );
1972 // EXT_TX_SET_DTT9_IDTX_1DDCT at `tx_size_sqr == TX_16X16`: the four
1973 // 1D ADST/FLIPADST types (TX_TYPES 12..15) drop out, the rest stay.
1974 assert_eq!(reduce_inherited_chroma_tx_type(HDct, 16, 16, fctx), HDct);
1975 assert_eq!(
1976 reduce_inherited_chroma_tx_type(FlipAdstAdst, 16, 16, fctx),
1977 FlipAdstAdst
1978 );
1979 assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 16, 16, fctx), DctDct);
1980 // EXT_TX_SET_ALL16 below that (`tx_size_sqr < TX_16X16`, so a 16x8
1981 // chroma unit too).
1982 assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 16, 8, fctx), HAdst);
1983 assert_eq!(
1984 reduce_inherited_chroma_tx_type(VFlipAdst, 8, 8, fctx),
1985 VFlipAdst
1986 );
1987 // `reduced_tx_set` collapses every inter set to DCT_IDTX.
1988 set_inter_tx_mode(true, true, true, fctx);
1989 assert_eq!(reduce_inherited_chroma_tx_type(Idtx, 8, 8, fctx), Idtx);
1990 assert_eq!(reduce_inherited_chroma_tx_type(HAdst, 8, 8, fctx), DctDct);
1991 set_inter_tx_mode(true, false, true, fctx);
1992}
1993
1994/// lane-fistrip r1 (class `enumerate-the-table-domain`): every block
1995/// shape this decoder can hand [`filter_intra_size_class_rect`], against
1996/// `av1_filter_intra_allowed_bsize` (`block_size_wide <= 32 &&
1997/// block_size_high <= 32`) and `default_filter_intra_cdfs`
1998/// (entropymode.c) row by row. A class that exists must carry ITS OWN
1999/// bsize's default probability -- a wrong row is a silently different
2000/// symbol, not a decode error. The shapes with no class are listed here
2001/// with their reason so the residue is pinned rather than implied.
2002#[test]
2003fn filter_intra_classes_carry_their_own_libaom_default_row() {
2004 // `default_filter_intra_cdfs[bsize]`, BLOCK_SIZES_ALL order, as
2005 // (width, height, default, refused_by) for the shapes <= 32 on both
2006 // axes. The first three fields are GENERATED from the oracle by
2007 // `scripts/extract-filter-intra-cdfs.py` (it reads BLOCK_SIZES_ALL's
2008 // order from enums.h and the table from entropymode.c, so no hand
2009 // transcription can drift -- lane-fistrip r1 listed the four 1:4
2010 // shapes as 16384 out of exactly that kind of guess; their real rows
2011 // are 12770/10368/20229/18101). `refused_by` is `None` for a shape
2012 // this decoder's partition tree reaches today -- it must own a class,
2013 // and that class must carry exactly this row -- and the refusal
2014 // string that blocks the shape otherwise. Either way the row is
2015 // pinned HERE, so the round that lifts one of those refusals cannot
2016 // land a wrong CDF row for the shape it unlocks.
2017 let libaom: &[(usize, usize, u16, Option<&str>)] = &[
2018 (4, 4, 4621, None),
2019 (4, 8, 6743, None),
2020 (8, 4, 5893, None),
2021 (8, 8, 7866, None),
2022 (8, 16, 12551, None),
2023 (16, 8, 9394, None),
2024 (16, 16, 12408, None),
2025 (16, 32, 14301, None),
2026 (32, 16, 12756, None),
2027 (32, 32, 22343, None),
2028 // The 1:4 strips: a 16x16-level PARTITION_HORZ_4/VERT_4 gives
2029 // 4x16/16x4 (still refused by name before any leaf is coded),
2030 // a 32x32-level one 8x32/32x8.
2031 // lane-r14: the 16-level pair is coded now (`decode_rect4_16`),
2032 // owning classes 13/12.
2033 (4, 16, 12770, None),
2034 (16, 4, 10368, None),
2035 // lane-fi32x8 r1: the 32-level pair is coded (four 32x8/8x32
2036 // strips per `PARTITION_HORZ_4`/`VERT_4`) and now owns classes
2037 // 10/11; only the 16-level pair is still refused before any leaf.
2038 (8, 32, 20229, None),
2039 (32, 8, 18101, None),
2040 ];
2041 let mut classes_seen = std::collections::BTreeSet::new();
2042 for &(bw, bh, default, refused_by) in libaom {
2043 match filter_intra_size_class_rect(bw, bh) {
2044 Some(class) => {
2045 assert!(
2046 refused_by.is_none(),
2047 "{bw}x{bh} has a CDF class but is listed as refused by {refused_by:?} -- \
2048 one of the two is stale"
2049 );
2050 assert_eq!(
2051 crate::cdf::FILTER_INTRA[class][0],
2052 default,
2053 "{bw}x{bh} (class {class}) must carry default_filter_intra_cdfs' own row"
2054 );
2055 assert_eq!(
2056 &crate::cdf::FILTER_INTRA[class][1..],
2057 &[32768u16, 0][..],
2058 "{bw}x{bh} (class {class}) is a 2-symbol CDF: {{p, 32768, count}}"
2059 );
2060 assert!(
2061 classes_seen.insert(class),
2062 "class {class} is claimed by two shapes -- one of them reads the other's \
2063 probability"
2064 );
2065 }
2066 None => {
2067 let why = refused_by.unwrap_or_else(|| {
2068 panic!(
2069 "{bw}x{bh} is inside av1_filter_intra_allowed_bsize and reachable, \
2070 but has no CDF class -- its use_filter_intra symbol is never read"
2071 )
2072 });
2073 assert!(
2074 !why.is_empty(),
2075 "{bw}x{bh}'s refusal string must name the blocker"
2076 );
2077 }
2078 }
2079 }
2080 // The other direction: every row of `cdf::FILTER_INTRA` was claimed
2081 // by exactly one shape above, so no row can be left over (or shared)
2082 // once a class is added or removed.
2083 assert_eq!(
2084 classes_seen.len(),
2085 crate::cdf::FILTER_INTRA.len(),
2086 "cdf::FILTER_INTRA has {} rows but only {:?} are claimed by an allowed shape",
2087 crate::cdf::FILTER_INTRA.len(),
2088 classes_seen
2089 );
2090 // Past the bound on either axis: no symbol at all (spec
2091 // `filter_intra_mode_info` never reads one).
2092 for (bw, bh) in [(64, 64), (64, 32), (32, 64)] {
2093 assert!(
2094 filter_intra_size_class_rect(bw, bh).is_none(),
2095 "{bw}x{bh} is past av1_filter_intra_allowed_bsize's <=32 bound"
2096 );
2097 }
2098}
2099use archmage::SimdToken;
2100use super::*;
2101
2102/// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
2103/// `SCAN_4X16[i]` must name the transpose of the position
2104/// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of
2105/// libaom's column-major `default_scan_*` installs the transpose and only
2106/// an asymmetric check catches it). Also pins both as permutations, and
2107/// pins the same relation for the 32x8/8x32 luma pair this arm reuses.
2108#[test]
2109fn the_rect4_scans_are_transposed_pairs() {
2110 for (a, b, w, h) in [
2111 (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize),
2112 (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8),
2113 ] {
2114 let mut seen_a: Vec<u16> = a.to_vec();
2115 seen_a.sort_unstable();
2116 assert_eq!(
2117 seen_a,
2118 (0..(w * h) as u16).collect::<Vec<_>>(),
2119 "{w}x{h} scan is not a permutation of its positions"
2120 );
2121 for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() {
2122 let (row, col) = (pa as usize / w, pa as usize % w);
2123 assert_eq!(
2124 pb as usize,
2125 col * w.min(h) + row,
2126 "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \
2127 visits position {pb}"
2128 );
2129 }
2130 }
2131}
2132
2133/// lane-coef2 (class `enumerate-table-domain`): the padded level buffers
2134/// [`read_coeffs`]/[`read_coeffs_rect`] hand to [`neighbour`] dropped the
2135/// `row >= side || col >= side` edge test, so the padding must cover the
2136/// WIDEST offset any `base_ctx` class reads -- `(row + 4, col)` and
2137/// `(row, col + 4)` -- at every transform size this decoder codes, and
2138/// the buffer must be no larger than the fixed frames those two functions
2139/// declare (`36 * 36` square, `768` rect).
2140#[test]
2141fn padded_level_buffers_cover_every_neighbour_read_at_every_transform_size() {
2142 for side in [4usize, 8, 16, 32] {
2143 let stride = side + 4;
2144 let (row, col) = (side - 1, side - 1);
2145 let widest = ((row + 4) * stride + col + 4).max(row * stride + col + 4);
2146 assert!(widest < stride * stride, "square {side}: {widest}");
2147 assert!(stride * stride <= 36 * 36, "square {side} frame");
2148 }
2149 for (w, h) in [
2150 (4usize, 8usize),
2151 (8, 4),
2152 (8, 16),
2153 (16, 8),
2154 (4, 16),
2155 (16, 4),
2156 (8, 32),
2157 (32, 8),
2158 (16, 32),
2159 (32, 16),
2160 ] {
2161 let stride = w + 4;
2162 let n = stride * (h + 4);
2163 let (row, col) = (h - 1, w - 1);
2164 let widest = ((row + 4) * stride + col + 4).max(row * stride + col + 4);
2165 assert!(widest < n, "rect {w}x{h}: {widest} >= {n}");
2166 assert!(n <= 768, "rect {w}x{h} frame {n}");
2167 assert!(w.is_power_of_two(), "rect {w}x{h} stride mask");
2168 }
2169}
2170
2171/// lane-rectsplit r4 (class `enumerate-table-domain`): [`base_ctx`]'s
2172/// `TX_CLASS_2D` arm must, over the WHOLE 5x5 domain of both rect shapes
2173/// and the square one, return exactly what libaom's
2174/// `av1_nz_map_ctx_offset[tx_size][coeff_idx]` holds -- the flat tables
2175/// transcribed in [`cdf`], read at libaom's own COLUMN-major
2176/// `coeff_idx = col * 32 + row`, i.e. `table[col][row]`. r1..r3 read them
2177/// `[row][col]`, which is the transpose (the OTHER shape's rule, with 11
2178/// and 16 swapped): it desynced the first superblock strip whose luma
2179/// corner held a coefficient off the first row/column.
2180/// lane-coefread: the per-coefficient neighbour gather now reads FLAT
2181/// offsets ([`flat_taps`]) instead of `(row + dr, col + dc)`. Same cells,
2182/// every class, every square size, over the whole `(row, col)` domain.
2183#[test]
2184fn flat_taps_match_the_row_col_neighbour_reads() {
2185 for &side in &[4usize, 8, 16, 32] {
2186 let stride = side + 4;
2187 let mut grid = vec![0u8; stride * stride];
2188 let mut x = 12345u32;
2189 for c in grid.iter_mut() {
2190 x = x.wrapping_mul(1103515245).wrapping_add(12345);
2191 *c = ((x >> 16) & 15) as u8;
2192 }
2193 for class in [TxClass::TwoD, TxClass::Horiz, TxClass::Vert] {
2194 let (bt, rt) = flat_taps(stride, class);
2195 for row in 0..side {
2196 for col in 0..side {
2197 let idx = row * stride + col;
2198 if !(class == TxClass::TwoD && row == 0 && col == 0) {
2199 let want = base_ctx(&grid, stride, row, col, class, None);
2200 let got = base_mag(&grid, idx, &bt)
2201 + match class {
2202 TxClass::TwoD => {
2203 cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
2204 }
2205 TxClass::Horiz => nz_map_ctx_offset_1d(col.min(31)),
2206 TxClass::Vert => nz_map_ctx_offset_1d(row.min(31)),
2207 };
2208 assert_eq!(got, want, "base side {side} at {row},{col}");
2209 }
2210 let want = br_ctx(&grid, stride, row, col, class);
2211 let mag = br_mag(&grid, idx, &rt);
2212 let got = if row == 0 && col == 0 {
2213 mag
2214 } else {
2215 let near = match class {
2216 TxClass::TwoD => row < 2 && col < 2,
2217 TxClass::Horiz => col == 0,
2218 TxClass::Vert => row == 0,
2219 };
2220 if near { mag + 7 } else { mag + 14 }
2221 };
2222 assert_eq!(got, want, "br side {side} at {row},{col}");
2223 assert_eq!(
2224 br_ctx_rect(&grid, stride, row, col, class),
2225 want,
2226 "br_rect side {side} at {row},{col}"
2227 );
2228 }
2229 }
2230 }
2231 }
2232}
2233
2234#[test]
2235fn base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain() {
2236 let grid = [0u8; 36 * 36];
2237 for (shape, table) in [
2238 (Some((64usize, 32usize)), &cdf::NZ_MAP_CTX_OFFSET_64X32),
2239 (Some((32, 64)), &cdf::NZ_MAP_CTX_OFFSET_32X64),
2240 (None, &cdf::NZ_MAP_CTX_OFFSET_32),
2241 ] {
2242 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
2243 #[allow(clippy::needless_range_loop)]
2244 for row in 0..5usize {
2245 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
2246 #[allow(clippy::needless_range_loop)]
2247 for col in 0..5usize {
2248 // An all-zero neighbourhood makes the magnitude term 0,
2249 // so `base_ctx` returns the offset itself.
2250 let got = base_ctx(&grid, 36, row, col, TxClass::TwoD, shape);
2251 let want = if row == 0 && col == 0 {
2252 0
2253 } else {
2254 table[col][row] as usize
2255 };
2256 assert_eq!(got, want, "{shape:?} at (row {row}, col {col})");
2257 }
2258 }
2259 }
2260}
2261
2262// `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
2263// `split_dc_key_frame_tile` are not exercised here: they are synthetic
2264// single-purpose writers with their own skip-context rule (keyed to
2265// superblock position, not the neighbour-tracked one every real block
2266// uses), never reached by `encode_key_frame_with_modes` — decoding them
2267// would need a second, throwaway context convention next to the real
2268// one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
2269// this decoder's one target, and the round-trip test below is against
2270// that path with real quantised residual, not a synthetic all-DC frame.
2271
2272/// [`SCAN_8X4`]/[`SCAN_4X8`] (lane-rectx r2): a bijection check alone
2273/// cannot catch a transposed pair -- a swap of two orientation tables is
2274/// still a bijection over the same 32 positions. This pins BOTH arrays
2275/// at once, element-for-element, against literal transcriptions of
2276/// libaom's real `default_scan_4x8`/`default_scan_8x4` in
2277/// `av1/common/scan.c` (`~/.cache/aom-oracle/src`, read directly for
2278/// this test, not re-derived from the zigzag formula). The two source
2279/// sequences are themselves different in their own right (not equal to
2280/// each other), so this is asymmetric in the two axes: if the repo's
2281/// `SCAN_8X4`/`SCAN_4X8` were swapped with each other, one side of this
2282/// assert pair would fail even though each individual array would still
2283/// pass a same-orientation bijection test.
2284#[test]
2285fn scan_8x4_and_4x8_are_not_transposed_against_each_other() {
2286 // libaom `default_scan_4x8` verbatim (scan.c:29-32) -- this repo
2287 // names it `SCAN_8X4` under the established w/h axis swap (see
2288 // `SCAN_8X4`'s own doc comment).
2289 const LIBAOM_DEFAULT_SCAN_4X8: [u16; 32] = [
2290 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14,
2291 7, 29, 22, 15, 30, 23, 31,
2292 ];
2293 // libaom `default_scan_8x4` verbatim (scan.c:44-47) -- this repo's
2294 // `SCAN_4X8`.
2295 const LIBAOM_DEFAULT_SCAN_8X4: [u16; 32] = [
2296 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25,
2297 28, 23, 26, 29, 27, 30, 31,
2298 ];
2299 assert_ne!(
2300 LIBAOM_DEFAULT_SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
2301 "the two libaom source sequences must differ, or this pin would \
2302 pass regardless of a swap"
2303 );
2304 assert_eq!(
2305 SCAN_8X4, LIBAOM_DEFAULT_SCAN_4X8,
2306 "SCAN_8X4 vs libaom default_scan_4x8"
2307 );
2308 assert_eq!(
2309 SCAN_4X8, LIBAOM_DEFAULT_SCAN_8X4,
2310 "SCAN_4X8 vs libaom default_scan_8x4"
2311 );
2312}
2313
2314/// lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <= 32",
2315/// so a DC_PRED 16x8/8x16 strip reads a `use_filter_intra` flag exactly
2316/// like a square 16x16 does. [`filter_intra_size_class_rect`] returned
2317/// `None` at those two sizes, so the symbol was never read and the tile
2318/// desynced from that block on (root-caused against an instrumented
2319/// aomdec `EC_TRACE_COEFF` ladder on a real stream: identical `mode=0`/
2320/// `uv_mode=9` values, our range 34808 vs the oracle's 40668 at the very
2321/// next transform block).
2322///
2323/// The two rows are ASYMMETRIC (9394 for 16x8, 12551 for 8x16), so this
2324/// pin fails if the pair is ever transposed -- the shape the repo's
2325/// scan tables already carry (`SCAN_8X4` == libaom `default_scan_4x8`).
2326#[test]
2327fn a_rect_strip_below_16x16_reads_its_own_filter_intra_cdf_row() {
2328 // `default_filter_intra_cdfs` (entropymode.c), indexed by BLOCK_SIZES_ALL:
2329 // [4] = BLOCK_8X16, [5] = BLOCK_16X8, [7] = BLOCK_16X32, [8] = BLOCK_32X16.
2330 const LIBAOM_8X16: u16 = 12551;
2331 const LIBAOM_16X8: u16 = 9394;
2332 let c16x8 = filter_intra_size_class_rect(16, 8).expect("16x8 reads use_filter_intra");
2333 let c8x16 = filter_intra_size_class_rect(8, 16).expect("8x16 reads use_filter_intra");
2334 assert_ne!(
2335 c16x8, c8x16,
2336 "the two orientations must not share a CDF row"
2337 );
2338 assert_eq!(
2339 cdf::FILTER_INTRA[c16x8][0],
2340 LIBAOM_16X8,
2341 "16x8 filter_intra row"
2342 );
2343 assert_eq!(
2344 cdf::FILTER_INTRA[c8x16][0],
2345 LIBAOM_8X16,
2346 "8x16 filter_intra row"
2347 );
2348 // The sizes one class up keep their own distinct rows (lane-intradisp).
2349 assert_eq!(
2350 cdf::FILTER_INTRA[filter_intra_size_class_rect(32, 16).unwrap()][0],
2351 12756
2352 );
2353 assert_eq!(
2354 cdf::FILTER_INTRA[filter_intra_size_class_rect(16, 32).unwrap()][0],
2355 14301
2356 );
2357 // A size with a side over 32 is genuinely not allowed the flag.
2358 assert_eq!(filter_intra_size_class_rect(64, 32), None);
2359}
2360
2361/// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
2362/// when both references sit on the same temporal side -- the three
2363/// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
2364/// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
2365/// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
2366/// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
2367/// not just the three enumerated syntax pairs).
2368#[test]
2369fn is_uni_comp_ref_matches_forward_backward_sides() {
2370 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
2371 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
2372 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
2373 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
2374 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
2375 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
2376}
2377
2378/// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
2379/// with the real second reference (lane-av1comp round 12: previously
2380/// always cleared to `None` by `record_inter`, so the next block's own
2381/// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
2382/// -- could never see a real compound neighbour).
2383/// lane-interp3 r1: a decoder must never abort the process on
2384/// stream-derived state. `neighbour_filter` used to feed the `[3, 3]`
2385/// "no filter recorded" sentinel straight into
2386/// `InterpFilterKind::from_switchable_symbol`, whose `panic!` ("...alphabet
2387/// is exactly 3 symbols") crashed on a real aomenc dual-filter + OBMC
2388/// stream. It now refuses by name; the real symbols still decode.
2389#[test]
2390fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() {
2391 assert!(
2392 neighbour_filter(None, [3, 3])
2393 .unwrap_err()
2394 .to_string()
2395 .contains("an OBMC neighbour whose switchable interp filter was never recorded"),
2396 "the [3, 3] sentinel must refuse by name, never panic"
2397 );
2398 assert!(neighbour_filter(None, [3, 0]).is_err());
2399 let (h, v) = neighbour_filter(None, [0, 2]).expect("real symbols decode");
2400 assert_eq!(
2401 h,
2402 mc::InterpFilterKind::Sharp,
2403 "sym[1] is the horizontal kernel"
2404 );
2405 assert_eq!(
2406 v,
2407 mc::InterpFilterKind::Regular,
2408 "sym[0] is the vertical kernel"
2409 );
2410 let (h, v) = neighbour_filter(Some(mc::InterpFilterKind::Smooth), [3, 3])
2411 .expect("a fixed-filter frame never reads a symbol");
2412 assert_eq!(
2413 (h, v),
2414 (mc::InterpFilterKind::Smooth, mc::InterpFilterKind::Smooth)
2415 );
2416}
2417
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]
2434fn every_inter_record_publishes_an_obmc_readable_filter() {
2435 let src = crate::test_source::module_source("decode");
2436 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
2437 // it names it and pins its guard site. The sibling test
2438 // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking`
2439 // carries the same string 27k lines away in this file -- exactly the
2440 // reach a window that is not a function boundary used to have.
2441 const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded";
2442 assert!(
2443 crate::refusal_inventory::pins_refusal(src, REFUSAL),
2444 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
2445 );
2446 let mut calls = 0usize;
2447 for (start, _) in src.match_indices("record_inter_rect_mi(") {
2448 // Skip the definition and the wrapper's own forwarding call.
2449 let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1);
2450 let head = &src[line_start..start];
2451 // The definition, the wrapper's own forwarding call, and this
2452 // test's own mentions of the name (doc comment, scan pattern,
2453 // assert message) are not publication sites.
2454 if head.contains("fn ") || head.contains("///") || head.ends_with('"') {
2455 continue;
2456 }
2457 let mut i = start + "record_inter_rect_mi(".len();
2458 let (mut depth, mut arg, mut args) = (0i32, String::new(), Vec::new());
2459 let bytes = src.as_bytes();
2460 while i < bytes.len() {
2461 let c = bytes[i] as char;
2462 match c {
2463 '(' | '[' => depth += 1,
2464 ')' | ']' if depth == 0 && c == ')' => break,
2465 ')' | ']' => depth -= 1,
2466 ',' if depth == 0 => {
2467 args.push(std::mem::take(&mut arg));
2468 i += 1;
2469 continue;
2470 }
2471 _ => {}
2472 }
2473 arg.push(c);
2474 i += 1;
2475 }
2476 if !arg.trim().is_empty() {
2477 args.push(arg);
2478 }
2479 assert_eq!(
2480 args.len(),
2481 8,
2482 "record_inter_rect_mi gained an argument -- re-index this audit: {args:?}"
2483 );
2484 calls += 1;
2485 let (is_inter, filter) = (args[4].trim(), args[6].trim());
2486 if filter.starts_with('[') {
2487 assert_eq!(
2488 filter.replace(' ', ""),
2489 "[3,3]",
2490 "a literal filter other than the sentinel is published at call {calls}"
2491 );
2492 assert_eq!(
2493 is_inter, "false",
2494 "an INTER cell is stamped with the [3, 3] sentinel (call {calls}): an OBMC \
2495 blend picking it up refuses by name. Publish the block's own resolved \
2496 switchable symbols instead."
2497 );
2498 }
2499 }
2500 assert!(
2501 calls >= 6,
2502 "the audit found only {calls} publication sites -- it is broken, not the decoder"
2503 );
2504}
2505
2506/// lane-t900 r27, negative gate for "a reference frame selected with no
2507/// picture at this frame's own ref_frame_idx slot for it": every
2508/// non-`LAST_FRAME` reference resolves through `ref_planes`, and an empty
2509/// slot is refused BY NAME there rather than predicting from `LAST`.
2510///
2511/// Direct-call, not a stream: with this crate's writers the case is
2512/// unreachable end to end. A SHOWN key frame refreshes all eight slots
2513/// (spec 5.9.2 forces `refresh_frame_flags`, `write_frame_header` does the
2514/// same) and nothing ever clears a slot, so once a stream has a key frame
2515/// every slot holds a picture; a stream that OPENS on an inter frame is
2516/// stopped one guard earlier, by `decode_stream`'s own `LAST` lookup
2517/// ("an inter frame with no key frame before it", gated by
2518/// `an_inter_frame_opening_a_stream_is_refused_by_name`). The reachable
2519/// premise is a HIDDEN key frame refreshing only some slots, which
2520/// `write_frame_header` refuses to write (`show_frame` must be set) --
2521/// so the stream-level witness needs a hidden-frame writer, noted as the
2522/// open half of this proof.
2523#[test]
2524fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {
2525 // lane-av1refusalspan: the FULL refusal, not a prefix of it. This gate
2526 // is the proof for the row in `refusal_inventory`, whose anchor is the
2527 // whole string (it carries no `(` and no `:`), and this const is what
2528 // that anchor reads. Shortened to `...own ref_frame_idx slot` it
2529 // stopped being a pin on the guard's text.
2530 const REFUSAL: &str = "a reference frame selected with no picture at this frame's own \
2531 ref_frame_idx slot for it";
2532 let pic = Picture {
2533 width: 4,
2534 height: 4,
2535 y: vec![0u16; 16],
2536 u: vec![0u16; 4],
2537 v: vec![0u16; 4],
2538 };
2539 let mut refs: [Option<&Picture>; 8] = [None; 8];
2540 refs[1] = Some(&pic);
2541 let refpix = RefPix::ready(refs);
2542 for ref_frame in [
2543 LAST2_FRAME,
2544 LAST3_FRAME,
2545 GOLDEN_FRAME,
2546 BWDREF_FRAME,
2547 ALTREF2_FRAME,
2548 ALTREF_FRAME,
2549 ] {
2550 let err = match ref_planes(ref_frame, &refpix) {
2551 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),
2552 Err(e) => e.to_string(),
2553 };
2554 assert!(
2555 err.contains(REFUSAL),
2556 "ref {ref_frame}: expected {REFUSAL:?}, got: {err}"
2557 );
2558 }
2559 // `LAST_FRAME` never consults the slots: `decode_stream` checked it.
2560 let Ok((y, _, _)) = ref_planes(LAST_FRAME, &refpix) else {
2561 panic!("LAST_FRAME resolves to the frame's own reference planes")
2562 };
2563 assert_eq!(y.width, 4);
2564}
2565
2566#[test]
2567fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
2568 let fctx = &crate::decode::FrameCtx::new();
2569 let mut n = Neighbours::new(4, 4, 16, 16, fctx);
2570 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
2571 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
2572 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
2573 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
2574 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
2575 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
2576}
2577
2578/// A below-16px leaf must clear the palette neighbour state over its own
2579/// cell: before lane-palette2 r8 `record_palette_y_rect`'s `w / SUB` loops
2580/// ran zero times for any sub-16 span, so `decode_leaf_rect` /
2581/// `decode_leaf8` left a previous block's palette size and colours in the
2582/// above/left arrays and the NEXT block read `palette_y_mode` off the
2583/// wrong CDF row with a stale colour cache (class
2584/// [[cdf-row-held-constant]]).
2585#[test]
2586fn a_sub16_leaf_after_a_palette_block_yields_palette_ctx_zero() {
2587 let fctx = &crate::decode::FrameCtx::new();
2588 let mut n = Neighbours::new(4, 4, 16, 16, fctx);
2589 // A real 16x16 palette block covering SUB cell (1, 1).
2590 n.record_palette_y_rect((4, 4), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
2591 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
2592 assert_eq!(ctx, 2, "the palette block itself must be visible");
2593 assert_eq!(cache, vec![7, 9]);
2594 // An 8x8 non-palette leaf in that same cell.
2595 n.record_palette_y_rect((4, 4), 8, 8, 0, [0u16; 8]);
2596 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
2597 assert_eq!(ctx, 0, "a sub-16 non-palette leaf must clear its own cell");
2598 assert!(cache.is_empty(), "and its stale colour cache with it");
2599 // Same for the chroma half.
2600 n.record_palette_uv_rect((4, 4), 16, 16, 2, [1, 2, 0, 0, 0, 0, 0, 0]);
2601 assert_eq!(n.palette_uv_cache((1, 1)), vec![1, 2]);
2602 n.record_palette_uv_rect((4, 4), 8, 8, 0, [0u16; 8]);
2603 assert!(n.palette_uv_cache((1, 1)).is_empty());
2604}
2605
2606/// lane-publish2 (the mode-info publish surface narrowed): two invariants
2607/// the byte-exact stream gate only covers indirectly -- a size-0 palette
2608/// stamp leaves the PREVIOUS block's colours in place (spec 5.11.46
2609/// `get_palette_cache` reads a neighbour's colours only where its size is
2610/// non-zero, so writing 16 bytes of zeroes was pure traffic), and the
2611/// narrowed `(u16, u8)` mi maps keep their "never written" sentinel.
2612#[test]
2613fn narrowed_publish_surface_keeps_neighbour_semantics() {
2614 assert_eq!(
2615 std::mem::size_of::<(u16, u8)>(),
2616 4,
2617 "the narrowing must actually be 4 bytes"
2618 );
2619 let fctx = &crate::decode::FrameCtx::new();
2620 let mut n = Neighbours::new(4, 4, 16, 16, fctx);
2621 n.record_palette_y_rect((4, 4), 16, 16, 2, [7, 9, 0, 0, 0, 0, 0, 0]);
2622 n.record_palette_y_rect((4, 4), 16, 16, 0, [0u16; 8]);
2623 assert_eq!(
2624 n.above_palette_size[4], 0,
2625 "the size is what a reader gates on"
2626 );
2627 assert_eq!(
2628 n.above_palette_colors[4],
2629 [7, 9, 0, 0, 0, 0, 0, 0],
2630 "a size-0 stamp deliberately leaves the stale colours behind"
2631 );
2632 let (ctx, cache) = n.palette_ctx_and_cache((1, 1));
2633 assert_eq!(ctx, 0, "and they stay invisible to every reader");
2634 assert!(cache.is_empty());
2635 assert_eq!(
2636 n.mode_above_mi(4, 4),
2637 None,
2638 "u16::MAX sentinel = never written"
2639 );
2640 n.record_mode_mi(3, 4, 1, 1, DC_PRED);
2641 assert_eq!(n.mode_above_mi(4, 4), Some(DC_PRED));
2642}
2643
2644/// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
2645/// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
2646/// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
2647/// -- a few corner and interior points, not the whole 6x6 grid.
2648#[test]
2649fn compound_mode_ctx_map_matches_libaom_corners() {
2650 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
2651 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
2652 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
2653 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
2654 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
2655 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
2656 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
2657 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
2658 // exactly the ranges `find_mv_stack_compound` produces.
2659 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][4], 7);
2660}
2661
2662#[test]
2663fn a_frame_with_no_mode_info_grid_is_refused() {
2664 let fctx = &crate::decode::FrameCtx::new();
2665 assert!(
2666 decode_key_frame_tile(
2667 &[0u8; 4],
2668 0,
2669 32,
2670 32,
2671 0,
2672 128,
2673 false,
2674 &CdefParams::default(),
2675 &LoopFilterParams::default(),
2676 false,
2677 true,
2678 false,
2679 false,
2680 fctx,
2681 )
2682 .is_err()
2683 );
2684}
2685
2686/// Encodes and decodes one picture with `modes`, asserting the decoder's
2687/// planes are byte-exact against the encoder's own reconstruction.
2688fn round_trips(w: usize, h: usize, modes: &[u8], fctx: &crate::decode::FrameCtx) {
2689 use crate::encode::{Encoded, Picture as Pic};
2690 let mut source = vec![0u16; w * h];
2691 for row in 0..h {
2692 for col in 0..w {
2693 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
2694 }
2695 }
2696 let picture = Pic {
2697 width: w,
2698 height: h,
2699 y: source,
2700 u: vec![128; w * h / 4],
2701 v: vec![128; w * h / 4],
2702 };
2703 let Encoded {
2704 tile,
2705 reconstruction,
2706 mi_cols,
2707 mi_rows,
2708 base_q_idx,
2709 tx_select,
2710 loop_filter,
2711 cdef,
2712 loop_restoration,
2713 ..
2714 }: Encoded =
2715 crate::encode::encode_key_frame_with_modes_with_ctx(&picture, 40, 0.0, modes, fctx)
2716 .unwrap();
2717 let decoded = decode_key_frame_tile_lr(
2718 &tile,
2719 mi_cols,
2720 mi_rows,
2721 base_q_idx,
2722 w as u32,
2723 h as u32,
2724 // lane-fintra: the sequence bit the encoder wrote this tile under
2725 // (stale-header class -- a hard-coded `false` here reads one symbol
2726 // short at the first DC_PRED block once the search offers filter intra).
2727 crate::encode::filter_intra_on(),
2728 &cdef,
2729 &loop_filter,
2730 tx_select,
2731 true,
2732 false,
2733 false,
2734 &loop_restoration,
2735 fctx,
2736 )
2737 .unwrap();
2738 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
2739 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
2740 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
2741 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
2742 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
2743}
2744
2745#[test]
2746fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
2747 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
2748 for (w, h) in [(128usize, 128usize), (192, 128)] {
2749 round_trips(w, h, &[DC_PRED as u8], fctx);
2750 }
2751}
2752
2753/// Every one of the thirteen key-frame intra modes, at their base angle,
2754/// on real (non-flat) content: the mode search picks whichever wins each
2755/// block, so this exercises the directional edge/reach plumbing this
2756/// decoder round adds, not just `DC_PRED`.
2757#[test]
2758fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
2759 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
2760 for (w, h) in [(128usize, 128usize), (192, 128)] {
2761 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
2762 }
2763}
2764
2765/// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
2766/// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
2767/// this decoder round adds.
2768#[test]
2769fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
2770 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size
2771 for (w, h) in [(854usize, 480usize), (216, 96)] {
2772 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
2773 }
2774}
2775
2776/// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
2777/// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
2778/// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
2779/// no whole 16x16/32x32 legally covers the true edge here -- this decoder
2780/// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
2781/// bit, `partition_w8` leaves).
2782#[test]
2783fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
2784 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
2785 for (w, h) in [(40usize, 32usize), (640, 360)] {
2786 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
2787 }
2788}
2789
2790/// A skipped block codes no residual syntax at all (spec 5.11.34):
2791/// straight prediction on every plane. The real key-frame writer never
2792/// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
2793/// `0`), so this constructs the exact symbol sequence a writer that did
2794/// emit it would produce, by hand, and asserts the decoded reconstruction
2795/// is pure DC prediction (mid-grey, with no neighbours) rather than
2796/// refusing.
2797#[test]
2798fn a_skipped_block_decodes_to_pure_prediction() {
2799 let fctx = &crate::decode::FrameCtx::new();
2800 use crate::msac::SymbolEncoder;
2801 let mut cdfs = Cdfs::new(q_ctx_of(40));
2802 let mut enc = SymbolEncoder::new();
2803 // One whole, unsplit 64x64 superblock, coded skip = true.
2804 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
2805 enc.symbol(1, &mut cdfs.skip[0]);
2806 enc.symbol(
2807 DC_PRED,
2808 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
2809 );
2810 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2811 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
2812 let data = enc.finish();
2813 let decoded = decode_key_frame_tile(
2814 &data,
2815 16,
2816 16,
2817 40,
2818 64,
2819 64,
2820 false,
2821 &CdefParams::default(),
2822 &LoopFilterParams::default(),
2823 false,
2824 true,
2825 false,
2826 false,
2827 fctx,
2828 )
2829 .unwrap();
2830 assert!(
2831 decoded.y.iter().all(|&s| s == 128),
2832 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
2833 );
2834}
2835
2836/// lane-av1txbands item 3: the sub-8x8 group whose CHROMA-REFERENCE leaf
2837/// codes `use_intrabc` AND `skip` -- the one route that arms
2838/// [`INTRABC_CHROMA_TX`] and then reads no chroma coefficient at all, so
2839/// before this round the slot stayed armed into the NEXT block's chroma
2840/// read (whose scan and inverse transform it then picked). No encoder in
2841/// hand codes this shape -- `crate::tile::write_intra_mode` hardcodes
2842/// `skip = 0`, and `aomenc`'s RD search never picked it on any of this
2843/// lane's screen-content recipes (the census in
2844/// `lanes/av1txbands.report.md`) -- so the symbol sequence is
2845/// hand-written, exactly as [`a_skipped_block_decodes_to_pure_prediction`]
2846/// does for a skipped block.
2847///
2848/// An 8x8 frame descends the superblock cascade to one 8x8 group without
2849/// coding any partition symbol at the outer levels (the true frame edge
2850/// forces every split), so that group's own `partition_w8` is the first
2851/// symbol the tile reads.
2852#[test]
2853fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
2854 let fctx = &crate::decode::FrameCtx::new();
2855 reset_skipped_intrabc_chroma_arm_hits();
2856 use crate::msac::SymbolEncoder;
2857 let mut cdfs = Cdfs::new(q_ctx_of(40));
2858 let mut enc = SymbolEncoder::new();
2859 // The frame edge forces every split above this group, so its own
2860 // `partition_w8` is the FIRST symbol the tile reads.
2861 enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w8[0]);
2862 // Leaves 0..2: ordinary intra `DC_PRED`, skipped (a skipped block codes
2863 // no coefficient at all, which is what keeps this sequence short).
2864 // `get_skip_txfm_context` over the group: 0 with no skipped neighbour
2865 // yet, 1 once leaf 0 is to the left (leaf 1) or above (leaf 2), and 2
2866 // for the bottom-right leaf, which has both.
2867 for skip_ctx in [0usize, 1, 1] {
2868 enc.symbol(1, &mut cdfs.skip[skip_ctx]);
2869 enc.symbol(0, &mut cdfs.intrabc);
2870 enc.symbol(
2871 DC_PRED,
2872 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
2873 );
2874 }
2875 // Leaf 3 IS the group's chroma reference: skipped AND intrabc.
2876 enc.symbol(1, &mut cdfs.skip[2]);
2877 enc.symbol(1, &mut cdfs.intrabc);
2878 enc.symbol(0, &mut cdfs.dv_joint);
2879 let data = enc.finish();
2880 let _ = decode_key_frame_tile(
2881 &data,
2882 2,
2883 2,
2884 40,
2885 8,
2886 8,
2887 false,
2888 &CdefParams::default(),
2889 &LoopFilterParams::default(),
2890 false,
2891 true,
2892 true,
2893 true,
2894 fctx,
2895 );
2896 assert!(
2897 skipped_intrabc_chroma_arm_hits() >= 1,
2898 "the hand-written tile never reached the skipped-intrabc chroma-reference route"
2899 );
2900 assert!(
2901 fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(),
2902 "the inherited chroma transform slot must be disarmed when its block's chroma \
2903 route ends, or the NEXT block's chroma read picks its scan and inverse transform"
2904 );
2905}
2906
2907/// [`a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx`]'s
2908/// twin for the OTHER sub-8x8 group shape: a `partition_w8` of VERT sends
2909/// the 8x8 to [`decode_leaf_rect8`], whose chroma reference is its second
2910/// (right-hand) 8x4 leaf. Same route, same disarm.
2911#[test]
2912fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx() {
2913 let fctx = &crate::decode::FrameCtx::new();
2914 reset_skipped_intrabc_chroma_arm_hits();
2915 use crate::msac::SymbolEncoder;
2916 let mut cdfs = Cdfs::new(q_ctx_of(40));
2917 let mut enc = SymbolEncoder::new();
2918 enc.symbol(PARTITION_VERT, &mut cdfs.partition_w8[0]);
2919 // Left leaf: skipped intra `DC_PRED`.
2920 enc.symbol(1, &mut cdfs.skip[0]);
2921 enc.symbol(0, &mut cdfs.intrabc);
2922 enc.symbol(
2923 DC_PRED,
2924 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
2925 );
2926 // Right leaf IS the group's chroma reference: skipped AND intrabc.
2927 enc.symbol(1, &mut cdfs.skip[1]);
2928 enc.symbol(1, &mut cdfs.intrabc);
2929 enc.symbol(0, &mut cdfs.dv_joint);
2930 let data = enc.finish();
2931 let _ = decode_key_frame_tile(
2932 &data,
2933 2,
2934 2,
2935 40,
2936 8,
2937 8,
2938 false,
2939 &CdefParams::default(),
2940 &LoopFilterParams::default(),
2941 false,
2942 true,
2943 true,
2944 true,
2945 fctx,
2946 );
2947 assert!(
2948 skipped_intrabc_chroma_arm_hits() >= 1,
2949 "the hand-written tile never reached the skipped-intrabc rect chroma-reference route"
2950 );
2951 assert!(
2952 fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(),
2953 "the inherited chroma transform slot must be disarmed when its block's chroma \
2954 route ends, or the NEXT block's chroma read picks its scan and inverse transform"
2955 );
2956}
2957
2958/// An inter tile's SB-level `part64` used to be read and thrown away
2959/// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
2960/// non-SPLIT value there silently desynced the whole tile instead of
2961/// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
2962/// symbol (never produced by this crate's own encoder, which only ever
2963/// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
2964/// and asserts this decoder refuses by name rather than decoding garbage.
2965#[test]
2966fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
2967 let fctx = &crate::decode::FrameCtx::new();
2968 use crate::msac::SymbolEncoder;
2969 let mut cdfs = Cdfs::new(q_ctx_of(40));
2970 let mut enc = SymbolEncoder::new();
2971 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
2972 let data = enc.finish();
2973 let reference = crate::encode::Picture::grey(64, 64);
2974 let err = decode_inter_frame_tile(
2975 &data,
2976 16,
2977 16,
2978 40,
2979 64,
2980 64,
2981 &last_only(&reference),
2982 &CdefParams::default(),
2983 &LoopFilterParams::default(),
2984 false,
2985 false,
2986 Some(mc::InterpFilterKind::Regular),
2987 false,
2988 false,
2989 // The fixture's own implied header codes the reduced sets (the
2990 // wrapper's old hardcoded value).
2991 true,
2992 false,
2993 None,
2994 false,
2995 fctx,
2996 )
2997 .unwrap_err();
2998 let msg = err.to_string();
2999 // lane-inter4 r1: this fixture's SB value is PARTITION_HORZ, now
3000 // DECODED rather than refused outright; its first 64x32 strip is
3001 // non-skip, so the named refusal is the rectangular-inter-residual
3002 // one. Either string proves what the pin was written for: a non-SPLIT
3003 // superblock never silently decodes as SPLIT.
3004 // lane-r14 r2: the rectangular-residual refusal is gone (a 64x32 strip
3005 // now codes its truncated low-32 coefficient corner), so this
3006 // hand-written fixture walks further still and stops on the limit of
3007 // the FIXTURE rather than of the decoder: it names no reference
3008 // pictures. All three strings prove the one thing this pin exists for
3009 // -- a non-SPLIT superblock never silently decodes as SPLIT.
3010 assert!(
3011 msg.contains("SPLIT")
3012 || msg.contains("rectangular residual coding")
3013 || msg.contains("no picture at this frame's own ref_frame_idx slot"),
3014 "expected the named inter-SB-partition refusal, got: {msg}"
3015 );
3016}
3017
3018// ffmpeg cross-oracle: an independent decoder (not this crate's own
3019// encoder-side reconstruction) agrees with what this module decodes,
3020// duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
3021// name (that module is another lane's territory this round, and the
3022// helpers are `#[cfg(test)]`-private to it).
3023use crate::probe::run_with_stdin;
3024use std::process::{Command, Stdio};
3025
3026/// Whether ffmpeg is on PATH. Absence normally SKIPs, but
3027/// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
3028/// aomenc gate decodes its stream through ffmpeg and is meaningless
3029/// without it -- turns it into a hard failure. Without this the require
3030/// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
3031/// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
3032/// printed SKIP and reported green (class gate-skips-on-its-own-failure).
3033fn have_ffmpeg() -> bool {
3034 let present = Command::new("ffmpeg")
3035 .arg("-version")
3036 .stdout(Stdio::null())
3037 .stderr(Stdio::null())
3038 .status()
3039 .is_ok_and(|s| s.success());
3040 assert!(
3041 present
3042 || (!crate::envflags::env_flag!("EC_AV1_REQUIRE_FFMPEG")
3043 && !crate::envflags::env_flag!("EC_AV1_REQUIRE_AOMENC")),
3044 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
3045 );
3046 present
3047}
3048
3049/// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
3050/// frame's planes, at ffmpeg's own (coded, block-padded) size.
3051fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
3052 let out = run_with_stdin(
3053 Command::new("ffmpeg").args([
3054 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3055 ]),
3056 stream,
3057 );
3058 assert!(
3059 out.status.success(),
3060 "ffmpeg refused the stream: {}",
3061 String::from_utf8_lossy(&out.stderr)
3062 );
3063 let (luma, chroma) = (width * height, width * height / 4);
3064 assert_eq!(
3065 out.stdout.len(),
3066 luma + 2 * chroma,
3067 "expected one 4:2:0 frame"
3068 );
3069 Picture {
3070 width,
3071 height,
3072 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
3073 u: out.stdout[luma..luma + chroma]
3074 .iter()
3075 .map(|&v| u16::from(v))
3076 .collect(),
3077 v: out.stdout[luma + chroma..]
3078 .iter()
3079 .map(|&v| u16::from(v))
3080 .collect(),
3081 }
3082}
3083
3084/// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
3085fn ffmpeg_decode_sequence(
3086 stream: &[u8],
3087 width: usize,
3088 height: usize,
3089 frames: usize,
3090) -> Vec<Picture> {
3091 let out = run_with_stdin(
3092 Command::new("ffmpeg").args([
3093 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3094 ]),
3095 stream,
3096 );
3097 assert!(
3098 out.status.success(),
3099 "ffmpeg refused the stream: {}",
3100 String::from_utf8_lossy(&out.stderr)
3101 );
3102 let (luma, chroma) = (width * height, width * height / 4);
3103 let frame_bytes = luma + 2 * chroma;
3104 assert_eq!(
3105 out.stdout.len(),
3106 frame_bytes * frames,
3107 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
3108 String::from_utf8_lossy(&out.stderr)
3109 );
3110 (0..frames)
3111 .map(|i| {
3112 let base = i * frame_bytes;
3113 Picture {
3114 width,
3115 height,
3116 y: out.stdout[base..base + luma]
3117 .iter()
3118 .map(|&v| u16::from(v))
3119 .collect(),
3120 u: out.stdout[base + luma..base + luma + chroma]
3121 .iter()
3122 .map(|&v| u16::from(v))
3123 .collect(),
3124 v: out.stdout[base + luma + chroma..base + frame_bytes]
3125 .iter()
3126 .map(|&v| u16::from(v))
3127 .collect(),
3128 }
3129 })
3130 .collect()
3131}
3132
3133/// `ffprobe`'s reported coded `width,height` for one OBU stream --
3134/// duplicating `crate::encode`'s own helper (per-call temp naming: the
3135/// test binary runs callers on parallel threads, and a shared name lets
3136/// one test's cleanup race another's still-reading ffprobe --
3137/// pid-keyed-temp-path class).
3138fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3139 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3140 let path = std::env::temp_dir().join(format!(
3141 "ec-av1-decode-probe-{}-{}.obu",
3142 std::process::id(),
3143 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
3144 ));
3145 let _ = std::fs::remove_file(&path);
3146 std::fs::write(&path, stream).expect("writing the probe stream");
3147 let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")
3148 .args([
3149 "-v",
3150 "error",
3151 "-f",
3152 "obu",
3153 "-select_streams",
3154 "v:0",
3155 "-show_entries",
3156 "stream=width,height",
3157 "-of",
3158 "csv=p=0",
3159 ])
3160 .arg(&path), None, |c| c.output())
3161 .expect("ffprobe failed to run");
3162 let _ = std::fs::remove_file(&path);
3163 assert!(
3164 out.status.success(),
3165 "ffprobe refused the stream: {}",
3166 String::from_utf8_lossy(&out.stderr)
3167 );
3168 let text = String::from_utf8_lossy(&out.stdout);
3169 let mut fields = text.trim().split(',');
3170 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
3171 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
3172 (width, height)
3173}
3174
3175/// This module's own decoder against an independent one (ffmpeg), not
3176/// just against this crate's encoder-side reconstruction: both decoders
3177/// read the identical tile bytes, so agreement here rules out a bug this
3178/// crate's own writer and reader could otherwise share.
3179#[test]
3180fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
3181 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3182 if !have_ffmpeg() {
3183 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
3184 return;
3185 }
3186 use crate::encode::encode_key_frame_with_ctx;
3187 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
3188 let picture = round_trip_test_card(width, height);
3189 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3190 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3191 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
3192 let ours = decode_key_frame_tile_lr(
3193 &encoded.tile,
3194 encoded.mi_cols,
3195 encoded.mi_rows,
3196 encoded.base_q_idx,
3197 coded_w,
3198 coded_h,
3199 // lane-fintra: the sequence bit the encoder wrote this tile under
3200 // (stale-header class -- a hard-coded `false` here reads one symbol
3201 // short at the first DC_PRED block once the search offers filter intra).
3202 crate::encode::filter_intra_on(),
3203 &encoded.cdef,
3204 &encoded.loop_filter,
3205 encoded.tx_select,
3206 true,
3207 encoded.screen,
3208 encoded.allow_intrabc,
3209 &encoded.loop_restoration,
3210 fctx,
3211 )
3212 .unwrap();
3213 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
3214 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
3215 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
3216 }
3217}
3218
3219/// lane-fintra: the encoder's own filter-intra blocks, read back by BOTH
3220/// decoders. Two claims in one gate: the stream really exercises the tool
3221/// (the decoder's own `use_filter_intra == 1` counter moves, class
3222/// `gate-blind-to-feature` -- a feature that never fires is not measured),
3223/// and every sample of the frame that carries them matches ffmpeg's
3224/// (class `fixture-proves-symbol-not-signal`: the symbol alone would not
3225/// prove the recursive predictor, the tx_type row or the syntax position
3226/// between the palette colours and the colour-index maps).
3227#[test]
3228fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {
3229 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3230 if !crate::encode::filter_intra_on() {
3231 eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0");
3232 return;
3233 }
3234 if !have_ffmpeg() {
3235 eprintln!("SKIP a_filter_intra_key_frame...: no ffmpeg");
3236 return;
3237 }
3238 let (width, height) = (128usize, 128usize);
3239 // Smooth, slowly curving content: what the recursive filter modes are
3240 // for, and what a plain directional prediction leaves residual on.
3241 let mut picture = crate::encode::Picture::grey(width, height);
3242 for row in 0..height {
3243 for col in 0..width {
3244 // lane-i64: the smooth field alone is now coded as four whole
3245 // 64x64 intra roots, which are too big for filter intra (the
3246 // tool stops at 32x32) -- so the fixture carries a hard step
3247 // through the middle of every superblock, which no 64x64
3248 // prediction fits and which sends the quadrants back to the
3249 // sizes the recursive modes are offered at.
3250 let step = if (row % 64) > 40 && (col % 64) > 24 {
3251 55.0
3252 } else {
3253 0.0
3254 };
3255 let v = 128.0
3256 + 60.0 * ((row as f64) / 9.0).sin() * ((col as f64) / 11.0).cos()
3257 + 8.0 * ((row + col) as f64 / 3.0).sin()
3258 + step;
3259 picture.y[row * width + col] = v.clamp(0.0, 255.0) as u16;
3260 }
3261 }
3262 let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3263 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3264 let before = filter_intra_hits();
3265 let ours = decode_key_frame_tile_lr(
3266 &encoded.tile,
3267 encoded.mi_cols,
3268 encoded.mi_rows,
3269 encoded.base_q_idx,
3270 coded_w,
3271 coded_h,
3272 crate::encode::filter_intra_on(),
3273 &encoded.cdef,
3274 &encoded.loop_filter,
3275 encoded.tx_select,
3276 true,
3277 encoded.screen,
3278 encoded.allow_intrabc,
3279 &encoded.loop_restoration,
3280 fctx,
3281 )
3282 .unwrap();
3283 let fired = filter_intra_hits() - before;
3284 assert!(
3285 fired > 0,
3286 "no block took filter intra -- the gate is blind to the feature"
3287 );
3288 eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks");
3289 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
3290 assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg");
3291 assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg");
3292 assert_eq!(ours.v, ffmpeg_decoded.v, "V vs ffmpeg");
3293 assert_eq!(
3294 ours.y, encoded.reconstruction.y,
3295 "luma vs the encoder's own reconstruction"
3296 );
3297}
3298
3299/// The key frame the encoder writes carries `tx_mode == TxMode::Select`,
3300/// and that header bit is load-bearing for a decode of its tile: read as a
3301/// `TxMode::Largest` frame the very first block misses its `tx_depth`
3302/// symbol and the whole tile desyncs. Pins the shape that broke nine gates
3303/// when `Encoded` had no `tx_select` for them to pass along — a test that
3304/// hardcoded the bit was decoding a different frame header than the one
3305/// the encoder wrote (and than the one `decode_stream`/ffmpeg read off the
3306/// wire).
3307#[test]
3308fn a_key_frames_tile_needs_the_headers_own_tx_select_bit() {
3309 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size
3310 use crate::encode::encode_key_frame_with_ctx;
3311 let (width, height) = (64usize, 64usize);
3312 let picture = round_trip_test_card(width, height);
3313 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3314 assert!(
3315 encoded.tx_select,
3316 "the encoder's key frame no longer codes TxMode::Select -- this \
3317 gate's premise moved, not the decoder"
3318 );
3319 let decode = |tx_select: bool| {
3320 decode_key_frame_tile_lr(
3321 &encoded.tile,
3322 encoded.mi_cols,
3323 encoded.mi_rows,
3324 encoded.base_q_idx,
3325 width as u32,
3326 height as u32,
3327 // lane-fintra: the sequence bit the encoder wrote this tile under
3328 // (stale-header class -- a hard-coded `false` here reads one symbol
3329 // short at the first DC_PRED block once the search offers filter intra).
3330 crate::encode::filter_intra_on(),
3331 &encoded.cdef,
3332 &encoded.loop_filter,
3333 tx_select,
3334 true,
3335 encoded.screen,
3336 encoded.allow_intrabc,
3337 &encoded.loop_restoration,
3338 fctx,
3339 )
3340 };
3341 let right = decode(true).expect("the header's own tx_mode decodes");
3342 assert_eq!(right.y, encoded.reconstruction.y, "luma under tx_select");
3343 assert_eq!(right.u, encoded.reconstruction.u, "U under tx_select");
3344 assert_eq!(right.v, encoded.reconstruction.v, "V under tx_select");
3345 // The wrong bit either refuses or reconstructs something else; what it
3346 // must never do is agree, which would mean the bit codes nothing.
3347 if let Ok(wrong) = decode(false) {
3348 assert_ne!(
3349 wrong.y, encoded.reconstruction.y,
3350 "reading a TxMode::Select tile as Largest agreed -- the \
3351 tx_depth symbols are not being coded"
3352 );
3353 }
3354}
3355
3356fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
3357 let mut picture = crate::encode::Picture::grey(width, height);
3358 for row in 0..height {
3359 for col in 0..width {
3360 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
3361 }
3362 }
3363 for row in 0..height / 2 {
3364 for col in 0..width / 2 {
3365 let i = row * width / 2 + col;
3366 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
3367 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
3368 }
3369 }
3370 picture
3371}
3372
3373fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
3374 let mut picture = crate::encode::Picture::grey(width, height);
3375 for y in 0..height {
3376 for x in 0..width {
3377 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
3378 let gradient = sx * 200.0 / width as f64;
3379 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
3380 }
3381 }
3382 for y in 0..height / 2 {
3383 for x in 0..width / 2 {
3384 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
3385 let i = y * width / 2 + x;
3386 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
3387 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
3388 }
3389 }
3390 picture
3391}
3392
3393/// A GOP (one key frame plus several inter frames, each panned so its
3394/// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
3395/// `(0, 0)` no-op) decodes bit-exact against the encoder's own
3396/// reconstruction, frame by frame, chaining each decoded frame straight
3397/// into the next as its reference -- exactly the single-slot DPB
3398/// [`crate::encode::encode_sequence`] itself threads.
3399fn gop_round_trips(width: usize, height: usize, fctx: &crate::decode::FrameCtx) {
3400 use crate::encode::encode_sequence_with_ctx;
3401 let pictures: Vec<_> = (0..4)
3402 .map(|i| panned_test_card(width, height, i * 3))
3403 .collect();
3404 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3405 assert_eq!(encoded.frames.len(), 4);
3406
3407 let key = &encoded.frames[0];
3408 let mut reference = decode_key_frame_tile_lr(
3409 &key.tile,
3410 key.mi_cols,
3411 key.mi_rows,
3412 key.base_q_idx,
3413 width as u32,
3414 height as u32,
3415 // lane-fintra: the sequence bit the encoder wrote this tile under
3416 // (stale-header class -- a hard-coded `false` here reads one symbol
3417 // short at the first DC_PRED block once the search offers filter intra).
3418 crate::encode::filter_intra_on(),
3419 &key.cdef,
3420 &key.loop_filter,
3421 key.tx_select,
3422 true,
3423 // This key frame's own `allow_screen_content_tools`: its intra
3424 // blocks carry the palette syntax under it (stale-header class).
3425 key.screen,
3426 // ... and its own `allow_intrabc`: every intra block carries a
3427 // `use_intrabc` symbol under it (stale-header class).
3428 key.allow_intrabc,
3429 &key.loop_restoration,
3430 fctx,
3431 )
3432 .unwrap();
3433 assert_eq!(
3434 reference.y, key.reconstruction.y,
3435 "{width}x{height} frame 0 luma"
3436 );
3437 assert_eq!(
3438 reference.u, key.reconstruction.u,
3439 "{width}x{height} frame 0 U"
3440 );
3441 assert_eq!(
3442 reference.v, key.reconstruction.v,
3443 "{width}x{height} frame 0 V"
3444 );
3445
3446 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
3447 let decoded = decode_inter_frame_tile_lr(
3448 &frame.tile,
3449 frame.mi_cols,
3450 frame.mi_rows,
3451 frame.base_q_idx,
3452 width as u32,
3453 height as u32,
3454 &last_golden_altref(
3455 &reference,
3456 &encoded.frames[0].reconstruction,
3457 (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
3458 ),
3459 &frame.cdef,
3460 &frame.loop_filter,
3461 false,
3462 false,
3463 Some(mc::InterpFilterKind::Regular),
3464 false,
3465 // The encoder's own `reference_select` (spec 5.9.22): these
3466 // GOP round trips decode a tile the ENCODER wrote, so the
3467 // header bit must be the one it wrote, not a hard-coded
3468 // `false` (stale-header class -- a `reference_select` stream
3469 // reads a `comp_mode` symbol this decode would skip).
3470 crate::encode::reference_select(),
3471 // lane-intertx: this frame's own `reduced_tx_set` -- the
3472 // bit the chroma inheritance reduces against. The wrapper
3473 // used to guess `true`, which mis-derived every inherited
3474 // chroma type on a screen frame's widened inter blocks
3475 // (stale-header class).
3476 frame.reduced_tx_set,
3477 frame.tx_select,
3478 &frame.loop_restoration,
3479 Some(frame.start_cdfs.0.clone()),
3480 NO_SIGN_BIAS,
3481 // This frame's own `allow_screen_content_tools`, off the
3482 // `Encoded` the encoder handed back (stale-header class).
3483 frame.screen,
3484 // Same stale-header class: the bit that makes this frame's
3485 // inter blocks carry a `motion_mode` symbol.
3486 frame.switchable_motion_mode,
3487 // These GOP round trips decode a tile the encoder wrote, so
3488 // the warp bit must be the one it wrote too (lane-av1obmc2);
3489 // the encoder only sets it under `EC_AV1_WARP`.
3490 crate::encode::warp_on(),
3491 // lane-fintra: the sequence bit the encoder wrote this tile
3492 // under -- same stale-header class as the warp bit above.
3493 crate::encode::filter_intra_on(),
3494 frame.delta,
3495 fctx,
3496 )
3497 .unwrap();
3498 assert_eq!(
3499 decoded.y, frame.reconstruction.y,
3500 "{width}x{height} frame {i} luma"
3501 );
3502 assert_eq!(
3503 decoded.u, frame.reconstruction.u,
3504 "{width}x{height} frame {i} U"
3505 );
3506 assert_eq!(
3507 decoded.v, frame.reconstruction.v,
3508 "{width}x{height} frame {i} V"
3509 );
3510 reference = decoded;
3511 }
3512}
3513
3514#[test]
3515fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
3516 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3517 gop_round_trips(128, 64, fctx);
3518}
3519
3520/// Same claim, at a size that is not a whole number of 32x32 blocks
3521/// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
3522/// split path is exercised too.
3523#[test]
3524fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
3525 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3526 gop_round_trips(216, 96, fctx);
3527}
3528
3529/// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
3530/// this module does, frame for frame.
3531/// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
3532/// MV stack's *second* candidate (`near_mv`), not its first
3533/// (`nearest_mv`) -- a hand-built symbol stream drives
3534/// [`decode_inter_block`] directly, since this crate's own encoder never
3535/// writes NEARMV (round 3: it never chooses the mode).
3536#[test]
3537fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
3538 let fctx = &crate::decode::FrameCtx::new();
3539 use crate::msac::SymbolEncoder;
3540 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
3541
3542 const LAST_FRAME: i8 = 1;
3543 let (mi_cols, mi_rows) = (12u32, 12u32);
3544 let side = 16usize; // one 16x16 leaf block
3545 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
3546 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3547 let bw4 = side / 4;
3548
3549 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
3550 let (above_mv, left_mv) = ((4, 4), (8, 8));
3551 let neighbour = |mv: (i32, i32)| MiInfo {
3552 is_inter: true,
3553 ref_frame: LAST_FRAME,
3554 ref_frame1: NO_REF1,
3555 mv1: (0, 0),
3556 mv: mv16(mv),
3557 is_new_mv: false,
3558 size: 1,
3559 size_h: 1,
3560 is_global_mv0: false,
3561 is_global_mv1: false,
3562 };
3563 for col in mi_col..mi_col + bw4 {
3564 grid.set(mi_row - 1, col, neighbour(above_mv));
3565 }
3566 for row in mi_row..mi_row + bw4 {
3567 grid.set(row, mi_col - 1, neighbour(left_mv));
3568 }
3569
3570 let stack = find_mv_stack(
3571 &grid,
3572 mi_row,
3573 mi_col,
3574 bw4,
3575 bw4,
3576 LAST_FRAME,
3577 mi_cols as usize,
3578 mi_rows as usize,
3579 );
3580 // Sanity on the test's own setup, not the code under test: two equal-
3581 // weight candidates keep scan order (above, then left -- module doc).
3582 assert_eq!(stack.entries.len(), 2);
3583 assert_eq!(stack.nearest_mv, above_mv);
3584 assert_eq!(stack.near_mv, left_mv);
3585
3586 let (skip_ctx, ii_ctx, sr_ctx) = (
3587 0usize,
3588 intra_inter_ctx(true, true, false, false),
3589 single_ref_ctx(false),
3590 );
3591
3592 let mut cdfs = Cdfs::new(q_ctx_of(100));
3593 let mut enc = SymbolEncoder::new();
3594 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
3595 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
3596 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
3597 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
3598 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
3599 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
3600 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
3601 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
3602 let data = enc.finish();
3603
3604 let (width, height) = (64usize, 64usize);
3605 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
3606 let chroma: Vec<u16> = ref_pattern
3607 .iter()
3608 .step_by(2)
3609 .take((width / 2) * (height / 2))
3610 .copied()
3611 .collect();
3612 let reference = Picture {
3613 width,
3614 height,
3615 y: ref_pattern.clone(),
3616 u: chroma.clone(),
3617 v: chroma,
3618 };
3619 let refpix = &last_only(&reference);
3620 let ref_y = whole_plane(&reference.y, width, height);
3621
3622 let mut y = PlaneBuf {
3623 data: std::borrow::Cow::Owned(vec![0u16; width * height]),
3624 width,
3625 height,
3626 true_width: width,
3627 true_height: height,
3628 tile_x0: 0,
3629 tile_y0: 0,
3630 tile_x1: width,
3631 tile_y1: height,
3632 plane: 0,
3633 };
3634 let mut u = PlaneBuf {
3635 data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]),
3636 width: width / 2,
3637 height: height / 2,
3638 true_width: width / 2,
3639 true_height: height / 2,
3640 tile_x0: 0,
3641 tile_y0: 0,
3642 tile_x1: width / 2,
3643 tile_y1: height / 2,
3644 plane: 1,
3645 };
3646 let mut v = PlaneBuf {
3647 data: std::borrow::Cow::Owned(vec![0u16; (width / 2) * (height / 2)]),
3648 width: width / 2,
3649 height: height / 2,
3650 true_width: width / 2,
3651 true_height: height / 2,
3652 tile_x0: 0,
3653 tile_y0: 0,
3654 tile_x1: width / 2,
3655 tile_y1: height / 2,
3656 plane: 2,
3657 };
3658
3659 let mut cdfs = Cdfs::new(q_ctx_of(100));
3660 let mut dec = SymbolDecoder::new(&data);
3661 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize, fctx);
3662 decode_inter_block(
3663 &mut dec,
3664 &mut cdfs,
3665 &mut neighbours,
3666 &mut grid,
3667 sub16_to_mi((r, c)),
3668 side,
3669 mi_cols,
3670 mi_rows,
3671 &mut y,
3672 &mut u,
3673 &mut v,
3674 refpix,
3675 &NO_SIGN_BIAS,
3676 &[ec_av1_syntax::WarpParams::default(); 7],
3677 100,
3678 TxbSet::Luma16,
3679 TxbSet::Luma16Inter,
3680 TxbSet::Chroma8,
3681 TX16,
3682 TX8,
3683 &[],
3684 &[],
3685 0,
3686 false,
3687 false,
3688 Some(mc::InterpFilterKind::Regular),
3689 false,
3690 None,
3691 false,
3692 false,
3693 false,
3694 false,
3695 0,
3696 0,
3697 [0; 7],
3698 false,
3699 [0; 2],
3700 false,
3701 false,
3702 false,
3703 side,
3704 side,
3705 false,
3706 (width, height),
3707 fctx,
3708 )
3709 .unwrap();
3710 // lane-wave1: a direct caller of the block decoder RECORDS its writes
3711 // (the tile decoder is what replays them), so this gate replays its
3712 // own before reading the plane back.
3713
3714 let (px, py) = (c * SUB, r * SUB);
3715 let mut want_near = vec![0u16; side * side];
3716 crate::mc::predict(
3717 &ref_y.data,
3718 ref_y.width,
3719 ref_y.true_width,
3720 ref_y.true_height,
3721 mv_to_q4(px, left_mv.1, 0),
3722 mv_to_q4(py, left_mv.0, 0),
3723 side,
3724 side,
3725 &mut want_near,
3726 fctx,
3727 );
3728 let mut want_nearest = vec![0u16; side * side];
3729 crate::mc::predict(
3730 &ref_y.data,
3731 ref_y.width,
3732 ref_y.true_width,
3733 ref_y.true_height,
3734 mv_to_q4(px, above_mv.1, 0),
3735 mv_to_q4(py, above_mv.0, 0),
3736 side,
3737 side,
3738 &mut want_nearest,
3739 fctx,
3740 );
3741 assert_ne!(
3742 want_near, want_nearest,
3743 "test setup: the two candidate MVs must predict differently"
3744 );
3745
3746 let mut got = vec![0u16; side * side];
3747 for row in 0..side {
3748 got[row * side..(row + 1) * side]
3749 .copy_from_slice(&y.data[(py + row) * y.width + px..(py + row) * y.width + px + side]);
3750 }
3751 assert_eq!(
3752 got, want_near,
3753 "NEARMV predicted from the wrong stack entry"
3754 );
3755}
3756
3757#[test]
3758fn ffmpeg_and_this_decoder_agree_on_a_gop() {
3759 let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3760 if !have_ffmpeg() {
3761 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
3762 return;
3763 }
3764 use crate::encode::encode_sequence_with_ctx;
3765 let (width, height) = (128usize, 64usize);
3766 let pictures: Vec<_> = (0..3)
3767 .map(|i| panned_test_card(width, height, i * 3))
3768 .collect();
3769 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3770 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
3771 let ffmpeg_frames =
3772 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
3773
3774 let key = &encoded.frames[0];
3775 let mut reference = decode_key_frame_tile_lr(
3776 &key.tile,
3777 key.mi_cols,
3778 key.mi_rows,
3779 key.base_q_idx,
3780 coded_w,
3781 coded_h,
3782 // lane-fintra: the sequence bit the encoder wrote this tile under
3783 // (stale-header class -- a hard-coded `false` here reads one symbol
3784 // short at the first DC_PRED block once the search offers filter intra).
3785 crate::encode::filter_intra_on(),
3786 &key.cdef,
3787 &key.loop_filter,
3788 key.tx_select,
3789 true,
3790 // This key frame's own `allow_screen_content_tools`: its intra
3791 // blocks carry the palette syntax under it (stale-header class).
3792 key.screen,
3793 // ... and its own `allow_intrabc`: every intra block carries a
3794 // `use_intrabc` symbol under it (stale-header class).
3795 key.allow_intrabc,
3796 &key.loop_restoration,
3797 fctx,
3798 )
3799 .unwrap();
3800 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
3801
3802 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
3803 let decoded = decode_inter_frame_tile_lr(
3804 &frame.tile,
3805 frame.mi_cols,
3806 frame.mi_rows,
3807 frame.base_q_idx,
3808 coded_w,
3809 coded_h,
3810 &last_golden_altref(
3811 &reference,
3812 &encoded.frames[0].reconstruction,
3813 (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
3814 ),
3815 &frame.cdef,
3816 &frame.loop_filter,
3817 false,
3818 false,
3819 Some(mc::InterpFilterKind::Regular),
3820 false,
3821 // The encoder's own `reference_select` (spec 5.9.22): these
3822 // GOP round trips decode a tile the ENCODER wrote, so the
3823 // header bit must be the one it wrote, not a hard-coded
3824 crate::encode::reference_select(),
3825 // lane-intertx: the frame's own `reduced_tx_set` -- see the
3826 // first GOP round trip's note.
3827 frame.reduced_tx_set,
3828 frame.tx_select,
3829 &frame.loop_restoration,
3830 Some(frame.start_cdfs.0.clone()),
3831 NO_SIGN_BIAS,
3832 // This frame's own `allow_screen_content_tools`, off the
3833 // `Encoded` the encoder handed back (stale-header class).
3834 frame.screen,
3835 // Same stale-header class: the bit that makes this frame's
3836 // inter blocks carry a `motion_mode` symbol.
3837 frame.switchable_motion_mode,
3838 // These GOP round trips decode a tile the encoder wrote, so
3839 // the warp bit must be the one it wrote too (lane-av1obmc2);
3840 // the encoder only sets it under `EC_AV1_WARP`.
3841 crate::encode::warp_on(),
3842 // lane-fintra: the sequence bit the encoder wrote this tile
3843 // under -- same stale-header class as the warp bit above.
3844 crate::encode::filter_intra_on(),
3845 frame.delta,
3846 fctx,
3847 )
3848 .unwrap();
3849 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
3850 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
3851 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
3852 reference = decoded;
3853 }
3854}