forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tests.rs4022 lines, 186.4 KiBHistoryRawDownload
1 use super::more_tests::*;
2
3 /// Every (site, frame type, block side) the census can be called with
4 /// lands in its own ten-counter bucket, inside the array (class
5 /// `enumerate-table-domain`: an off-by-one here would silently add two
6 /// sites' trials together).
7 #[test]
8 fn the_split_census_buckets_are_distinct_and_in_bounds() {
9 let mut seen = std::collections::BTreeSet::new();
10 for site in 0..2 {
11 for key in [true, false] {
12 for side in [8usize, 16, 32, 64] {
13 let base = super::split_census_base(site, key, side);
14 assert!(
15 base + 10 <= super::SPLIT_CENSUS.len(),
16 "{site} {key} {side}"
17 );
18 assert!(seen.insert(base), "{site} {key} {side} collides");
19 }
20 }
21 }
22 assert_eq!(seen.len(), 16);
23 }
24
25 /// An [`crate::mvstack::MvStack`] with every context at zero and no
26 /// neighbours, for the pricer tests below to fill the one band each of
27 /// them is about.
28 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
29 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
30 /// against the same stack -- an offer the writer clamps prices the
31 /// residual against a predictor the decoder never derives, which is the
32 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
33 /// side, so the stream stays legal; here the pricer's own offer set is
34 /// enumerated, class `enumerate-table-domain`).
35 ///
36 /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
37 /// r2, 2026-09-29). It replaces the clip gate
38 /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
39 /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
40 /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
41 /// while the invariant above holds, so no recipe could ever satisfy it.
42 /// Deletion loses no coverage on either half:
43 /// * the clamp half -- this test IS the coverage, and it is strictly
44 /// stronger than any clip gate: it enumerates the pricer's whole offer
45 /// set against the writer's rule for every stack size 0..=4, and larger
46 /// stacks add entries the pricers never offer (`best_new_mv_syntax`
47 /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
48 /// unreachable at ANY stack size), which is why 0..=4 bounds the
49 /// domain rather than sampling it;
50 /// * the pixel half -- the deleted gate's own decode-vs-encoder-
51 /// reconstruction compare on a 1280x768 sb128 sequence is already made
52 /// four times over, by `a_128_superblock_clip_whose_root_search_codes_
53 /// 128x128_blocks_decodes_exact`,
54 /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
55 /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
56 /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
57 /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
58 /// ffmpeg compare).
59 ///
60 /// MEASURED before deleting (153 clip x size x frame-count x q combinations,
61 /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
62 /// the clip was never the variable: widening `best_new_mv_syntax`'s offer
63 /// set to `0..5` fires the counter immediately (9/2/2/1 on
64 /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
65 /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
66 /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
67 /// (`deferred(unblock: the DRL owner widens the pricer past the writer's
68 /// `start + 2` ceiling, or retires the counter)`) -- this test will go red
69 /// the moment either happens, which is the signal to re-open the cell.
70 ///
71 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
72 #[test]
73 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
74 for n in 0..=4usize {
75 let mut stack = bare_stack();
76 for i in 0..n {
77 stack.entries.push(crate::mvstack::StackEntry {
78 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
79 weight: 1,
80 });
81 stack.drl_ctx.push(0);
82 }
83 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
84 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
85 stack.pred_mv = stack.nearest_mv;
86 // Aim the vector at each entry in turn, so every index the offer
87 // set holds is the one that wins at least once.
88 for target in 0..n.max(1) {
89 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
90 let (_, idx) =
91 best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
92 let idx = usize::from(idx);
93 assert_eq!(
94 crate::tile::signalled_drl_idx(n, 0, idx),
95 idx,
96 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
97 );
98 }
99 // The NEARMV arm's own offer set (`search_inter_block`,
100 // `search_skip_64`): indices 1 and 2, offered only when the stack
101 // really holds that entry.
102 for idx in 1..=2usize {
103 if stack.entries.get(idx).is_some() {
104 assert_eq!(
105 crate::tile::signalled_drl_idx(n, 1, idx),
106 idx,
107 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
108 );
109 }
110 }
111 }
112 }
113
114 pub(super) fn bare_stack() -> crate::mvstack::MvStack {
115 crate::mvstack::MvStack {
116 entries: Default::default(),
117 nearest_mv: (0, 0),
118 near_mv: (0, 0),
119 pred_mv: (0, 0),
120 new_mv_ctx: 0,
121 ref_mv_ctx: 0,
122 zero_mv_ctx: 0,
123 drl_ctx: Default::default(),
124 above_refs: (None, None),
125 left_refs: (None, None),
126 above_nbr: None,
127 left_nbr: None,
128 above_skip: false,
129 left_skip: false,
130 }
131 }
132
133 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
134 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
135 /// own neighbour-derived context. Red before lane-ctx, where the pricer
136 /// spent four constants at CDF row 0 that assumed the pair was
137 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
138 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
139 #[test]
140 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
141 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
142 use crate::encode::symbol_bits as b;
143 use crate::mvstack::{
144 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
145 LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
146 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
147 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
148 };
149 // (pair, unidirectional?, the tree's symbols as (table, p index,
150 // context selector, value)) -- transcribed from the writer.
151 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
152 type Sym = (char, usize, usize, usize);
153 let cases: [((i8, i8), bool, &[Sym]); 7] = [
154 (
155 (LAST_FRAME, LAST2_FRAME),
156 true,
157 &[('u', 0, 1, 0), ('u', 1, 7, 0)],
158 ),
159 (
160 (LAST_FRAME, LAST3_FRAME),
161 true,
162 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
163 ),
164 (
165 (LAST_FRAME, GOLDEN_FRAME),
166 true,
167 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
168 ),
169 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
170 (
171 (LAST_FRAME, ALTREF_FRAME),
172 false,
173 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
174 ),
175 (
176 (LAST_FRAME, BWDREF_FRAME),
177 false,
178 &[
179 ('c', 0, 3, 0),
180 ('c', 1, 4, 0),
181 ('b', 0, 2, 0),
182 ('b', 1, 6, 0),
183 ],
184 ),
185 (
186 (LAST_FRAME, ALTREF2_FRAME),
187 false,
188 &[
189 ('c', 0, 3, 0),
190 ('c', 1, 4, 0),
191 ('b', 0, 2, 0),
192 ('b', 1, 6, 1),
193 ],
194 ),
195 ];
196 let nbr = |ref0, ref1: Option<i8>| {
197 Some(NeighbourRef {
198 is_inter: true,
199 ref0,
200 ref1,
201 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
202 })
203 };
204 // No neighbours (every context zero), then a mixed pair that puts the
205 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
206 for (above_nbr, left_nbr, above_refs, left_refs) in [
207 (None, None, (None, None), (None, None)),
208 (
209 nbr(LAST_FRAME, None),
210 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
211 (Some(LAST_FRAME), None),
212 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
213 ),
214 ] {
215 let stack = crate::mvstack::MvStack {
216 above_nbr,
217 left_nbr,
218 above_refs,
219 left_refs,
220 ..bare_stack()
221 };
222 let (a, a1) = above_refs;
223 let (l, l1) = left_refs;
224 let ctx_of = |sel: usize| match sel {
225 1 => single_ref_p1_ctx(a, a1, l, l1),
226 2 => single_ref_p2_ctx(a, a1, l, l1),
227 3 => single_ref_p3_ctx(a, a1, l, l1),
228 4 => single_ref_p4_ctx(a, a1, l, l1),
229 5 => single_ref_p5_ctx(a, a1, l, l1),
230 6 => single_ref_p6_ctx(a, a1, l, l1),
231 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
232 };
233 for (pair, unidir, symbols) in cases {
234 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
235 + b(
236 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
237 usize::from(!unidir),
238 );
239 for &(table, p, sel, v) in symbols {
240 let row = ctx_of(sel);
241 want += match table {
242 'u' => b(&UNI_COMP_REF[row][p], v),
243 'c' => b(&COMP_REF[row][p], v),
244 _ => b(&COMP_BWDREF[row][p], v),
245 };
246 }
247 let got = super::compound_ref_bits(pair, &stack);
248 assert!(
249 (got - want).abs() < 1e-9,
250 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
251 priced {got} bits, writer codes {want}"
252 );
253 }
254 }
255 }
256
257 /// The `skip` and `is_inter` symbols are priced at the SAME context
258 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
259 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
260 /// on every neighbour configuration whose context is not zero (class
261 /// pricer-context-zero).
262 #[test]
263 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
264 use crate::cdf::{INTRA_INTER, SKIP};
265 use crate::encode::symbol_bits as b;
266 use crate::mvstack::NeighbourRef;
267 let nbr = |is_inter| NeighbourRef {
268 is_inter,
269 ref0: if is_inter {
270 crate::mvstack::LAST_FRAME
271 } else {
272 0
273 },
274 ref1: None,
275 uni: false,
276 };
277 for (above, left, above_skip, left_skip) in [
278 (None, None, false, false),
279 (Some(nbr(true)), Some(nbr(true)), true, false),
280 (Some(nbr(false)), Some(nbr(false)), true, true),
281 (Some(nbr(false)), None, false, true),
282 (None, Some(nbr(true)), true, true),
283 ] {
284 let stack = crate::mvstack::MvStack {
285 above_nbr: above,
286 left_nbr: left,
287 above_skip,
288 left_skip,
289 ..bare_stack()
290 };
291 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
292 let ii_ctx = crate::tile::intra_inter_ctx(
293 above.is_some(),
294 left.is_some(),
295 above.is_some_and(|n| n.is_inter),
296 left.is_some_and(|n| n.is_inter),
297 );
298 for v in [false, true] {
299 let (got, want) = (
300 super::skip_bits_at(&stack, v),
301 b(&SKIP[skip_ctx], usize::from(v)),
302 );
303 assert!(
304 (got - want).abs() < 1e-9,
305 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
306 );
307 let (got, want) = (
308 super::intra_inter_bits_at(&stack, v),
309 b(&INTRA_INTER[ii_ctx], usize::from(v)),
310 );
311 assert!(
312 (got - want).abs() < 1e-9,
313 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
314 );
315 }
316 }
317 }
318
319 /// [`super::single_ref_bits`] pays exactly what tile.rs'
320 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
321 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
322 /// the context that symbol's own `single_ref_p*_ctx` derives from the
323 /// block's above/left neighbours. Red before lane-pricer, where every
324 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
325 #[test]
326 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
327 use crate::cdf::SINGLE_REF as SR;
328 use crate::encode::symbol_bits as b;
329 use crate::mvstack::{
330 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
331 LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
332 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
333 };
334 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
335 above_refs,
336 left_refs,
337 above_nbr,
338 left_nbr,
339 ..bare_stack()
340 };
341 let nbr = |ref0, ref1| {
342 Some(crate::mvstack::NeighbourRef {
343 is_inter: true,
344 ref0,
345 ref1,
346 uni: false,
347 })
348 };
349 // (reference, the symbols `write_single_ref` emits as (p index, value))
350 let cases: [(i8, &[(usize, usize)]); 7] = [
351 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
352 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
353 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
354 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
355 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
356 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
357 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
358 ];
359 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
360 // that puts every p* context on a different row -- the second with a
361 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
362 // off row 0.
363 for (above_refs, left_refs, above_nbr, left_nbr) in [
364 ((None, None), (None, None), None, None),
365 (
366 (Some(LAST_FRAME), None),
367 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
368 nbr(LAST_FRAME, None),
369 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
370 ),
371 ] {
372 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
373 let (a, a1) = above_refs;
374 let (l, l1) = left_refs;
375 let ctx_of = |p: usize| match p {
376 0 => single_ref_p1_ctx(a, a1, l, l1),
377 1 => single_ref_p2_ctx(a, a1, l, l1),
378 2 => single_ref_p3_ctx(a, a1, l, l1),
379 3 => single_ref_p4_ctx(a, a1, l, l1),
380 4 => single_ref_p5_ctx(a, a1, l, l1),
381 _ => single_ref_p6_ctx(a, a1, l, l1),
382 };
383 for (ref_frame, symbols) in cases {
384 // Plus the `comp_mode = 0` symbol the writer codes ahead of
385 // the reference syntax on a `reference_select` frame.
386 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
387 if super::reference_select() {
388 want += b(
389 &crate::cdf::COMP_MODE
390 [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
391 0,
392 );
393 }
394 let got = super::single_ref_bits(ref_frame, &stack);
395 assert!(
396 (got - want).abs() < 1e-9,
397 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
398 priced {got} bits, writer codes {want}"
399 );
400 }
401 }
402 }
403
404 /// lane-av1tpl2's propagated map, on the two properties every decision
405 /// under it rests on: a frame the whole lookahead window repeats exactly
406 /// (uniform texture) leans on every cell alike, so every factor is 1 and
407 /// the weighting is a no-op; and where the window really does save bits
408 /// by predicting -- the textured half of a frame whose other half is
409 /// flat -- the factor FALLS below 1, i.e. that half is coded more
410 /// distortion-averse than the half nothing gains from.
411 /// The distortion metric itself (lane-sse): a block the true frame edge
412 /// cuts through is scored over its INSIDE part only, so a difference that
413 /// lives entirely in the padding costs nothing and a block wholly past
414 /// the edge scores zero. Before this, the search ranked modes,
415 /// transforms and partition trees on samples the display crop throws
416 /// away -- which lane-b64b had fixed for the 64x64 root alone.
417 #[test]
418 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
419 // A 40x40 true frame on a 64x64 padded coding surface.
420 let source = vec![10u8; 64 * 64];
421 let plane = fresh_plane(&source, 64, 64, 40, 40);
422 let mut reconstruction = vec![10u8; 64 * 64];
423 // Off by 190 at (50, 50) -- past the true edge in both axes.
424 reconstruction[50 * 64 + 50] = 200;
425 assert_eq!(
426 plane.block_sse(0, 0, 64, &reconstruction),
427 0.0,
428 "padding was scored"
429 );
430 // Off by 10 at (39, 39) -- the last sample the decoder shows.
431 reconstruction[39 * 64 + 39] = 20;
432 assert_eq!(
433 plane.block_sse(0, 0, 64, &reconstruction),
434 100.0,
435 "inside was not scored"
436 );
437 // A 16x16 block whose every sample is padding.
438 let block = vec![200u8; 16 * 16];
439 assert_eq!(
440 plane.block_sse(48, 0, 16, &block),
441 0.0,
442 "a block past the edge scored"
443 );
444 // A 16x16 block the edge cuts: 8 of its columns are inside.
445 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
446 }
447
448 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
449 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
450 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
451 #[test]
452 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
453 let (base, res) = (162u8, 4i32);
454 let rf = 2.0;
455 // A superblock the window leans on more than the frame average is
456 // coded FINER (lower qindex); a slack one coarser; the average one
457 // exactly at the base.
458 assert!(
459 super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
460 "leaned-on SB must go finer"
461 );
462 assert!(
463 super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
464 "idle SB must go coarser"
465 );
466 assert_eq!(
467 super::deltaq_libaom(base, rf, rf, 1.0, res),
468 base,
469 "the average SB moves 0"
470 );
471 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
472 let max = ((res * 9 - 1) / res) * res;
473 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
474 for k in [0.5f64, 1.0, 1.5] {
475 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
476 let d = q - i32::from(base);
477 assert_eq!(
478 d % res,
479 0,
480 "r={r} k={k}: offset {d} is not a whole {res}-step"
481 );
482 assert!(
483 d.abs() <= max,
484 "r={r} k={k}: offset {d} past libaom's +-{max}"
485 );
486 }
487 }
488 // The clamp is REACHED from both ends, so the bound is a real bound
489 // and not a formula that never gets there.
490 assert_eq!(
491 i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
492 -max
493 );
494 assert_eq!(
495 i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
496 max
497 );
498 // A stronger `k` never moves less than a weaker one.
499 let d = |k: f64| {
500 (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs()
501 };
502 assert!(
503 d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
504 "strength must be monotone: {} {} {}",
505 d(0.5),
506 d(1.0),
507 d(1.5)
508 );
509 // The frame reference is libaom's log-mean: flat in, the same value out.
510 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
511 }
512
513 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
514 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
515 /// shipped default, and the multiplier reaches the strength.
516 #[test]
517 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
518 let d = crate::speed::DQ_LEVEL_K;
519 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
520 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
521 // Short and broken fields fall back per SLOT, not per spec.
522 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
523 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
524 assert_eq!(super::DqLevel::TopArf as usize, 0);
525 assert_eq!(super::DqLevel::MidArf as usize, 1);
526 assert_eq!(super::DqLevel::Leaf as usize, 2);
527 }
528
529 #[test]
530 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
531 // Four 64x64 superblocks across: the shipped map forms its ratio per
532 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
533 // only ever produce one ratio -- and one ratio, mean-normalised, is
534 // the flat map, whatever the content underneath it.
535 let (w, h) = (256usize, 64usize);
536 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
537 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
538 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
539 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
540 for (i, &v) in f.iter().enumerate() {
541 assert!(
542 (v - 1.0).abs() < 1e-6,
543 "cell {i} factor {v}, a flat map must move no lambda"
544 );
545 }
546
547 // Left half textured, right half constant: the window saves bits
548 // predicting the left half and nothing at all on the right.
549 let split: Vec<u8> = (0..w * h)
550 .map(|i| {
551 if i % w < w / 2 {
552 ((i * 37) % 251) as u8
553 } else {
554 128
555 }
556 })
557 .collect();
558 let frames: Vec<&[u8]> = vec![&split, &split, &split];
559 let cells_x = w / 16;
560 for k in [0.25f64, 0.5, 1.0, 2.0] {
561 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
562 for r in 0..h / 16 {
563 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
564 assert!(
565 lean < 1.0,
566 "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
567 );
568 assert!(
569 idle > 1.0,
570 "k={k} row {r}: idle cell factor {idle} must be > 1"
571 );
572 }
573 }
574 }
575
576 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
577 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
578 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
579 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
580 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
581 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
582 /// only a quarter of the 16x8 table and read the wrong byte for every
583 /// block row but the first (silently wrong above-right/below-left
584 /// availability -- wrong pixels, no error).
585 #[test]
586 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
587 for (bw, bh) in [
588 (16usize, 8usize),
589 (8, 16),
590 (32, 16),
591 (16, 32),
592 (64, 32),
593 (32, 64),
594 ] {
595 let (bw_log2, bh_log2) = (
596 (bw / 4).trailing_zeros() as usize,
597 (bh / 4).trailing_zeros() as usize,
598 );
599 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
600 for (name, table) in [
601 ("has_tr", rect_reach_tables(bw, bh).0),
602 ("has_bl", rect_reach_tables(bw, bh).1),
603 ] {
604 assert_eq!(
605 table.len() * 8,
606 rows * cols,
607 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
608 );
609 let mut seen = vec![0u32; table.len() * 8];
610 for blk_row in 0..rows {
611 for blk_col in 0..cols {
612 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
613 assert!(
614 idx < seen.len(),
615 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
616 );
617 seen[idx] += 1;
618 }
619 }
620 assert!(
621 seen.iter().all(|&n| n == 1),
622 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
623 (row stride is not {cols})"
624 );
625 }
626 }
627 }
628 use super::*;
629 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
630 use crate::probe::run_with_stdin;
631 use std::process::{Command, Stdio};
632
633 /// Every rectangular shape this decoder codes, at every position a block
634 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
635 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
636 /// (`reconintra.c`) answer, whose bodies are ported below.
637 ///
638 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
639 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
640 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
641 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
642 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
643 /// oracle's own arrays, so a re-routed or truncated table fails here even
644 /// where the two rows happen to agree.
645 ///
646 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
647 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
648 /// callers handle by predicting each transform unit as its own block.
649 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
650 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
651 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
652 /// (the horizontal shapes, which those partitions never produce).
653 #[test]
654 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
655 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
656 // it pins the 64 reach explicitly instead of following the process's
657 // own superblock knob (`for_encoder`), which made it red under
658 // `EC_AV1_SB128=1` for no defect of the code under test.
659 let fctx = &crate::decode::FrameCtx::new();
660 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
661 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
662 (4, 8, 64, 9280, 64, 550),
663 (8, 4, 64, 3712, 64, 9630),
664 (8, 16, 16, 2352, 16, 134),
665 (16, 8, 16, 960, 16, 2400),
666 (16, 32, 4, 620, 4, 32),
667 (32, 16, 4, 32, 4, 184),
668 (32, 64, 1, 127, 1, 0),
669 (64, 32, 1, 19, 1, 34),
670 (4, 16, 32, 5472, 32, 14),
671 (16, 4, 32, 960, 32, 6464),
672 (8, 32, 8, 1400, 8, 2),
673 (32, 8, 8, 32, 8, 1136),
674 (16, 64, 2, 382, 2, 0),
675 (64, 16, 2, 4, 2, 84),
676 ];
677 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
678 /// a block whose transform covers it whole (`row_off == col_off == 0`,
679 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
680 /// superblock (`sb_mi_size == 16`).
681 fn libaom_reach(
682 bw: usize,
683 bh: usize,
684 x: usize,
685 y: usize,
686 width: usize,
687 height: usize,
688 _fctx: &crate::decode::FrameCtx,
689 ) -> (bool, bool) {
690 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
691 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
692 let sb_mi_size = 16usize;
693 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
694 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
695 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
696 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
697 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
698 // has_top_right: top_available && right_available, then row_off == 0.
699 let top_right = if y == 0 || x + bw >= width {
700 false
701 } else if blk_row_in_sb == 0 {
702 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
703 // `bw_unit < bw_unit`, false for a whole-block transform.)
704 true
705 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
706 false
707 } else {
708 bit(tr_table)
709 };
710 // has_bottom_left: bottom_available && left_available, col_off == 0.
711 let bottom_left = if x == 0 || y + bh >= height {
712 false
713 } else if blk_col_in_sb == 0 {
714 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
715 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
716 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
717 false
718 } else {
719 bit(bl_table)
720 };
721 (top_right, bottom_left)
722 }
723 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
724 let (tr, bl) = rect_reach_tables(bw, bh);
725 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
726 assert_eq!(
727 (tr.len(), sum(tr), bl.len(), sum(bl)),
728 (tr_len, tr_sum, bl_len, bl_sum),
729 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
730 );
731 // Two superblocks across and down, so the superblock-relative
732 // position (and not the frame position) is what decides.
733 for sb_y in [0usize, 64] {
734 for sb_x in [0usize, 64] {
735 for y in (sb_y..sb_y + 64).step_by(bh) {
736 for x in (sb_x..sb_x + 64).step_by(bw) {
737 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
738 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
739 assert_eq!(
740 (got.above_right, got.below_left),
741 want,
742 "{bw}x{bh} at ({x}, {y})"
743 );
744 }
745 }
746 }
747 }
748 }
749 }
750
751 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
752 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
753 /// aomenc gate decodes its stream through ffmpeg and is meaningless
754 /// without it -- turns it into a hard failure. Without this the require
755 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
756 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
757 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
758 pub(super) fn have_ffmpeg() -> bool {
759 let present = Command::new("ffmpeg")
760 .arg("-version")
761 .stdout(Stdio::null())
762 .stderr(Stdio::null())
763 .status()
764 .is_ok_and(|s| s.success());
765 assert!(
766 present
767 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
768 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
769 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
770 );
771 present
772 }
773
774 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
775 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
776 pub(super) fn have_encoder(encoder: &str) -> bool {
777 crate::tool_cache::cached_output_io(Command::new("ffmpeg")
778 .args(["-hide_banner", "-encoders"])
779 .stderr(Stdio::null()), None, |c| c.output())
780 .is_ok_and(|o| {
781 String::from_utf8_lossy(&o.stdout)
782 .lines()
783 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
784 })
785 }
786
787 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
788 pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
789 let out = run_with_stdin(
790 Command::new("ffmpeg").args([
791 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
792 ]),
793 stream,
794 );
795 assert!(
796 out.status.success(),
797 "ffmpeg refused the stream: {}",
798 String::from_utf8_lossy(&out.stderr)
799 );
800 let (luma, chroma) = (width * height, width * height / 4);
801 assert_eq!(
802 out.stdout.len(),
803 luma + 2 * chroma,
804 "expected one 4:2:0 frame"
805 );
806 Picture {
807 width,
808 height,
809 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
810 u: out.stdout[luma..luma + chroma]
811 .iter()
812 .map(|&v| u16::from(v))
813 .collect(),
814 v: out.stdout[luma + chroma..]
815 .iter()
816 .map(|&v| u16::from(v))
817 .collect(),
818 }
819 }
820
821 /// A picture with something of everything in it: a gradient, an edge, a
822 /// ripple and a block of flat colour, none of them aligned to the block
823 /// grid.
824 /// The in-loop filters actually FIRE and the stream still decodes to
825 /// exactly what the encoder kept as its reconstruction
826 /// (gate-blind-to-feature: a filter search that always answered "off"
827 /// would leave every other test just as green, and the BD gate that
828 /// would notice is `#[ignore]`d).
829 ///
830 /// Run:
831 /// cargo test -p ec-av1 --release --lib -- \
832 /// encode::tests::the_filter_search_picks_real_filters
833 #[test]
834 fn the_filter_search_picks_real_filters() {
835 let _knobs = crate::speed::knob_read();
836 let fctx = &crate::decode::FrameCtx::for_encoder();
837 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
838 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
839 let fired = encoded
840 .frames
841 .iter()
842 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
843 .count();
844 assert!(
845 fired > 0,
846 "no frame of this sequence chose any in-loop filtering: {:?}",
847 encoded
848 .frames
849 .iter()
850 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
851 .collect::<Vec<_>>()
852 );
853 // The reconstruction the encoder predicts from is the FILTERED one,
854 // and it is what a decoder of the stream produces -- byte for byte,
855 // frame for frame.
856 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
857 assert_eq!(decoded.len(), encoded.frames.len());
858 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
859 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
860 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
861 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
862 }
863 }
864
865 pub(super) fn test_card(width: usize, height: usize) -> Picture {
866 let mut picture = Picture::grey(width, height);
867 for y in 0..height {
868 for x in 0..width {
869 let gradient = x as f64 * 200.0 / width as f64;
870 let ripple = 30.0
871 * (x as f64 * std::f64::consts::PI / 23.0).sin()
872 * (y as f64 * std::f64::consts::PI / 37.0).cos();
873 let edge = if x > width * 3 / 7 && y > height / 3 {
874 40.0
875 } else {
876 0.0
877 };
878 picture.y[y * width + x] =
879 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
880 }
881 }
882 for y in 0..height / 2 {
883 for x in 0..width / 2 {
884 let i = y * width / 2 + x;
885 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
886 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
887 }
888 }
889 picture
890 }
891
892 pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 {
893 let squared: f64 = a
894 .iter()
895 .zip(b)
896 .map(|(&x, &y)| {
897 let d = f64::from(x) - f64::from(y);
898 d * d
899 })
900 .sum();
901 if squared == 0.0 {
902 return f64::INFINITY;
903 }
904 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
905 }
906
907 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
908 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
909 /// frame's new root fires on most superblocks -- and what BOTH decoders
910 /// produce is the encoder's own reconstruction, sample for sample.
911 ///
912 /// The fire count is the `gate-blind-to-feature` guard: without it every
913 /// assert below passes on a stream that codes no whole superblock at all.
914 #[test]
915 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
916 let _knobs = crate::speed::knob_read();
917 let fctx = &crate::decode::FrameCtx::for_encoder();
918 // 4 x 3 superblocks, all of them wholly inside the frame.
919 let (width, height) = (256usize, 192usize);
920 let mut picture = Picture::grey(width, height);
921 for y in 0..height {
922 for x in 0..width {
923 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
924 }
925 }
926 for y in 0..height / 2 {
927 for x in 0..width / 2 {
928 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
929 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
930 }
931 }
932 let _ = take_i64_root_hits();
933 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
934 let [roots, _offered, _edge] = take_i64_root_hits();
935 // The counters are process-global, so another test encoding in
936 // parallel can only ADD to them -- the per-FRAME fact is the mode
937 // list, which carries one entry per coded block and so exactly 12
938 // when every superblock was coded as one 64x64 intra block.
939 assert_eq!(
940 encoded.modes.len(),
941 12,
942 "not every superblock was coded as one 64x64 intra block"
943 );
944 assert!(
945 roots >= 8,
946 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
947 );
948 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
949
950 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
951 assert_eq!(ours.len(), 1, "our decoder's frames");
952 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
953 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
954 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
955
956 if !have_ffmpeg() {
957 eprintln!("SKIP the ffmpeg half: no ffmpeg");
958 return;
959 }
960 let decoded = ffmpeg_decode(&encoded.stream, width, height);
961 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
962 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
963 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
964 }
965
966 /// The claim the whole encoder rests on: what a decoder produces is what
967 /// the encoder said it would, sample for sample, on every plane.
968 ///
969 /// Prediction reads the reconstruction, so a single sample of drift
970 /// anywhere would spread into every block below and to the right of it —
971 /// which is why this is an equality and not a tolerance.
972 #[test]
973 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
974 let _knobs = crate::speed::knob_read();
975 let fctx = &crate::decode::FrameCtx::for_encoder();
976 if !have_ffmpeg() {
977 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
978 return;
979 }
980 for &(width, height) in &[
981 (64usize, 64usize),
982 (96, 64),
983 (160, 96),
984 (32, 48),
985 (248, 152),
986 ] {
987 let picture = test_card(width, height);
988 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
989 let decoded = ffmpeg_decode(&encoded.stream, width, height);
990 assert_eq!(
991 decoded.y, encoded.reconstruction.y,
992 "{width}x{height}: luma"
993 );
994 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
995 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
996 }
997 // One q index from each of the four coefficient-CDF contexts
998 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
999 let (width, height) = (64usize, 64usize);
1000 let picture = test_card(width, height);
1001 let _ = take_tx_depth_hits();
1002 for &q in &[15u8, 45, 100, 200] {
1003 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
1004 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1005 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
1006 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
1007 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
1008 }
1009 // lane-av1tx: the exactness above is only a claim about SPLIT
1010 // transforms if some block actually split one (`gate-blind-to-feature`
1011 // -- with `tx_depth` stuck at 0 every assert here passes on the
1012 // pre-lane stream). The test card's edges split at these four
1013 // quantizers; the counter is per-process (another test encoding in
1014 // parallel can only ADD to it, so this can be masked, never falsely
1015 // failed), so it is read once for the whole q ladder.
1016 let depths = take_tx_depth_hits();
1017 assert!(
1018 depths[1] + depths[2] > 0,
1019 "no block split its transform: depths {depths:?}"
1020 );
1021 }
1022
1023 /// A synthetic screen-content picture -- a few flat colours in a grid of
1024 /// boxes with hard edges and text-like bars, the shape a desktop capture
1025 /// has -- so the palette path is exercised on content it is for.
1026 #[cfg(test)]
1027 pub(super) fn screen_card(width: usize, height: usize) -> Picture {
1028 const INK: [u16; 4] = [16, 90, 180, 235];
1029 let mut picture = Picture::grey(width, height);
1030 for y in 0..height {
1031 for x in 0..width {
1032 let cell = (x / 24 + y / 24) % 2;
1033 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
1034 picture.y[y * width + x] = INK[cell * 2 + bar];
1035 }
1036 }
1037 // Four chroma colours, not two: a two-colour chroma block only ever
1038 // codes a `PaletteSizeUV` of 2, which leaves
1039 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
1040 // deltas and the neighbour cache flags, exercised only when
1041 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
1042 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
1043 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
1044 for y in 0..height / 2 {
1045 for x in 0..width / 2 {
1046 let cell = (x / 12 + 2 * (y / 12)) % 4;
1047 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
1048 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
1049 }
1050 }
1051 picture
1052 }
1053
1054 /// The lane's own end-to-end check: on screen content the detector fires,
1055 /// blocks really take a palette (fire count, class
1056 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
1057 /// symbol this lane writes -- reconstructs exactly what the encoder did.
1058 /// The film-shaped `test_card` must NOT trip the detector, which is what
1059 /// keeps every non-screen stream byte-identical.
1060 #[test]
1061 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
1062 let _knobs = crate::speed::knob_read();
1063 let fctx = &crate::decode::FrameCtx::for_encoder();
1064 let (width, height) = (192usize, 96usize);
1065 let _ = crate::tile::take_palette_hits();
1066 let picture = screen_card(width, height);
1067 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1068 assert!(
1069 encoded.screen,
1070 "the detector did not fire on screen content -- no palette syntax was coded at all"
1071 );
1072 let hits = crate::tile::take_palette_hits();
1073 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
1074 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
1075 // The chroma half is a claim about the plane-1 syntax only if some
1076 // block really took a chroma palette (`gate-blind-to-feature`): every
1077 // exactness assert below passes on a stream that codes
1078 // `palette_uv_mode == 0` everywhere.
1079 let uv_hits = crate::tile::take_palette_uv_hits();
1080 assert!(
1081 uv_hits[0] > 0,
1082 "no block took a chroma palette: {uv_hits:?}"
1083 );
1084 let uv_cached = crate::tile::take_palette_uv_cache_hits();
1085 eprintln!(
1086 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
1087 uv_hits[0],
1088 &uv_hits[2..]
1089 );
1090 assert!(
1091 uv_cached > 0,
1092 "no chroma base colour came out of the neighbour cache -- \
1093 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
1094 );
1095 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
1096 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
1097 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
1098 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
1099 if !have_ffmpeg() {
1100 eprintln!("SKIP the ffmpeg half: no ffmpeg");
1101 return;
1102 }
1103 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1104 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
1105 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
1106 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
1107 // A whole GOP: the inter frames' own intra blocks carry the palette
1108 // syntax too (the three intra arms of the inter writers), which only
1109 // ffmpeg reading the frames back can prove.
1110 let moved: Vec<Picture> = (0..4)
1111 .map(|f| {
1112 let base = screen_card(width, height);
1113 let mut out = Picture::grey(width, height);
1114 for y in 0..height {
1115 for x in 0..width {
1116 let sx = (x + f * 7) % width;
1117 out.y[y * width + x] = base.y[y * width + sx];
1118 }
1119 }
1120 for y in 0..height / 2 {
1121 for x in 0..width / 2 {
1122 let sx = (x + f * 3) % (width / 2);
1123 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
1124 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
1125 }
1126 }
1127 out
1128 })
1129 .collect();
1130 let _ = crate::tile::take_palette_hits();
1131 let _ = crate::tile::take_palette_uv_hits();
1132 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
1133 let gop_hits = crate::tile::take_palette_hits();
1134 let gop_uv_hits = crate::tile::take_palette_uv_hits();
1135 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
1136 eprintln!(
1137 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
1138 {} chroma palette blocks",
1139 inter_screen, gop_hits[0], gop_uv_hits[0]
1140 );
1141 assert!(
1142 gop_uv_hits[0] > 0,
1143 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
1144 );
1145 assert!(
1146 inter_screen > 0,
1147 "no inter frame set allow_screen_content_tools"
1148 );
1149 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
1150 assert_eq!(
1151 gop_decoded.len(),
1152 gop.frames.len(),
1153 "our decoder: GOP frame count"
1154 );
1155 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
1156 assert_eq!(
1157 ours.y, frame.reconstruction.y,
1158 "our decoder: GOP frame {i} luma"
1159 );
1160 }
1161 if have_ffmpeg() {
1162 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
1163 assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
1164 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
1165 assert_eq!(
1166 theirs.y, frame.reconstruction.y,
1167 "ffmpeg: GOP frame {i} luma"
1168 );
1169 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
1170 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
1171 }
1172 }
1173
1174 // The other half of the keep rule: film-shaped content leaves the
1175 // detector (and so the whole sequence header) alone.
1176 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
1177 assert!(
1178 !film.screen,
1179 "the detector fired on the film-shaped test card"
1180 );
1181 }
1182
1183 /// lane-av1paletteuv: the census for `crate::tile::palette_uv_side`, the
1184 /// `(side / 2).max(4)` named in `lanes/av1subsizesweep.report.md` as a
1185 /// "4:2:2/4:4:0 palette map mis-sized" site.
1186 ///
1187 /// **What the site computes.** libaom reads the plane-1 colour-index map
1188 /// at `av1_get_block_dimensions(bsize, 1, xd)` (blockd.h:1512): per axis,
1189 /// `plane_block = block >> ss`, then `+2` when that came out under 4
1190 /// (the chroma sub-8x8 bump, blockd.h:1533-1541). For a SQUARE 4:2:0
1191 /// block both axes carry `ss = 1`, so both come to `side / 2` with the
1192 /// bump -- which is exactly `(side / 2).max(4)`. The value is right.
1193 ///
1194 /// **What it is not.** At 4:2:2 the correct map is `(side >> 1) x side`
1195 /// and at 4:4:4 it is `side x side` -- neither is square. So the value is
1196 /// 4:2:0-only BY CONSTRUCTION, and this gate is what keeps it that way:
1197 /// if an encoder that can emit another chroma shape ever appears, this
1198 /// reds rather than the writer silently writing a half-height map.
1199 ///
1200 /// The three arms are (1) the value matches libaom's own per-axis
1201 /// formula at 4:2:0 over every side the palette syntax admits, (2) no
1202 /// reachable writer path can be handed another chroma shape, (3) a real
1203 /// encode really fires chroma palettes, so arm 1 is not arithmetic on a
1204 /// function nothing calls (class `gate-blind-to-feature`).
1205 #[test]
1206 fn the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it() {
1207 const NAME: &str =
1208 "the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it";
1209 let encode_src = crate::test_source::module_source("encode");
1210
1211 // ---- arm 1: the value, against libaom's formula --------------------
1212 // blockd.h:1530-1541, transcribed. A plane_block under 4 gains 2.
1213 let libaom_plane1 = |block: usize, ss: usize| {
1214 let plane_block = block >> ss;
1215 plane_block + 2 * usize::from(plane_block < 4)
1216 };
1217 let mut admitted = 0usize;
1218 for side in 4usize..=64 {
1219 // `palette_bsize_ctx`'s own domain: both sides <= 64 and
1220 // bw * bh >= 64 (`av1_allow_palette`). A side outside it codes no
1221 // palette syntax at all, so its map size is unobservable.
1222 if side > 64 || side * side < 64 {
1223 continue;
1224 }
1225 admitted += 1;
1226 let want_x = libaom_plane1(side, 1);
1227 let want_y = libaom_plane1(side, 1);
1228 assert_eq!(want_x, want_y, "{NAME}: 4:2:0 arms the libaom formula");
1229 assert_eq!(
1230 crate::tile::palette_uv_side(side),
1231 want_x,
1232 "{NAME}: side {side} -- palette_uv_side disagrees with libaom's plane-1 block"
1233 );
1234 }
1235 assert_eq!(
1236 admitted, 57,
1237 "{NAME}: the sweep admitted {admitted} sides, expected 57 (every integer 8..=64 -- \
1238 `palette_bsize_ctx`'s whole square domain, not just the powers of two a real block \
1239 takes) -- it must cover that domain, or it is not measuring it"
1240 );
1241
1242 // Why `.max(4)` cannot fire, stated as a measurement rather than left
1243 // for a reader to assume: `palette_bsize_ctx` refuses `bw * bh < 64`,
1244 // so the smallest admitted square side is 8, whose halved plane block
1245 // is already 4. The floor's only reachable input would be a side
1246 // under 8, and libaom's own chroma sub-8x8 bump (+2) is likewise
1247 // unreachable there. Dropping the floor is therefore NOT a witness
1248 // mutation for this gate -- the mutation that bites is dropping the
1249 // halving (measured, see the lane report) -- and this arm says why,
1250 // so nobody later mistakes a green floor mutation for coverage.
1251 for side in [8usize, 16, 32, 64] {
1252 assert!(
1253 side / 2 >= 4 && libaom_plane1(side, 1) == side / 2,
1254 "{NAME}: side {side} -- the admitted domain moved, so `.max(4)` may now be \
1255 reachable and the floor needs a witness mutation of its own"
1256 );
1257 }
1258
1259 // The claim the gate rests on, stated as arithmetic so a future
1260 // reader cannot mistake "correct" for "correct at any shape": at
1261 // these shapes the per-axis answer is NOT this square.
1262 for side in [8usize, 16, 32, 64] {
1263 let square = crate::tile::palette_uv_side(side);
1264 let want_422 = (libaom_plane1(side, 1), libaom_plane1(side, 0));
1265 let want_444 = (libaom_plane1(side, 0), libaom_plane1(side, 0));
1266 assert_ne!(
1267 (square, square),
1268 want_422,
1269 "{NAME}: side {side} -- a square map IS the 4:2:2 map, so this gate's premise \
1270 (the site is 4:2:0-only) is wrong"
1271 );
1272 assert_ne!(
1273 (square, square),
1274 want_444,
1275 "{NAME}: side {side} -- a square map IS the 4:4:4 map"
1276 );
1277 }
1278
1279 // ---- arm 2: nothing can hand the writer another shape --------------
1280 // (a) Every non-test `ColorConfig` literal in the encoder names
1281 // subsampling (1, 1). These are the two constructors the whole
1282 // encoder reaches its colour config through; the test-module copies
1283 // are excluded by scanning only the pre-`mod tests` prefix. The cut
1284 // matches an inline `mod tests {` body only, so a `mod tests;` file
1285 // declaration does not truncate the production files after it.
1286 fn head(src: &str) -> &str {
1287 let cut = src.find("\nmod tests {").unwrap_or(src.len());
1288 &src[..cut]
1289 }
1290 for (label, src) in [
1291 ("encode.rs", head(crate::test_source::module_production_source("encode"))),
1292 ("encoder.rs", head(crate::test_source::module_production_source("encoder"))),
1293 ] {
1294 // Every `subsampling_*` the non-test encoder names, counted: a
1295 // `(0, y)` or `(1, 0)` here is a chroma shape
1296 // `palette_uv_side` cannot express. The one value allowed is 1
1297 // -- 4:2:0, the shape the square map is the right size for.
1298 let mut shapes: std::collections::BTreeSet<(usize, usize)> = Default::default();
1299 for (sx, _) in src.match_indices("subsampling_x:") {
1300 let rest = &src[sx + "subsampling_x:".len()..];
1301 let digits = |s: &str| {
1302 s.trim_start()
1303 .split(|c: char| !c.is_ascii_digit())
1304 .next()
1305 .and_then(|d| d.parse::<usize>().ok())
1306 .unwrap_or(usize::MAX)
1307 };
1308 let x = digits(rest);
1309 let y = rest
1310 .find("subsampling_y:")
1311 .map(|y| digits(&rest[y + "subsampling_y:".len()..]))
1312 .unwrap_or(usize::MAX);
1313 shapes.insert((x, y));
1314 }
1315 assert_eq!(
1316 shapes,
1317 std::collections::BTreeSet::from([(1usize, 1usize)]),
1318 "{NAME}: the non-test {label} names chroma shapes {shapes:?} -- any shape other \
1319 than 4:2:0 is one palette_uv_side's square map cannot express (at 4:2:2 the \
1320 map is (side >> 1) x side, at 4:4:4 side x side)"
1321 );
1322 }
1323
1324 // (b) `key_frame_headers_colour` is the only PUBLIC entry that takes
1325 // a caller-chosen ColorConfig -- it is how a 4:2:2 or 4:4:4 header is
1326 // written at all -- so it is the one door a non-4:2:0 shape comes
1327 // through. It builds HEADERS only: no tile writer is reachable from
1328 // its body. (Its own doc says so; this measures it.)
1329 let headers_at = encode_src
1330 .find("pub fn key_frame_headers_colour(")
1331 .expect("key_frame_headers_colour is gone -- re-derive this arm's scan anchor");
1332 let body_end = encode_src[headers_at..]
1333 .find("\npub fn ")
1334 .map(|n| headers_at + n)
1335 .unwrap_or(encode_src.len());
1336 let headers_body = &encode_src[headers_at..body_end];
1337 for writer in [
1338 "write_palette_syntax",
1339 "write_color_index_map",
1340 "encode_key_frame_inner",
1341 "tile::",
1342 ] {
1343 assert!(
1344 !headers_body.contains(writer),
1345 "{NAME}: key_frame_headers_colour now reaches {writer} -- a caller can pair a \
1346 4:2:2/4:4:4 header with a tile, and palette_uv_side writes a square map into \
1347 the per-axis slot libaom reads as (side >> ss_x) x (side >> ss_y)"
1348 );
1349 }
1350
1351 // (c) Every tile-producing entry point goes through
1352 // `encode_key_frame_inner`, whose five non-test call sites all pass
1353 // one of the two 4:2:0 constructors above. Counted over the
1354 // non-test source only, so a new road is a red rather than a line
1355 // somebody has to notice.
1356 let inner_calls = head(crate::test_source::module_production_source("encode")).matches("encode_key_frame_inner(").count()
1357 + head(crate::test_source::module_production_source("encoder")).matches("encode_key_frame_inner(").count()
1358 - 1; // the definition itself
1359 assert_eq!(
1360 inner_calls, 5,
1361 "{NAME}: encode_key_frame_inner has {inner_calls} non-test call sites, expected 5 -- \
1362 a new one must pass a colour config this gate has read"
1363 );
1364
1365 // (d) The picture itself is 4:2:0-shaped at the door, so a 4:2:2 or
1366 // 4:4:4 frame cannot even be handed to an encode entry. Measured by
1367 // calling `check`, not by reading it.
1368 for (label, divisor) in [("4:2:2", 2usize), ("4:4:4", 1)] {
1369 let p = Picture {
1370 width: 64,
1371 height: 64,
1372 y: vec![0; 64 * 64],
1373 u: vec![0; 64 * 64 / divisor],
1374 v: vec![0; 64 * 64 / divisor],
1375 };
1376 assert!(
1377 p.check().is_err(),
1378 "{NAME}: Picture::check accepted a {label}-shaped picture -- if the encoder can be \
1379 fed one, palette_uv_side's square map is wrong by construction"
1380 );
1381 }
1382
1383 // ---- arm 3: the site really fires ---------------------------------
1384 // Without this, arms 1 and 2 are arithmetic and a source scan over a
1385 // function no encode reaches (class `gate-blind-to-feature`).
1386 //
1387 // The fire count is the DECODER's thread-local one, not the writer's
1388 // process-global `tile::take_palette_uv_hits`: that one is a
1389 // swap-to-zero, so a parallel sibling test's encode steals this test's
1390 // count (measured: it read `[0; 9]` under `cargo test palette`, and
1391 // passed alone). Round-tripping the stream instead also proves the
1392 // stronger half -- the reader took the map at the extent the WRITER
1393 // sized, which is what makes the square value right rather than merely
1394 // unchallenged.
1395 let _knobs = crate::speed::knob_read();
1396 let fctx = &crate::decode::FrameCtx::for_encoder();
1397 let before = crate::decode::palette_uv_hits();
1398 let encoded = encode_key_frame_with_ctx(&screen_card(192, 96), 100, 0.5, fctx).unwrap();
1399 let decoded = crate::stream::decode_stream(&encoded.stream)
1400 .unwrap_or_else(|e| panic!("{NAME}: our own stream refused: {e}"));
1401 let fired = crate::decode::palette_uv_hits() - before;
1402 assert!(
1403 fired > 0,
1404 "{NAME}: no block took a chroma palette -- palette_uv_side was never exercised, so \
1405 this gate measures nothing"
1406 );
1407 assert_eq!(
1408 decoded[0].u, encoded.reconstruction.u,
1409 "{NAME}: the decoder did not read the chroma map at the extent the writer sized it"
1410 );
1411 assert_eq!(
1412 decoded[0].v, encoded.reconstruction.v,
1413 "{NAME}: the decoder did not read the chroma map at the extent the writer sized it"
1414 );
1415 eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped");
1416 }
1417
1418 /// The lane's keep-rule measurement: the gate's own screen capture, one
1419 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
1420 /// Setting the bit forces deblocking, CDEF and loop restoration off for
1421 /// that frame, so the table is exactly the filter loss against the bytes
1422 /// the copied blocks save.
1423 #[test]
1424 #[ignore = "needs the real-library manifest and ffmpeg"]
1425 fn probe_intrabc_key_frame() {
1426 let _knobs = crate::speed::knob_write();
1427 let fctx = &crate::decode::FrameCtx::for_encoder();
1428 // lane-av1clipprobe: the manifest is a real-library file, so it
1429 // resolves through the crate's one fixture root (EC_FIXTURES first)
1430 // and its absence is reported by the one probe instead of an inline
1431 // SKIP that named no path. A file that IS there but unreadable is not
1432 // an absence, so it is a hard error rather than a second silent skip.
1433 let Some(manifest_path) =
1434 crate::library_fixture::require("real-library-manifest.tsv", "probe_intrabc_key_frame")
1435 else {
1436 return;
1437 };
1438 let manifest = std::fs::read_to_string(&manifest_path).unwrap_or_else(|e| {
1439 panic!(
1440 "probe_intrabc_key_frame: {} is present but unreadable ({e})",
1441 manifest_path.display()
1442 )
1443 });
1444 let Some(clip) = manifest
1445 .lines()
1446 .skip(1)
1447 .filter_map(|l| l.split('\t').next())
1448 .find(|p| {
1449 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
1450 })
1451 else {
1452 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
1453 return;
1454 };
1455 let (width, height) = (1280usize, 768usize);
1456 let picture = clip_frame(clip, "0", width, height);
1457 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
1458 for q in [5u8, 20, 35, 45] {
1459 for on in [false, true] {
1460 force_intrabc(Some(on));
1461 let _ = crate::tile::take_intrabc_hits();
1462 let _ = take_intrabc_search();
1463 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
1464 let hits = crate::tile::take_intrabc_hits();
1465 let search = take_intrabc_search();
1466 eprintln!(
1467 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
1468 if encoded.allow_intrabc { "on" } else { "off" },
1469 encoded.stream.len(),
1470 psnr_all(&encoded.reconstruction, &picture),
1471 hits[0],
1472 &hits[1..],
1473 search[0],
1474 search[1],
1475 search[2],
1476 );
1477 }
1478 }
1479 force_intrabc(None);
1480 }
1481
1482 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
1483 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
1484 /// take a block vector (fire count + DV histogram, class
1485 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
1486 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
1487 /// exactly what the encoder did.
1488 #[test]
1489 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
1490 let _knobs = crate::speed::knob_write();
1491 let fctx = &crate::decode::FrameCtx::for_encoder();
1492 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
1493 // superblocks of 64) and tall enough for a source superblock row
1494 // above the blocks that copy from it.
1495 let (width, height) = (512usize, 256usize);
1496 let picture = screen_card(width, height);
1497 let _ = crate::tile::take_intrabc_hits();
1498 // The default is OFF (it measured worse on the real screen capture --
1499 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
1500 // the arm on for its own encode and puts it back straight after.
1501 force_intrabc(Some(true));
1502 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1503 force_intrabc(None);
1504 assert!(
1505 encoded.allow_intrabc,
1506 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
1507 intrabc_source_share() * 100.0
1508 );
1509 let hits = crate::tile::take_intrabc_hits();
1510 eprintln!(
1511 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
1512 hits[0],
1513 &hits[1..],
1514 intrabc_source_share() * 100.0
1515 );
1516 let search = take_intrabc_search();
1517 eprintln!(
1518 "intrabc searches {} found-valid {} won-RD {}",
1519 search[0], search[1], search[2]
1520 );
1521 assert!(
1522 hits[0] > 0,
1523 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
1524 );
1525 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
1526 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
1527 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
1528 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
1529 if !have_ffmpeg() {
1530 eprintln!("SKIP the ffmpeg half: no ffmpeg");
1531 return;
1532 }
1533 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1534 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
1535 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
1536 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
1537 }
1538
1539 /// The minimal repro that isolated the inter-residual desync: a key frame
1540 /// followed by one inter frame whose single superblock carries one
1541 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
1542 /// coefficient, its three sibling blocks all `skip: true`. Before the
1543 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
1544 /// found when processing input") even though every symbol either block
1545 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
1546 /// same coefficient syntax decodes clean on every intra key-frame gate).
1547 #[test]
1548 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
1549 let _knobs = crate::speed::knob_write();
1550 let fctx = &crate::decode::FrameCtx::for_encoder();
1551 if !have_ffmpeg() {
1552 eprintln!(
1553 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
1554 );
1555 return;
1556 }
1557 let (width, height) = (64usize, 64usize);
1558 let picture = Picture::grey(width, height);
1559 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1560
1561 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
1562 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
1563
1564 let residual_block = BlockCoeffs {
1565 luma_tx_types: Vec::new(),
1566 angle_delta_y: 0,
1567 cfl_alphas: None,
1568 filter_intra: None,
1569 luma: vec![Coeff {
1570 row: 0,
1571 col: 0,
1572 level: 4,
1573 }],
1574 u: Vec::new(),
1575 v: Vec::new(),
1576 mode: 0,
1577 uv_mode: 0,
1578 skip: false,
1579 eight: None,
1580 dv: None,
1581 palette: None,
1582 palette_uv: None,
1583 tx_depth: 0,
1584 inter: Some(InterInfo {
1585 ref1: None,
1586 mv1: (0, 0),
1587 ref_frame: crate::mvstack::LAST_FRAME,
1588 mode: InterMode::NearestMv,
1589 mv: (0, 0),
1590 ref_mv_idx: 0,
1591 }),
1592 motion_mode: 0,
1593 };
1594 let skipped_block = BlockCoeffs {
1595 skip: true,
1596 inter: Some(InterInfo {
1597 ref1: None,
1598 mv1: (0, 0),
1599 ref_frame: crate::mvstack::LAST_FRAME,
1600 mode: InterMode::NearestMv,
1601 mv: (0, 0),
1602 ref_mv_idx: 0,
1603 }),
1604 ..BlockCoeffs::default()
1605 };
1606 let blocks = vec![
1607 Quadrant::Whole(residual_block),
1608 Quadrant::Whole(skipped_block.clone()),
1609 Quadrant::Whole(skipped_block.clone()),
1610 Quadrant::Whole(skipped_block),
1611 ];
1612 // lane-av1obmc: the header this tile is decoded under carries
1613 // `is_motion_mode_switchable`, so the writer must be armed with it
1614 // too or the decoder reads a `motion_mode` symbol nobody wrote.
1615 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
1616 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
1617 let tile = crate::tile::sb_coeff_inter_frame_tile(
1618 inter_header.mi_cols,
1619 inter_header.mi_rows,
1620 100,
1621 &blocks,
1622 )
1623 .unwrap();
1624
1625 // `key.stream` is already a temporal delimiter, the sequence header
1626 // and the key frame's own OBU (`encode_key_frame` built it from the
1627 // same `key_frame_headers(width, height, 100)` this test calls), so
1628 // the inter frame's OBU is appended straight onto it rather than
1629 // re-deriving the key frame's tile bytes.
1630 let mut stream = key.stream.clone();
1631 stream.extend_from_slice(&temporal_delimiter());
1632 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
1633
1634 ffmpeg_decode_sequence(&stream, width, height, 2);
1635 }
1636
1637 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
1638 /// frame size an AV1 decoder allocates, not necessarily the render size
1639 /// (see [`a_frame_round_trips_at_its_own_size`]).
1640 pub(super) fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
1641 // Distinct per call, not per process: the test binary runs callers on
1642 // parallel threads, and a shared name lets one test's cleanup delete
1643 // the stream another test's ffprobe is still reading.
1644 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1645 let path = std::env::temp_dir().join(format!(
1646 "ec-av1-probe-{}-{}.obu",
1647 std::process::id(),
1648 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
1649 ));
1650 let _ = std::fs::remove_file(&path);
1651 std::fs::write(&path, stream).expect("writing the probe stream");
1652 let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")
1653 .args([
1654 "-v",
1655 "error",
1656 "-f",
1657 "obu",
1658 "-select_streams",
1659 "v:0",
1660 "-show_entries",
1661 "stream=width,height",
1662 "-of",
1663 "csv=p=0",
1664 ])
1665 .arg(&path), None, |c| c.output())
1666 .expect("ffprobe failed to run");
1667 let _ = std::fs::remove_file(&path);
1668 assert!(
1669 out.status.success(),
1670 "ffprobe refused the stream: {}",
1671 String::from_utf8_lossy(&out.stderr)
1672 );
1673 let text = String::from_utf8_lossy(&out.stdout);
1674 let mut fields = text.trim().split(',');
1675 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
1676 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
1677 (width, height)
1678 }
1679
1680 /// lane-av1cap: the final filter replay against the capture decode it
1681 /// replaced, at the block-padded and straddling sizes the whole-frame
1682 /// tests cover -- `set_verify_final_replay` makes
1683 /// [`pick_and_apply_filters`] run both on every frame and assert, per
1684 /// frame, that the spliced picture and the two filter stages the
1685 /// restoration search reads are bit-identical over the frame's own crop.
1686 #[test]
1687 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
1688 let _knobs = crate::speed::knob_write();
1689 let fctx = &crate::decode::FrameCtx::for_encoder();
1690 crate::decode::set_verify_final_replay(true);
1691 for &(width, height) in &[
1692 (64usize, 56usize),
1693 (216, 96),
1694 (192, 120),
1695 (640, 352),
1696 (1280, 720),
1697 ] {
1698 eprintln!("--- {width}x{height}");
1699 let picture = test_card(width, height);
1700 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1701 }
1702 crate::decode::set_verify_final_replay(false);
1703 }
1704
1705 /// A key frame at an arbitrary even size round-trips through ffmpeg over
1706 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
1707 /// picture's own size, and what ffmpeg decodes over that same top-left
1708 /// region equals it sample for sample.
1709 ///
1710 /// This does not check that `ffprobe` reports the picture's own size,
1711 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
1712 /// (block-padded) frame size, the same one libaom itself would code for
1713 /// a non-block-aligned picture. `render_width`/`render_height` (which
1714 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
1715 /// decoder is required to crop pixels by, and ffmpeg's does not --
1716 /// checked empirically against ffprobe here and against a real libaom
1717 /// encode separately. So the coded size, not the render size, is what
1718 /// `ffprobe` is asserted to report below.
1719 #[test]
1720 fn a_frame_round_trips_at_its_own_size() {
1721 let _knobs = crate::speed::knob_read();
1722 let fctx = &crate::decode::FrameCtx::for_encoder();
1723 if !have_ffmpeg() {
1724 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
1725 return;
1726 }
1727 // 854x480 is covered separately by
1728 // `an_854x480_picture_round_trips_through_its_padding`, which its own
1729 // doc comment explains was worth keeping as its own test.
1730 for &(width, height) in &[
1731 (1920usize, 1080usize),
1732 (640, 352),
1733 (1280, 720),
1734 (64, 56),
1735 (854, 480),
1736 (216, 96),
1737 (192, 120),
1738 ] {
1739 let picture = test_card(width, height);
1740 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1741 assert_eq!(
1742 (encoded.reconstruction.width, encoded.reconstruction.height),
1743 (width, height),
1744 "{width}x{height}: reconstruction is cropped to the picture's own size"
1745 );
1746 assert_eq!(
1747 ffprobe_size(&encoded.stream),
1748 (width as u32, height as u32),
1749 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
1750 );
1751 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1752 assert_eq!(
1753 decoded.y, encoded.reconstruction.y,
1754 "{width}x{height}: luma"
1755 );
1756 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
1757 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
1758 }
1759 }
1760
1761 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
1762 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
1763 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
1764 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
1765 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
1766 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
1767 /// col`) -- different bits of an 8-byte table, one true, one false. The
1768 /// stride libaom indexes by is fixed at its compile-time maximum
1769 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
1770 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
1771 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
1772 /// row/col position within the (correctly 64-relative) superblock stayed
1773 /// right, only the table's own row stride was wrong. Fixed in
1774 /// `Reach::table_stride`; not an arithmetic-coder desync (an
1775 /// EC_RNG-per-symbol trace against the same debug decoder found the
1776 /// bitstream byte-for-byte identical to libaom's across all 51188
1777 /// symbols of this frame before this bug was found).
1778 ///
1779 /// Since the frame header started writing the true (unpadded) display
1780 /// size into `frame_width`/`frame_height` rather than the padded coded
1781 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
1782 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
1783 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
1784 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
1785 /// the header's own size before output).
1786 #[test]
1787 fn an_854x480_picture_round_trips_through_its_padding() {
1788 let _knobs = crate::speed::knob_read();
1789 let fctx = &crate::decode::FrameCtx::for_encoder();
1790 if !have_ffmpeg() {
1791 return;
1792 }
1793 let (width, height) = (854usize, 480usize);
1794 let picture = test_card(width, height);
1795 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1796 let decoded = ffmpeg_decode(&encoded.stream, width, height);
1797 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
1798 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
1799 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
1800 }
1801
1802 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
1803 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
1804 /// superblock, both partition tables:
1805 ///
1806 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
1807 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
1808 /// wiring the TU sites onto it changes no existing stream;
1809 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
1810 /// NULL in libaom because that lookup never happens, and reading a
1811 /// 4x4 row out of the three-row vert tables is what crashed a real
1812 /// `--enable-tx-size-search=1` stream (r2);
1813 /// 3. and it must be the BLOCK's vert answer where the two tables
1814 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
1815 /// row 1, column 0 reads its above-right samples from the 8x8 to its
1816 /// upper right, which a vertical AB partition codes AFTER it
1817 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
1818 #[test]
1819 fn of_tu_follows_the_block_row_including_under_vert_ab() {
1820 let fctx = &crate::decode::FrameCtx::for_encoder();
1821 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
1822 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
1823 // above-right answer is the BLOCK's, which is the whole reason a unit
1824 // asks the block instead of looking itself up (the
1825 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
1826 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
1827 assert_eq!(
1828 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
1829 plain.above_right,
1830 "ordinary table: the top-right TX4 unit takes the block's row"
1831 );
1832 let guard = Reach::vert_ab_partition();
1833 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
1834 assert_eq!(
1835 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
1836 vert.above_right,
1837 "vert AB: the unit follows the vert row the block just picked"
1838 );
1839 assert_ne!(
1840 plain.above_right, vert.above_right,
1841 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
1842 );
1843 drop(guard);
1844 }
1845
1846 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
1847 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
1848 /// reconintra.c`), for every 16x16 and 32x32 block position across three
1849 /// superblocks square -- interior and every superblock edge (top row,
1850 /// left column, right column, bottom row) both sizes reach. Written to
1851 /// catch the class the `table_stride` bug was: an index stride silently
1852 /// wrong for one block size while looking plausible for the other.
1853 #[test]
1854 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
1855 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
1856 // it pins the 64 reach explicitly instead of following the process's
1857 // own superblock knob (`for_encoder`), which made it red under
1858 // `EC_AV1_SB128=1` for no defect of the code under test.
1859 let fctx = &crate::decode::FrameCtx::new();
1860 // Transcribed from has_top_right/has_bottom_left's row_off==0,
1861 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
1862 // 128px reference grid) pinned as libaom pins it, independent of the
1863 // 64px superblock this crate actually codes.
1864 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
1865 if y == 0 || x + side >= width {
1866 return false;
1867 }
1868 let (row, col, per_side) = (
1869 (y % SUPERBLOCK) / side,
1870 (x % SUPERBLOCK) / side,
1871 SUPERBLOCK / side,
1872 );
1873 if row == 0 {
1874 return true;
1875 }
1876 if col + 1 == per_side {
1877 return false;
1878 }
1879 let stride = 128 / side;
1880 let index = row * stride + col;
1881 let table = if side == BLOCK {
1882 [95u8, 87].to_vec()
1883 } else {
1884 vec![255, 85, 119, 85, 127, 85, 119, 85]
1885 };
1886 (table[index / 8] >> (index % 8)) & 1 != 0
1887 }
1888
1889 fn libaom_bottom_left(
1890 side: usize,
1891 x: usize,
1892 y: usize,
1893 height: usize,
1894 _fctx: &crate::decode::FrameCtx,
1895 ) -> bool {
1896 if x == 0 || y + side >= height {
1897 return false;
1898 }
1899 let (row, col, per_side) = (
1900 (y % SUPERBLOCK) / side,
1901 (x % SUPERBLOCK) / side,
1902 SUPERBLOCK / side,
1903 );
1904 if col == 0 {
1905 return row * side + side < SUPERBLOCK;
1906 }
1907 if row + 1 == per_side {
1908 return false;
1909 }
1910 let stride = 128 / side;
1911 let index = row * stride + col;
1912 let table = if side == BLOCK {
1913 [4u8, 4].to_vec()
1914 } else {
1915 vec![84, 16, 84, 0, 84, 16, 84, 0]
1916 };
1917 (table[index / 8] >> (index % 8)) & 1 != 0
1918 }
1919
1920 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
1921 for side in [16usize, BLOCK] {
1922 for y in (0..height).step_by(side) {
1923 for x in (0..width).step_by(side) {
1924 let reach = Reach::of(side, x, y, width, height, fctx);
1925 assert_eq!(
1926 reach.above_right,
1927 libaom_top_right(side, x, y, width, height),
1928 "side={side} x={x} y={y}: above_right"
1929 );
1930 assert_eq!(
1931 reach.below_left,
1932 libaom_bottom_left(side, x, y, height, fctx),
1933 "side={side} x={x} y={y}: below_left"
1934 );
1935 }
1936 }
1937 }
1938 }
1939
1940 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
1941 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
1942 /// column inside the superblock) may read the below-left samples the
1943 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
1944 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
1945 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
1946 /// stream that partitions that small first hits the still-refused
1947 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
1948 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
1949 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
1950 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
1951 /// pixels -- lane-palette2 r12: the square multi-TU path used the
1952 /// standalone-block tables instead of this rule and granted a 16x16
1953 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
1954 #[test]
1955 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
1956 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
1957 // *_count_unit = tx size / 4.
1958 fn libaom_tr(
1959 bw: usize,
1960 bh: usize,
1961 col_off: usize,
1962 row_off: usize,
1963 tx: usize,
1964 blk: bool,
1965 ) -> bool {
1966 let (plane_bw_unit, count) = (bw / 4, tx / 4);
1967 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
1968 let _ = bh;
1969 if row_off_u > 0 {
1970 col_off_u + count < plane_bw_unit
1971 } else if col_off_u + count < plane_bw_unit {
1972 true
1973 } else {
1974 blk
1975 }
1976 }
1977 fn libaom_bl(
1978 bw: usize,
1979 bh: usize,
1980 col_off: usize,
1981 row_off: usize,
1982 tx: usize,
1983 blk: bool,
1984 ) -> bool {
1985 let (plane_bh_unit, count) = (bh / 4, tx / 4);
1986 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
1987 let _ = bw;
1988 if col_off_u > 0 {
1989 false
1990 } else if row_off_u + count < plane_bh_unit {
1991 true
1992 } else {
1993 blk
1994 }
1995 }
1996 for &(bw, bh) in &[
1997 (8, 8),
1998 (16, 16),
1999 (32, 32),
2000 (64, 64),
2001 (16, 8),
2002 (8, 16),
2003 (32, 16),
2004 (16, 32),
2005 (64, 32),
2006 (32, 64),
2007 ] {
2008 for &tx in &[4usize, 8, 16, 32] {
2009 if tx > bw.min(bh) {
2010 continue;
2011 }
2012 for row_off in (0..bh).step_by(tx) {
2013 for col_off in (0..bw).step_by(tx) {
2014 for &blk in &[
2015 Reach {
2016 above_right: false,
2017 below_left: false,
2018 },
2019 Reach {
2020 above_right: true,
2021 below_left: true,
2022 },
2023 ] {
2024 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
2025 assert_eq!(
2026 got.above_right,
2027 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
2028 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
2029 );
2030 assert_eq!(
2031 got.below_left,
2032 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
2033 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
2034 );
2035 }
2036 }
2037 }
2038 }
2039 }
2040 }
2041
2042 #[test]
2043 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
2044 let fctx = &crate::decode::FrameCtx::for_encoder();
2045 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
2046 // Interior superblock, so neither the frame edge nor the col == 0 /
2047 // last-row early returns answer instead of the table.
2048 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
2049 let mut flipped = 0;
2050 for row in 0..8 {
2051 for col in 1..8 {
2052 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
2053 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
2054 let vert = {
2055 let _guard = Reach::vert_ab_partition();
2056 Reach::of(8, x, y, width, height, fctx).below_left
2057 };
2058 // The TR square of a VERT_A/_B sits at an even row, odd
2059 // column; every other slot must be untouched by the guard.
2060 if row % 2 == 0 && col % 2 == 1 {
2061 assert!(!raster, "raster below_left at row={row} col={col}");
2062 assert!(vert, "vert below_left at row={row} col={col}");
2063 flipped += 1;
2064 } else {
2065 assert_eq!(raster, vert, "guard moved row={row} col={col}");
2066 }
2067 }
2068 }
2069 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
2070 // The guard is scoped: it must not leak past its own block.
2071 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
2072 }
2073
2074 /// An odd width or height is refused by name, not by however the padder
2075 /// or the block coder would happen to fail on it.
2076 #[test]
2077 fn odd_dimensions_are_refused() {
2078 let _knobs = crate::speed::knob_read();
2079 let fctx = &crate::decode::FrameCtx::for_encoder();
2080 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
2081 let picture = Picture::grey(width, height);
2082 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
2083 .expect_err(&format!("{width}x{height} is odd and must be refused"));
2084 assert!(
2085 err.to_string().contains("even"),
2086 "{width}x{height}: error was {err}"
2087 );
2088 }
2089 }
2090
2091 /// A sequence at a size that is not a multiple of the block grid decodes
2092 /// to the right frame count and the right size for every frame,
2093 /// including the inter frames whose reference is the previous frame's
2094 /// own (padded) reconstruction.
2095 #[test]
2096 fn sequence_round_trips_at_a_non_multiple_size() {
2097 let _knobs = crate::speed::knob_read();
2098 let fctx = &crate::decode::FrameCtx::for_encoder();
2099 if !have_ffmpeg() {
2100 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
2101 return;
2102 }
2103 let (width, height) = (160usize, 96usize);
2104 let pictures: Vec<Picture> = (0..3)
2105 .map(|i| panned_test_card(width, height, i * 3))
2106 .collect();
2107 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
2108 assert_eq!(encoded.frames.len(), 3);
2109 for (i, frame) in encoded.frames.iter().enumerate() {
2110 assert_eq!(
2111 (frame.reconstruction.width, frame.reconstruction.height),
2112 (width, height),
2113 "frame {i}: reconstruction size"
2114 );
2115 }
2116 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
2117 // true (display) size a sequence's frames share, not the padded one.
2118 assert_eq!(
2119 ffprobe_size(&encoded.stream),
2120 (width as u32, height as u32),
2121 "sequence: ffprobe reports the true (display) size"
2122 );
2123 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
2124 assert_eq!(decoded.len(), 3, "decoded frame count");
2125 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
2126 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
2127 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
2128 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
2129 }
2130 }
2131
2132 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
2133 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
2134 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
2135 /// `pos + side_mi / 2 < bound` boundary), which is the case
2136 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
2137 /// refusing. A key frame alone already covered this size; this proves the
2138 /// inter tile writer's parity with it across a real multi-frame export.
2139 #[test]
2140 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
2141 let _knobs = crate::speed::knob_read();
2142 let fctx = &crate::decode::FrameCtx::for_encoder();
2143 if !have_ffmpeg() {
2144 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
2145 return;
2146 }
2147 let (width, height) = (1280usize, 720usize);
2148 let pictures: Vec<Picture> = (0..3)
2149 .map(|i| panned_test_card(width, height, i * 3))
2150 .collect();
2151 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
2152 assert_eq!(encoded.frames.len(), 3);
2153 for (i, frame) in encoded.frames.iter().enumerate() {
2154 assert_eq!(
2155 (frame.reconstruction.width, frame.reconstruction.height),
2156 (width, height),
2157 "frame {i}: reconstruction size"
2158 );
2159 }
2160 assert_eq!(
2161 ffprobe_size(&encoded.stream),
2162 (width as u32, height as u32),
2163 "ffprobe reports the true (display) 1280x720 size"
2164 );
2165 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
2166 assert_eq!(decoded.len(), 3, "decoded frame count");
2167 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
2168 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
2169 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
2170 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
2171 }
2172 }
2173
2174 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
2175 /// leaf's own half (`has_half` at the SUB level) itself straddles the
2176 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
2177 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
2178 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
2179 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
2180 /// straddling-16x16 branch), so an inter frame no longer refuses this
2181 /// size either. This only proves the encoder does not error out -- see
2182 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
2183 /// decoder-clean proof (a 3-frame sequence, so the inter path is
2184 /// actually exercised).
2185 #[test]
2186 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
2187 let _knobs = crate::speed::knob_read();
2188 let fctx = &crate::decode::FrameCtx::for_encoder();
2189 let (width, height) = (640usize, 360usize);
2190 let picture = Picture::grey(width, height);
2191 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
2192 .expect("key frame now codes the mod-32==8 straddle");
2193
2194 // `encode_sequence`'s second frame is the inter path: same size, now
2195 // wired the same way.
2196 let pictures = vec![picture.clone(), picture];
2197 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
2198 .expect("inter frame now codes the mod-32==8 straddle too");
2199 }
2200
2201 /// The r15 fix at production size: three 640x360 key frames (inter is
2202 /// still refused at this size, per the test above, so this stands in for
2203 /// the charter's "3-frame sequence" using three independent key frames of
2204 /// shifted content), each proven decoder-clean through ffmpeg rather than
2205 /// only encoder-clean.
2206 #[test]
2207 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
2208 let _knobs = crate::speed::knob_read();
2209 let fctx = &crate::decode::FrameCtx::for_encoder();
2210 if !have_ffmpeg() {
2211 eprintln!(
2212 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
2213 no ffmpeg"
2214 );
2215 return;
2216 }
2217 let (width, height) = (640usize, 360usize);
2218 for shift in [0i64, 7, 19] {
2219 let picture = panned_test_card(width, height, shift);
2220 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2221 let decoded = ffmpeg_decode(&encoded.stream, width, height);
2222 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
2223 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
2224 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
2225 }
2226 }
2227
2228 /// The 640x360 straddle class, but through the inter path an actual
2229 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
2230 /// proves the leaf-8 inter stream this round wires up is not just
2231 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
2232 #[test]
2233 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
2234 let _knobs = crate::speed::knob_read();
2235 let fctx = &crate::decode::FrameCtx::for_encoder();
2236 if !have_ffmpeg() {
2237 eprintln!(
2238 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
2239 );
2240 return;
2241 }
2242 let (width, height) = (640usize, 360usize);
2243 let pictures: Vec<Picture> = (0..4)
2244 .map(|i| panned_test_card(width, height, i * 3))
2245 .collect();
2246 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
2247 assert_eq!(encoded.frames.len(), 4);
2248 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
2249 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
2250 }
2251 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
2252 assert_eq!(decoded.len(), 4, "decoded frame count");
2253 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
2254 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
2255 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
2256 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
2257 }
2258 }
2259
2260 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
2261 pub(super) fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
2262 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
2263 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
2264 .args(["-vf", &format!("scale={width}:{height}")])
2265 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())
2266 .expect("ffmpeg failed to run");
2267 assert!(
2268 out.status.success(),
2269 "ffmpeg: {}",
2270 String::from_utf8_lossy(&out.stderr)
2271 );
2272 let (luma, chroma) = (width * height, width * height / 4);
2273 assert_eq!(
2274 out.stdout.len(),
2275 luma + 2 * chroma,
2276 "expected one 4:2:0 frame"
2277 );
2278 Picture {
2279 width,
2280 height,
2281 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
2282 u: out.stdout[luma..luma + chroma]
2283 .iter()
2284 .map(|&v| u16::from(v))
2285 .collect(),
2286 v: out.stdout[luma + chroma..]
2287 .iter()
2288 .map(|&v| u16::from(v))
2289 .collect(),
2290 }
2291 }
2292
2293 /// Prints what the mode search saves over DC prediction alone, for the
2294 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
2295 /// weight the search puts on rate can be swept.
2296 #[test]
2297 #[ignore = "a sweep, not a gate"]
2298 fn probe_lambda() {
2299 let _knobs = crate::speed::knob_read();
2300 let fctx = &crate::decode::FrameCtx::for_encoder();
2301 let mut pictures = vec![
2302 ("test card".to_string(), test_card(160, 96)),
2303 ("stripes".to_string(), stripes(160, 96, true)),
2304 ];
2305 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
2306 for entry in clips.split(':').filter(|e| !e.is_empty()) {
2307 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
2308 let name = path.rsplit('/').next().unwrap_or(path).to_string();
2309 pictures.push((name, clip_frame(path, skip, 640, 352)));
2310 }
2311 }
2312 for (name, picture) in pictures {
2313 let dc = ladder(&picture, &[DC_PRED], fctx);
2314 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
2315 println!(
2316 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
2317 bd_rate(&dc, &searched) * 100.0,
2318 10f64.powf(searched[1].1),
2319 searched[1].0,
2320 10f64.powf(dc[1].1),
2321 dc[1].0,
2322 );
2323 }
2324 }
2325
2326 /// Prints the whole mode-search ladder, so two builds of the search can be
2327 /// compared against each other rather than each against its own baseline.
2328 #[test]
2329 #[ignore = "a sweep, not a gate"]
2330 fn probe_ladder() {
2331 let _knobs = crate::speed::knob_read();
2332 let fctx = &crate::decode::FrameCtx::for_encoder();
2333 for (name, picture) in sweep_pictures() {
2334 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
2335 let points = all
2336 .iter()
2337 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
2338 .collect::<Vec<_>>()
2339 .join(" ");
2340 println!("ladder {name}: {points}");
2341 }
2342 }
2343
2344 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
2345 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
2346 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
2347 #[test]
2348 // ROBUST-RED on this tree, and the red is in the MEASURE, not the codec:
2349 // the `stripes` picture codes LOSSLESSLY at q110/90/70, so both ladders
2350 // come back as three identical `(inf, 1.8260748027008264)` points and
2351 // `bd_rate` has an empty trapezoid to integrate, which panics with
2352 // "the two ladders have to overlap in PSNR". Row 1 (`test card`) still
2353 // prints its number before the panic. Point `EC_AV1_CLIPS` at a real lossy
2354 // clip, or read only row 1.
2355 #[ignore = "a sweep, not a gate; PANICS on its own lossless synthetic rows (stripes is lossless at q110/90/70, so bd_rate has no PSNR overlap) -- point EC_AV1_CLIPS at a lossy clip"]
2356 pub(super) fn probe_split() {
2357 let _knobs = crate::speed::knob_read();
2358 let fctx = &crate::decode::FrameCtx::for_encoder();
2359 for (name, picture) in sweep_pictures() {
2360 let ladder = |split: bool| {
2361 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
2362 .iter()
2363 .map(|&q| {
2364 let encoded = encode_key_frame_inner(
2365 &picture,
2366 q,
2367 0.5,
2368 &KEY_FRAME_MODES,
2369 split,
2370 (picture.width, picture.height),
2371 unspecified_color_config(),
2372 fctx,
2373 )
2374 .unwrap();
2375 (
2376 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
2377 (encoded.stream.len() as f64).log10(),
2378 )
2379 })
2380 .collect();
2381 points.sort_by(|a, b| a.0.total_cmp(&b.0));
2382 points
2383 };
2384 let (whole, split) = (ladder(false), ladder(true));
2385 let blocks = encode_key_frame_inner(
2386 &picture,
2387 90,
2388 0.5,
2389 &KEY_FRAME_MODES,
2390 true,
2391 (picture.width, picture.height),
2392 unspecified_color_config(),
2393 fctx,
2394 )
2395 .unwrap()
2396 .modes
2397 .len();
2398 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
2399 println!(
2400 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
2401 bd_rate(&whole, &split) * 100.0
2402 );
2403 }
2404 }
2405
2406 /// A striped picture, running one way or the other. The stripes are what
2407 /// separates a vertical predictor from a horizontal one: a mode search
2408 /// reading a transposed edge would pick the wrong one of the pair, which no
2409 /// symmetric picture would show.
2410 pub(super) fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
2411 let mut picture = Picture::grey(width, height);
2412 for y in 0..height {
2413 for x in 0..width {
2414 let along = if vertical { x } else { y };
2415 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
2416 }
2417 }
2418 picture
2419 }
2420
2421 /// Where two planes first disagree, and by how much: a mismatch reported as
2422 /// a position says which block and which sample of it went wrong, which a
2423 /// pair of thousand-sample arrays does not. A length difference counts as a
2424 /// disagreement: `zip` stops at the shorter plane, so a short one would
2425 /// otherwise compare exact over the prefix the two share.
2426 pub(super) fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
2427 if let Some(i) = ours.iter().zip(theirs).position(|(a, b)| a != b) {
2428 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
2429 return Some(format!(
2430 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
2431 i % width,
2432 i / width,
2433 ours[i],
2434 theirs[i]
2435 ));
2436 }
2437 if ours.len() != theirs.len() {
2438 return Some(format!(
2439 "no sample in the shared prefix differs, but ours is {} samples and theirs is {}",
2440 ours.len(),
2441 theirs.len()
2442 ));
2443 }
2444 None
2445 }
2446
2447 /// Every mode the encoder offers has to predict what the decoder predicts,
2448 /// not just the ones a particular picture happens to choose: each is forced
2449 /// over a whole picture and the reconstruction gated against ffmpeg.
2450 #[test]
2451 fn every_mode_decodes_to_what_the_encoder_predicted() {
2452 let _knobs = crate::speed::knob_write();
2453 let fctx = &crate::decode::FrameCtx::for_encoder();
2454 if !have_ffmpeg() {
2455 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
2456 return;
2457 }
2458 // A mode ablation measures the MODE search: a filter-intra block is
2459 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
2460 // "the encoder coded something else" check for a reason that is not
2461 // about the mode search at all.
2462 force_filter_intra(Some(false));
2463 // 128 wide is a whole number of superblocks and 160 is not: the last
2464 // superblock of a 160-wide row is half a one, whose blocks have no
2465 // above-right samples inside the frame at all.
2466 for (width, height) in [(128, 96), (160, 96)] {
2467 let picture = test_card(width, height);
2468 for mode in KEY_FRAME_MODES {
2469 let encoded =
2470 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx)
2471 .unwrap();
2472 let decoded = ffmpeg_decode(&encoded.stream, width, height);
2473 for (plane, ours, theirs, stride) in [
2474 ("luma", &encoded.reconstruction.y, &decoded.y, width),
2475 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
2476 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
2477 ] {
2478 assert!(
2479 first_difference(ours, theirs, stride).is_none(),
2480 "{width}x{height} mode {mode}, {plane}: {}",
2481 first_difference(ours, theirs, stride).unwrap()
2482 );
2483 }
2484 assert!(
2485 encoded.modes.iter().all(|&m| m == mode),
2486 "mode {mode}: the encoder coded something else"
2487 );
2488 }
2489 }
2490 }
2491
2492 /// The search has to follow the picture: vertical stripes are cheapest
2493 /// predicted from the row above, horizontal ones from the column to the
2494 /// left. Reading the edges the other way round would swap the two answers
2495 /// while leaving every fidelity gate intact.
2496 #[test]
2497 fn the_search_picks_the_direction_the_picture_runs() {
2498 let _knobs = crate::speed::knob_write();
2499 let fctx = &crate::decode::FrameCtx::for_encoder();
2500 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
2501 // a filter-intra block is coded `DC_PRED` whatever mode the arm
2502 // offers, and these stripes are SCREEN content, where the filter arm
2503 // now searches its own transform depth (lane-fitu) and wins outright
2504 // -- which says nothing about the mode search this gate measures.
2505 force_filter_intra(Some(false));
2506 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
2507 let picture = stripes(128, 96, vertical);
2508 // Only the pair, because on stripes a third mode predicts exactly
2509 // what the right one of the pair does -- PAETH reads the corner and
2510 // the left column, which a striped picture makes equal -- and the
2511 // tie then goes to whichever is cheaper to name, which is not what
2512 // this gate is about.
2513 let encoded =
2514 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx)
2515 .unwrap();
2516 // The first block of the picture has neither neighbour, so it
2517 // cannot tell the modes apart; every other one can.
2518 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
2519 assert!(
2520 picked * 2 > encoded.modes.len() - 1,
2521 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
2522 encoded.modes.len() - 1,
2523 encoded.modes
2524 );
2525 }
2526 }
2527
2528 /// What the search is for: the same picture, at the same quantizer, coded
2529 /// smaller and more faithfully than DC alone can manage.
2530 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
2531 /// between the two rate-distortion curves in log-rate against PSNR, as a
2532 /// fraction of the reference's rate. Negative means the second curve costs
2533 /// less for the same picture.
2534 pub(super) fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
2535 let low = reference[0].0.max(other[0].0);
2536 let high = reference[reference.len() - 1]
2537 .0
2538 .min(other[other.len() - 1].0);
2539 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
2540 // the non-directional one on the synthetic diagonals -- every point
2541 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
2542 // to integrate over any more. A curve that dominates that way has
2543 // saved everything the measure can express (the
2544 // `instrument-at-bound` class: the answer is at the instrument's own
2545 // edge, not undefined), so name it rather than panicking; anything
2546 // less clean than strict dominance still is.
2547 if high <= low {
2548 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
2549 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
2550 let dominates =
2551 other[0].0 > reference[reference.len() - 1].0 && other_hi_rate <= ref_lo_rate;
2552 assert!(
2553 dominates,
2554 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
2555 );
2556 return -1.0;
2557 }
2558 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
2559 let i = curve
2560 .windows(2)
2561 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
2562 .unwrap_or(0);
2563 let (x0, y0) = curve[i];
2564 let (x1, y1) = curve[i + 1];
2565 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
2566 };
2567 let steps = 64;
2568 let mut area = 0.0;
2569 for step in 0..steps {
2570 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
2571 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
2572 }
2573 10f64.powf(area / f64::from(steps)) - 1.0
2574 }
2575
2576 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
2577 /// fidelity.
2578 pub(super) fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
2579 // A mode ablation measures the MODE search: the palette would code
2580 // these synthetic two-colour pictures losslessly under every arm and
2581 // leave nothing to compare (see [`force_screen`]).
2582 force_screen(Some(false));
2583 // Same reason, for the filter-intra candidate: it wins blocks under
2584 // BOTH arms of a mode ablation and so cancels the difference the
2585 // ablation measures (class `gate-recipe-confound`).
2586 force_filter_intra(Some(false));
2587 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
2588 .iter()
2589 .map(|&q| {
2590 let encoded =
2591 encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
2592 (
2593 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
2594 (encoded.stream.len() as f64).log10(),
2595 )
2596 })
2597 .collect();
2598 points.sort_by(|a, b| a.0.total_cmp(&b.0));
2599 points
2600 }
2601
2602 /// What the search is for: the same pictures cost less to code at the same
2603 /// fidelity than DC prediction alone can manage. A picture that runs one
2604 /// way saves far more than a busy one, which is the shape a working
2605 /// directional pair has.
2606 #[test]
2607 fn the_search_beats_dc_alone() {
2608 let _knobs = crate::speed::knob_read();
2609 let fctx = &crate::decode::FrameCtx::for_encoder();
2610 for (name, picture, want) in [
2611 ("test card", test_card(160, 96), -0.05),
2612 ("stripes", stripes(160, 96, true), -0.40),
2613 ] {
2614 let saved = bd_rate(
2615 &ladder(&picture, &[DC_PRED], fctx),
2616 &ladder(&picture, &NON_DIRECTIONAL, fctx),
2617 );
2618 assert!(
2619 saved < want,
2620 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
2621 saved * 100.0,
2622 -want * 100.0
2623 );
2624 }
2625 }
2626
2627 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
2628 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
2629 pub(super) fn sweep_pictures() -> Vec<(String, Picture)> {
2630 let mut pictures = vec![
2631 ("test card".to_string(), test_card(160, 96)),
2632 ("stripes".to_string(), stripes(160, 96, true)),
2633 ("diagonal".to_string(), diagonal(160, 96, true)),
2634 ];
2635 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
2636 for entry in clips.split(':').filter(|e| !e.is_empty()) {
2637 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
2638 let name = path.rsplit('/').next().unwrap_or(path).to_string();
2639 pictures.push((name, clip_frame(path, skip, 640, 352)));
2640 }
2641 }
2642 pictures
2643 }
2644
2645 /// What the six directional modes are worth, per picture, at whatever
2646 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
2647 /// no further, and how often the search picks one.
2648 #[test]
2649 #[ignore = "a sweep, not a gate"]
2650 fn probe_directional() {
2651 let _knobs = crate::speed::knob_write();
2652 let fctx = &crate::decode::FrameCtx::for_encoder();
2653 for (name, picture) in sweep_pictures() {
2654 let dc = ladder(&picture, &[DC_PRED], fctx);
2655 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
2656 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
2657 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
2658 let directional = encoded
2659 .modes
2660 .iter()
2661 .filter(|&&m| (3..=8).contains(&m))
2662 .count();
2663 // A picture whose ladders sit at different fidelities altogether
2664 // has no BD-rate to report -- see the flat-sample-window class.
2665 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
2666 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
2667 };
2668 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
2669 if overlap(a, b) {
2670 format!("{:+.2}%", bd_rate(a, b) * 100.0)
2671 } else {
2672 "no overlap".to_string()
2673 }
2674 };
2675 println!(
2676 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
2677 against(&flat, &all),
2678 against(&dc, &all),
2679 encoded.modes.len(),
2680 );
2681 }
2682 }
2683
2684 /// A picture whose stripes run along a diagonal, one way or the other.
2685 /// This is to the directional modes what [`stripes`] is to the vertical and
2686 /// horizontal pair: a predictor that walked the edge in the wrong direction
2687 /// would answer the two pictures the same way round.
2688 pub(super) fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
2689 let mut picture = Picture::grey(width, height);
2690 for y in 0..height {
2691 for x in 0..width {
2692 let along = if down_right { x + height - y } else { x + y };
2693 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
2694 }
2695 }
2696 picture
2697 }
2698
2699 /// The mode picked by the most blocks of a picture, ignoring the first
2700 /// block, which has no neighbours to tell the modes apart with.
2701 pub(super) fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
2702 // A mode ablation measures the MODE search: the palette would code
2703 // these synthetic two-colour pictures losslessly under every arm and
2704 // leave nothing to compare (see [`force_screen`]).
2705 force_screen(Some(false));
2706 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
2707 let blocks = &encoded.modes[1..];
2708 let mut counts = [0usize; 13];
2709 for &mode in blocks {
2710 counts[usize::from(mode)] += 1;
2711 }
2712 let (mode, count) = counts
2713 .iter()
2714 .enumerate()
2715 .max_by_key(|&(_, count)| *count)
2716 .expect("thirteen modes");
2717 (mode as u8, *count, blocks.len())
2718 }
2719
2720 /// The search has to follow a diagonal the way it runs: stripes down and to
2721 /// the right are cheapest predicted at 135 degrees, stripes down and to the
2722 /// left at 45. A walk that stepped the wrong way along the edge, or read
2723 /// the above row where it should read the left column, would swap these.
2724 #[test]
2725 fn the_search_picks_the_diagonal_the_picture_runs() {
2726 let _knobs = crate::speed::knob_write();
2727 let fctx = &crate::decode::FrameCtx::for_encoder();
2728 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
2729 let picture = diagonal(160, 96, down_right);
2730 let (mode, count, blocks) = favourite_mode(&picture, fctx);
2731 assert_eq!(
2732 mode, want,
2733 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
2734 );
2735 }
2736 }
2737
2738 /// What the directional modes are for: a picture that runs along a diagonal
2739 /// costs far less to code with them than the seven that read only their own
2740 /// edges can manage, and a picture that runs no particular way costs no
2741 /// more. The second half is the one that bites: a mode set the search
2742 /// cannot price is a mode set that loses rate on content that does not want
2743 /// it, which is what costing the mode symbol is for.
2744 #[test]
2745 fn the_diagonals_beat_the_modes_that_read_no_further() {
2746 let _knobs = crate::speed::knob_read();
2747 let fctx = &crate::decode::FrameCtx::for_encoder();
2748 for (name, picture, want) in [
2749 ("down-right", diagonal(160, 96, true), -0.20),
2750 ("down-left", diagonal(160, 96, false), -0.20),
2751 ("test card", test_card(160, 96), 0.01),
2752 ] {
2753 let saved = bd_rate(
2754 &ladder(&picture, &NON_DIRECTIONAL, fctx),
2755 &ladder(&picture, &KEY_FRAME_MODES, fctx),
2756 );
2757 assert!(
2758 saved < want,
2759 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
2760 saved * 100.0,
2761 -want * 100.0
2762 );
2763 }
2764 }
2765
2766 /// A mode the encoder cannot predict must be refused rather than coded as
2767 /// something else, and a search with nothing to choose from likewise.
2768 #[test]
2769 fn a_mode_the_encoder_cannot_predict_is_refused() {
2770 let _knobs = crate::speed::knob_read();
2771 let fctx = &crate::decode::FrameCtx::for_encoder();
2772 let picture = test_card(64, 64);
2773 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
2774 .unwrap_err()
2775 .to_string();
2776 assert!(
2777 message.contains("intra mode 13"),
2778 "the refusal must name the mode, got {message}"
2779 );
2780 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
2781 }
2782
2783 /// The picture that comes back is the picture that went in, to within the
2784 /// quantizer. A prediction that read the wrong neighbours, or a block
2785 /// written into the wrong place, would still decode to what the encoder
2786 /// reconstructed — it is this gate that says the reconstruction is of the
2787 /// right picture.
2788 #[test]
2789 fn the_encoded_picture_is_the_one_that_went_in() {
2790 let _knobs = crate::speed::knob_read();
2791 let fctx = &crate::decode::FrameCtx::for_encoder();
2792 let picture = test_card(160, 96);
2793 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2794 let luma = psnr(&encoded.reconstruction.y, &picture.y);
2795 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
2796 for (plane, (got, want)) in [
2797 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
2798 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
2799 ]
2800 .iter()
2801 .enumerate()
2802 {
2803 let chroma = psnr(got, want);
2804 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
2805 }
2806 }
2807
2808 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
2809 /// does the opposite. Both are monotone, which is what a rate-distortion
2810 /// loop above this will assume.
2811 #[test]
2812 fn fidelity_and_rate_move_with_the_quantizer() {
2813 let _knobs = crate::speed::knob_read();
2814 let fctx = &crate::decode::FrameCtx::for_encoder();
2815 let picture = test_card(128, 128);
2816 let mut previous: Option<(usize, f64)> = None;
2817 for &q in &[70u8, 90, 110] {
2818 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
2819 let quality = psnr(&encoded.reconstruction.y, &picture.y);
2820 if let Some((bytes, better)) = previous {
2821 assert!(
2822 encoded.stream.len() < bytes,
2823 "q {q}: {} bytes",
2824 encoded.stream.len()
2825 );
2826 assert!(quality < better, "q {q}: PSNR {quality}");
2827 }
2828 previous = Some((encoded.stream.len(), quality));
2829 }
2830
2831 // The deadzone half of this claim lives in
2832 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
2833 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
2834 // every zeroing, the deadzone no longer moves a coded stream
2835 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
2836 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
2837 // job, not a quantiser defect.
2838
2839 // Bytes must not jump up across a q-context boundary: a wrong CDF
2840 // table for the far side would show up as a rate discontinuity here,
2841 // even though a coarser quantizer always codes no more than a finer
2842 // one on the same picture.
2843 //
2844 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
2845 // chroma searches its own mode, a coarser quantizer can pick a
2846 // *different* uv_mode on a block whose modes now cost nearly the
2847 // same, and the search prices that symbol against the static default
2848 // CDF while the writer codes it against an adapted one -- 311 -> 319
2849 // bytes at q 120->121 on this picture. The table this gate is really
2850 // watching would move the rate by far more than the mode churn does.
2851 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
2852 // same block can also change transform DEPTH between two neighbouring
2853 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
2854 // symbol is priced off the static CDF row 0 for the same reason the
2855 // uv_mode one is.
2856 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
2857 // path is pricing through the adapting CDF state (what
2858 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
2859 // drift of), after which the exact bound comes back.
2860 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
2861 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx)
2862 .unwrap()
2863 .stream
2864 .len();
2865 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx)
2866 .unwrap()
2867 .stream
2868 .len();
2869 assert!(
2870 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
2871 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
2872 );
2873 }
2874 }
2875
2876 /// A flat picture is a flat stream: every block predicts its neighbours'
2877 /// average, which is the picture's own value, and codes nothing.
2878 #[test]
2879 fn a_flat_picture_costs_almost_nothing() {
2880 let _knobs = crate::speed::knob_read();
2881 let fctx = &crate::decode::FrameCtx::for_encoder();
2882 let mut picture = Picture::grey(128, 128);
2883 picture.y.fill(97);
2884 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
2885 // The first block has no neighbour and predicts 128, so it carries a
2886 // DC; every block after it predicts 97 and carries nothing.
2887 assert!(
2888 encoded.stream.len() < 100,
2889 "{} bytes for a flat picture",
2890 encoded.stream.len()
2891 );
2892 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
2893 assert_eq!(s, 97, "sample {i} of a flat picture");
2894 }
2895 }
2896
2897 /// The sizes the encoder refuses, refused for a reason rather than by
2898 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
2899 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
2900 /// lands past the halfway point of whichever block it falls in, so
2901 /// `PARTITION_NONE` or a single gathered split flag still says everything
2902 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
2903 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
2904 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
2905 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
2906 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
2907 /// refusal here claimed otherwise and was wrong; see
2908 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
2909 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
2910 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
2911 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
2912 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
2913 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
2914 /// still refused is a malformed picture.
2915 #[test]
2916 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
2917 let _knobs = crate::speed::knob_read();
2918 let fctx = &crate::decode::FrameCtx::for_encoder();
2919 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
2920 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
2921 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
2922 .expect("36 luma columns still round up to an even MiCols");
2923
2924 let mut short = Picture::grey(64, 64);
2925 short.u.truncate(10);
2926 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
2927 }
2928
2929 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
2930 /// column half only (`has_half` false on cols, true on rows) -- exactly
2931 /// the single-axis straddle lane-av1-rect r7 wires through
2932 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
2933 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
2934 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
2935 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
2936 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
2937 /// `partition_context_lookup` entry this writer ever produces (no 4x4
2938 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
2939 /// leaf regardless of neighbour state -- our writer already agreed with
2940 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
2941 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
2942 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
2943 /// it does not regress the gate. r11 tell-for-tell traced two further,
2944 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
2945 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
2946 /// leaves, when the second leaf's true above (or left) neighbour is the
2947 /// first leaf itself -- fixed by threading the first leaf's mode into the
2948 /// second leaf's context, mi-precise, like `record_mi` already does for
2949 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
2950 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
2951 /// `reduced_tx_set` is false), but this crate's key frames set
2952 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
2953 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
2954 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
2955 /// symbol bits to desync everything after it. Fixed with a new
2956 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
2957 /// eset/size slot). Both fixes are provably correct against libaom
2958 /// source and each closed part of the gap (leaf0's `eob` went from a
2959 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
2960 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
2961 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
2962 /// (do not reuse r11's committed logs, which predate its own fixes) and
2963 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
2964 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
2965 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
2966 /// every other `write_block` caller at 16x16 and up already passes
2967 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
2968 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
2969 /// different amount of arithmetic range and derailed everything after
2970 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
2971 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
2972 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
2973 /// never updating those coarse arrays itself -- so a *second* straddling
2974 /// 16x16 quadrant stacked above or left of the first (never covered by
2975 /// r11's same-call `prev_leaf` override, which only threads state
2976 /// between the two leaves of one shared quadrant) read whatever stale
2977 /// mode sat in that slot before either leaf ran. Fixed by writing the
2978 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
2979 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
2980 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
2981 /// offset of a single unit; fixing (3)+(4) together still leaves a
2982 /// residual divergence one leaf further in -- the decoder now reads
2983 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
2984 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
2985 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
2986 /// desyncs the stream by exactly the width of one earlier symbol -- not
2987 /// yet isolated to a single named symbol. r15 found the last bug: the
2988 /// header fix from r14 explained the rng skew fully, and the remaining
2989 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
2990 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
2991 /// loop, once per leaf, so the first leaf's write clobbered the true
2992 /// external neighbour mode the second leaf of the *same* straddling
2993 /// quadrant still needed for its non-adjacency axis (a column-straddle
2994 /// case: two leaves share one `outer_at` column index, so leaf 1's
2995 /// write to `left_mode[r]` overwrote the real western neighbour before
2996 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
2997 /// doing it once, after the whole leaf loop, from the last (bottom/
2998 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
2999 #[test]
3000 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
3001 let _knobs = crate::speed::knob_read();
3002 let fctx = &crate::decode::FrameCtx::for_encoder();
3003 if !have_ffmpeg() {
3004 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
3005 return;
3006 }
3007 let (width, height) = (40usize, 32usize);
3008 let picture = test_card(width, height);
3009 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3010 assert_eq!(
3011 (encoded.reconstruction.width, encoded.reconstruction.height),
3012 (width, height)
3013 );
3014 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
3015 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
3016 }
3017 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3018 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
3019 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
3020 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
3021 }
3022
3023 /// A frame of real video, rather than a picture built to be easy.
3024 ///
3025 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
3026 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
3027 /// encoder's reconstruction has to survive the same equality gate as the
3028 /// synthetic pictures — real video reaches contexts a test card does not.
3029 #[test]
3030 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
3031 let _knobs = crate::speed::knob_read();
3032 let fctx = &crate::decode::FrameCtx::for_encoder();
3033 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
3034 eprintln!(
3035 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
3036 set EC_AV1_CLIP to a clip"
3037 );
3038 return;
3039 };
3040 if !have_ffmpeg() {
3041 eprintln!(
3042 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
3043 );
3044 return;
3045 }
3046 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
3047 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
3048 // test quick while still spanning many superblocks.
3049 let (width, height) = (640usize, 352usize);
3050 let picture = clip_frame(&clip, &skip, width, height);
3051
3052 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
3053 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3054 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
3055 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
3056 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
3057 eprintln!(
3058 "{} bytes, luma PSNR {:.2} dB",
3059 encoded.stream.len(),
3060 psnr(&decoded.y, &picture.y)
3061 );
3062 }
3063
3064 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
3065 /// sequence of these is a translation a motion search can actually find
3066 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
3067 /// inter frame's rate against the key frame's is measuring the same
3068 /// picture moving, not two different pictures.
3069 pub(super) fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
3070 let mut picture = Picture::grey(width, height);
3071 for y in 0..height {
3072 for x in 0..width {
3073 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
3074 let gradient = sx * 200.0 / width as f64;
3075 let ripple = 30.0
3076 * (sx * std::f64::consts::PI / 23.0).sin()
3077 * (y as f64 * std::f64::consts::PI / 37.0).cos();
3078 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
3079 40.0
3080 } else {
3081 0.0
3082 };
3083 picture.y[y * width + x] =
3084 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
3085 }
3086 }
3087 for y in 0..height / 2 {
3088 for x in 0..width / 2 {
3089 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
3090 let i = y * width / 2 + x;
3091 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
3092 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
3093 }
3094 }
3095 picture
3096 }
3097
3098 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
3099 pub(super) fn ffmpeg_decode_sequence(
3100 stream: &[u8],
3101 width: usize,
3102 height: usize,
3103 frames: usize,
3104 ) -> Vec<Picture> {
3105 let out = run_with_stdin(
3106 Command::new("ffmpeg").args([
3107 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
3108 ]),
3109 stream,
3110 );
3111 assert!(
3112 out.status.success(),
3113 "ffmpeg refused the stream: {}",
3114 String::from_utf8_lossy(&out.stderr)
3115 );
3116 let (luma, chroma) = (width * height, width * height / 4);
3117 let frame_bytes = luma + 2 * chroma;
3118 assert_eq!(
3119 out.stdout.len(),
3120 frame_bytes * frames,
3121 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
3122 String::from_utf8_lossy(&out.stderr)
3123 );
3124 (0..frames)
3125 .map(|i| {
3126 let base = i * frame_bytes;
3127 Picture {
3128 width,
3129 height,
3130 y: out.stdout[base..base + luma]
3131 .iter()
3132 .map(|&v| u16::from(v))
3133 .collect(),
3134 u: out.stdout[base + luma..base + luma + chroma]
3135 .iter()
3136 .map(|&v| u16::from(v))
3137 .collect(),
3138 v: out.stdout[base + luma + chroma..base + frame_bytes]
3139 .iter()
3140 .map(|&v| u16::from(v))
3141 .collect(),
3142 }
3143 })
3144 .collect()
3145 }
3146
3147 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
3148 /// makes for a key frame, extended down the reference chain: each inter
3149 /// frame's reconstruction predicts from the previous frame's own decoded
3150 /// reconstruction, so a single sample of drift anywhere would propagate
3151 /// into every frame after it -- which is why every frame is checked, not
3152 /// just the last one, and why this is an equality and not a tolerance.
3153 #[test]
3154 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
3155 let _knobs = crate::speed::knob_read();
3156 let fctx = &crate::decode::FrameCtx::for_encoder();
3157 if !have_ffmpeg() {
3158 eprintln!(
3159 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
3160 );
3161 return;
3162 }
3163 let (width, height) = (128usize, 64usize);
3164 let pictures: Vec<Picture> = (0..5)
3165 .map(|i| panned_test_card(width, height, i * 3))
3166 .collect();
3167 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3168 assert_eq!(encoded.frames.len(), 5);
3169
3170 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
3171 assert_eq!(
3172 encoded.frames.len(),
3173 decoded.len(),
3174 "frame count: ours vs ffmpeg"
3175 );
3176 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3177 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
3178 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
3179 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
3180 }
3181
3182 eprintln!("frame bytes luma PSNR (dB) inter share");
3183 for (i, frame) in encoded.frames.iter().enumerate() {
3184 eprintln!(
3185 "{i:5} {:5} {:14.2} {:11.2}",
3186 frame.stream.len(),
3187 psnr(&frame.reconstruction.y, &pictures[i].y),
3188 frame.inter_block_share
3189 );
3190 }
3191 }
3192
3193 // The same sequence through OUR OWN decoder, sample-exact against the
3194 // encoder's reconstruction. ffmpeg stays the bitstream oracle
3195 // ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
3196 // divergence point at all, while our decoder can be traced symbol by
3197 // symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
3198 // the instrument the inter `TxMode::Select` hunt lacked; on failure it
3199 // names the first differing frame, plane and position.
3200 // lane-sb128b: the writer used to price a `NEWMV` residual against
3201 // `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
3202 // write-time stack could not carry, while the drl symbols signalled the
3203 // clamped index -- so the decoder derived a DIFFERENT motion vector with
3204 // the entropy stream still in sync, and the drift only surfaced frames
3205 // later as a drl desync (on film B, as the encoder's own trial decode
3206 // refusing a reference slot).
3207 //
3208 // The clamp needs a stack that shrinks between search and write, which
3209 // is what a 128x128 superblock's visit order does; the counter is the
3210 // point (class `gate-blind-to-feature`): a green round trip on a clip
3211 // that never clamps proves nothing.
3212 //
3213 // `#[ignore]`: [`force_sb128`] moves a process-global.
3214 //
3215 // The drl-clamp cell this gate's counter used to gate is no longer gated
3216 // here: it is covered by
3217 // [`every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`],
3218 // which enumerates the pricer's offer set against the writer's rule (see
3219 // its doc). The clamp needs a stack that shrinks between search and
3220 // write, which is what a 128x128 superblock's visit order would do -- but
3221 // the pricer never offers an index this tree's `write_drl_idx` cannot
3222 // signal, so no clip can provoke it (lane-av1recipehunt: 153 attempts, 0;
3223 // widening the pricer to `0..5` fires the counter immediately, reverting
3224 // silences it). `drl_clamp_hits` is kept as the tripwire for that fix.
3225
3226 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
3227 /// and one motion vector where the four 64x64 roots below spend four of
3228 /// each (cen3's L1). The counter is the gate on the fixture (class
3229 /// `gate-blind-to-feature`): a green round trip on a clip that never
3230 /// codes a 128x128 block proves nothing. RED before the search existed
3231 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
3232 /// root by construction).
3233 ///
3234 /// Both readers: our own decoder sample-exact against the encoder's
3235 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
3236 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
3237 ///
3238 /// `#[ignore]`: [`force_sb128`] moves a process-global.
3239 ///
3240 /// Runs only inside `superblock_size_global_suite`.
3241 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
3242 let _knobs = crate::speed::knob_write();
3243 if !have_ffmpeg() {
3244 eprintln!("SKIP: no ffmpeg");
3245 return;
3246 }
3247 force_sb128(true);
3248 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
3249 std::fs::create_dir_all(&dir).unwrap();
3250 let clip = dir.join("smpte-1280x768.y4m");
3251 // A slow horizontal pan over a still pattern: whole 128x128 regions
3252 // share one motion vector, which is exactly what a 128 root can code
3253 // as one block and four 64 roots cannot.
3254 let ok = Command::new("ffmpeg")
3255 .args(["-v", "error", "-y", "-f", "lavfi"])
3256 .args(["-i", "smptebars=size=1600x768:rate=24"])
3257 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
3258 .args(["-pix_fmt", "yuv420p"])
3259 .arg(&clip)
3260 .status()
3261 .expect("ffmpeg failed to run")
3262 .success();
3263 assert!(ok, "ffmpeg could not write the synthetic clip");
3264 let (width, height) = (1280usize, 768usize);
3265 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
3266 let _ = take_b128_none_hits();
3267 let _ = crate::tile::take_sb128_none_hits();
3268 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
3269 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
3270 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
3271 assert!(
3272 coded > 0,
3273 "no 128x128 block was coded on this clip, so it cannot witness the root search",
3274 );
3275 assert_eq!(
3276 won, coded,
3277 "every 128x128 root the search took must be coded as one"
3278 );
3279 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3280 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3281 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3282 let recon = &frame.reconstruction;
3283 for (plane, got, want) in [
3284 ("luma", &dec.y, &recon.y),
3285 ("U", &dec.u, &recon.u),
3286 ("V", &dec.v, &recon.v),
3287 ] {
3288 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3289 assert_eq!(
3290 differ,
3291 0,
3292 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
3293 own reconstruction",
3294 got.len()
3295 );
3296 assert_eq!(
3297 got.len(),
3298 want.len(),
3299 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3300 got.len(),
3301 want.len()
3302 );
3303 }
3304 }
3305 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3306 assert_eq!(
3307 encoded.frames.len(),
3308 ff.len(),
3309 "frame count: ours vs ffmpeg"
3310 );
3311 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3312 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3313 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3314 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3315 }
3316 }
3317
3318 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
3319 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
3320 /// same pan the skip-only witness above uses, with the arm FORCED
3321 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
3322 /// about once per frame, which witnesses the shape but not every context
3323 /// it reads, and forcing codes all 420 roots of the clip through it. RED
3324 /// before this lane by construction (`write_inter_block_128` refused
3325 /// every non-skip 128 block, so no such block existed to decode), and RED
3326 /// again on the first draft of the writer, whose neighbour band recorded
3327 /// `skip = true` for a block that carries a residual -- the next root's
3328 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
3329 ///
3330 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
3331 /// the skip arm's cost unconditionally (that is what makes the writer see
3332 /// the residual), and the cost model moved under it since lane-b128r --
3333 /// lane-rectdq made every non-skipped root pay its delta_q group and the
3334 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
3335 /// lost its partition at ALL 420 roots and the writer coded none. q=60
3336 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
3337 /// is the guard that catches the next such drift.
3338 ///
3339 /// Runs only inside `superblock_size_global_suite`.
3340 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
3341 let _knobs = crate::speed::knob_write();
3342 if !have_ffmpeg() {
3343 eprintln!("SKIP: no ffmpeg");
3344 return;
3345 }
3346 force_sb128(true);
3347 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
3348 std::fs::create_dir_all(&dir).unwrap();
3349 let clip = dir.join("smpte-pan-1280x768.y4m");
3350 let ok = Command::new("ffmpeg")
3351 .args(["-v", "error", "-y", "-f", "lavfi"])
3352 .args(["-i", "smptebars=size=1600x768:rate=24"])
3353 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
3354 .args(["-pix_fmt", "yuv420p"])
3355 .arg(&clip)
3356 .status()
3357 .expect("ffmpeg failed to run")
3358 .success();
3359 assert!(ok, "ffmpeg could not write the synthetic clip");
3360 let (width, height) = (1280usize, 768usize);
3361 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
3362 let _ = take_b128_residual_hits();
3363 let _ = crate::tile::take_sb128_residual_hits();
3364 force_b128_residual(true);
3365 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
3366 let (won, coded) = (
3367 take_b128_residual_hits(),
3368 crate::tile::take_sb128_residual_hits(),
3369 );
3370 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
3371 assert!(
3372 coded > 0,
3373 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
3374 );
3375 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3376 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3377 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3378 let recon = &frame.reconstruction;
3379 for (plane, got, want) in [
3380 ("luma", &dec.y, &recon.y),
3381 ("U", &dec.u, &recon.u),
3382 ("V", &dec.v, &recon.v),
3383 ] {
3384 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3385 assert_eq!(
3386 differ,
3387 0,
3388 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
3389 own reconstruction",
3390 got.len()
3391 );
3392 assert_eq!(
3393 got.len(),
3394 want.len(),
3395 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3396 got.len(),
3397 want.len()
3398 );
3399 }
3400 }
3401 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3402 assert_eq!(
3403 encoded.frames.len(),
3404 ff.len(),
3405 "frame count: ours vs ffmpeg"
3406 );
3407 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3408 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3409 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3410 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3411 }
3412 }
3413
3414 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
3415 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
3416 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
3417 /// copies it over every unit the block SPANS, so the four units of a 128
3418 /// root share one index -- while the encoder's CDEF search prices a
3419 /// preset per unit and its filter replay applied all four. Only the first
3420 /// reached the stream, so every decoder filtered the other three with the
3421 /// origin's strengths and the encoder's reconstruction (the picture the
3422 /// next frame predicts from) was a filter apart from what a decoder
3423 /// produces. RED before this lane on the native BD gate's bars 2160p row
3424 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
3425 /// the rows above the 128 superblock's own edge); the stream itself was
3426 /// always right -- ffmpeg and our own decoder agreed with each other and
3427 /// disagreed with the encoder.
3428 ///
3429 /// `take_cdef_covered_units` is the gate on the fixture (class
3430 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
3431 /// for the whole frame codes no literal at all and witnesses nothing.
3432 ///
3433 /// Runs only inside `superblock_size_global_suite`.
3434 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
3435 let _knobs = crate::speed::knob_write();
3436 if !have_ffmpeg() {
3437 eprintln!("SKIP: no ffmpeg");
3438 return;
3439 }
3440 force_sb128(true);
3441 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
3442 std::fs::create_dir_all(&dir).unwrap();
3443 let clip = dir.join("testsrc2-1280x768.y4m");
3444 // Detailed synthetic content: its CDEF search spends more than one
3445 // strength pair, which is what puts a `cdef_idx` literal in the tile.
3446 let ok = Command::new("ffmpeg")
3447 .args(["-v", "error", "-y", "-f", "lavfi"])
3448 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3449 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
3450 .arg(&clip)
3451 .status()
3452 .expect("ffmpeg failed to run")
3453 .success();
3454 assert!(ok, "ffmpeg could not write the synthetic clip");
3455 let (width, height) = (1280usize, 768usize);
3456 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
3457 force_b128_root(true);
3458 force_b128_residual(true);
3459 let _ = crate::tile::take_sb128_residual_hits();
3460 let _ = crate::filter_search::take_cdef_covered_units();
3461 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
3462 let coded = crate::tile::take_sb128_residual_hits();
3463 let covered = crate::filter_search::take_cdef_covered_units();
3464 eprintln!(
3465 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
3466 another unit's literal: {covered}"
3467 );
3468 assert!(
3469 coded > 0,
3470 "no 128x128 block carried a residual on this clip"
3471 );
3472 assert!(
3473 covered > 0,
3474 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
3475 cannot witness the rule",
3476 );
3477 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3478 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3479 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3480 for (plane, got, want) in [
3481 ("luma", &dec.y, &frame.reconstruction.y),
3482 ("U", &dec.u, &frame.reconstruction.u),
3483 ("V", &dec.v, &frame.reconstruction.v),
3484 ] {
3485 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3486 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
3487 assert_eq!(
3488 got.len(),
3489 want.len(),
3490 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3491 got.len(),
3492 want.len()
3493 );
3494 }
3495 }
3496 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3497 assert_eq!(
3498 encoded.frames.len(),
3499 ff.len(),
3500 "frame count: ours vs ffmpeg"
3501 );
3502 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3503 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3504 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3505 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3506 }
3507 }
3508
3509 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
3510 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
3511 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
3512 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
3513 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
3514 /// rect partition with [`force_b128_rect`]) so every inter root of the
3515 /// clip goes through it; the `coded > 0` assert is the guard that catches
3516 /// the next fixture drift (the whole-128 twin of this witness went RED
3517 /// twice that way).
3518 ///
3519 /// Runs only inside `superblock_size_global_suite`.
3520 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
3521 let _knobs = crate::speed::knob_write();
3522 if !have_ffmpeg() {
3523 eprintln!("SKIP: no ffmpeg");
3524 return;
3525 }
3526 force_sb128(true);
3527 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
3528 std::fs::create_dir_all(&dir).unwrap();
3529 let clip = dir.join("smpte-pan-1280x768.y4m");
3530 let ok = Command::new("ffmpeg")
3531 .args(["-v", "error", "-y", "-f", "lavfi"])
3532 .args(["-i", "smptebars=size=1600x768:rate=24"])
3533 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
3534 .args(["-pix_fmt", "yuv420p"])
3535 .arg(&clip)
3536 .status()
3537 .expect("ffmpeg failed to run")
3538 .success();
3539 assert!(ok, "ffmpeg could not write the synthetic clip");
3540 let (width, height) = (1280usize, 768usize);
3541 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
3542 force_b128_rect(1);
3543 force_b128_rectres(true);
3544 let _ = take_b128_rectres_hits();
3545 let _ = crate::tile::take_sb128_rectres_hits();
3546 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
3547 let (won, coded) = (
3548 take_b128_rectres_hits(),
3549 crate::tile::take_sb128_rectres_hits(),
3550 );
3551 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
3552 assert!(
3553 coded > 0,
3554 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
3555 );
3556 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3557 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3558 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3559 let recon = &frame.reconstruction;
3560 for (plane, got, want) in [
3561 ("luma", &dec.y, &recon.y),
3562 ("U", &dec.u, &recon.u),
3563 ("V", &dec.v, &recon.v),
3564 ] {
3565 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3566 assert_eq!(
3567 differ,
3568 0,
3569 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
3570 own reconstruction",
3571 got.len()
3572 );
3573 assert_eq!(
3574 got.len(),
3575 want.len(),
3576 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3577 got.len(),
3578 want.len()
3579 );
3580 }
3581 }
3582 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3583 assert_eq!(
3584 encoded.frames.len(),
3585 ff.len(),
3586 "frame count: ours vs ffmpeg"
3587 );
3588 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3589 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3590 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3591 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3592 }
3593 }
3594
3595 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
3596 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
3597 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
3598 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
3599 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
3600 /// reference picture the GOP has not produced yet, which refuses before
3601 /// any AB root is coded.
3602 ///
3603 /// Runs only inside `superblock_size_global_suite`.
3604 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
3605 let _knobs = crate::speed::knob_write();
3606 if !have_ffmpeg() {
3607 eprintln!("SKIP: no ffmpeg");
3608 return;
3609 }
3610 force_sb128(true);
3611 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
3612 std::fs::create_dir_all(&dir).unwrap();
3613 let clip = dir.join("testsrc2-1280x768.y4m");
3614 let ok = Command::new("ffmpeg")
3615 .args(["-v", "error", "-y", "-f", "lavfi"])
3616 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3617 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
3618 .arg(&clip)
3619 .status()
3620 .expect("ffmpeg failed to run")
3621 .success();
3622 assert!(ok, "ffmpeg could not write the synthetic clip");
3623 let (width, height) = (1280usize, 768usize);
3624 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
3625 force_b128_ab(4);
3626 force_b128_rectres(true);
3627 let _ = take_b128_rectres_hits();
3628 let _ = crate::tile::take_sb128_rectres_hits();
3629 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
3630 let (won, coded) = (
3631 take_b128_rectres_hits(),
3632 crate::tile::take_sb128_rectres_hits(),
3633 );
3634 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
3635 assert!(
3636 coded > 0,
3637 "no AB piece carried a residual on this clip, so it cannot witness the arm",
3638 );
3639 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3640 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3641 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3642 let recon = &frame.reconstruction;
3643 for (plane, got, want) in [
3644 ("luma", &dec.y, &recon.y),
3645 ("U", &dec.u, &recon.u),
3646 ("V", &dec.v, &recon.v),
3647 ] {
3648 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3649 assert_eq!(
3650 differ,
3651 0,
3652 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
3653 own reconstruction",
3654 got.len()
3655 );
3656 assert_eq!(
3657 got.len(),
3658 want.len(),
3659 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3660 got.len(),
3661 want.len()
3662 );
3663 }
3664 }
3665 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3666 assert_eq!(
3667 encoded.frames.len(),
3668 ff.len(),
3669 "frame count: ours vs ffmpeg"
3670 );
3671 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3672 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3673 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3674 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3675 }
3676 }
3677
3678 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
3679 /// half WITH a residual under a clip whose CDEF search codes a
3680 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
3681 /// and the decoder stamps BOTH units it spans with it, so the owner map
3682 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
3683 /// collapse the pair -- exactly the bug class that broke bars 2160p at
3684 /// the whole-128 root. RED before this lane by construction: no rect
3685 /// piece could carry a residual, so no such literal existed.
3686 ///
3687 /// Runs only inside `superblock_size_global_suite`.
3688 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
3689 let _knobs = crate::speed::knob_write();
3690 if !have_ffmpeg() {
3691 eprintln!("SKIP: no ffmpeg");
3692 return;
3693 }
3694 force_sb128(true);
3695 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
3696 std::fs::create_dir_all(&dir).unwrap();
3697 let clip = dir.join("testsrc2-1280x768.y4m");
3698 // Detailed synthetic content: its CDEF search spends more than one
3699 // strength pair, which is what puts a `cdef_idx` literal in the tile.
3700 let ok = Command::new("ffmpeg")
3701 .args(["-v", "error", "-y", "-f", "lavfi"])
3702 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3703 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
3704 .arg(&clip)
3705 .status()
3706 .expect("ffmpeg failed to run")
3707 .success();
3708 assert!(ok, "ffmpeg could not write the synthetic clip");
3709 let (width, height) = (1280usize, 768usize);
3710 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
3711 force_b128_rect(1);
3712 force_b128_rectres(true);
3713 let _ = crate::tile::take_sb128_rectres_hits();
3714 let _ = crate::filter_search::take_cdef_covered_units();
3715 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
3716 let coded = crate::tile::take_sb128_rectres_hits();
3717 let covered = crate::filter_search::take_cdef_covered_units();
3718 eprintln!(
3719 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
3720 another unit's literal: {covered}"
3721 );
3722 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
3723 assert!(
3724 covered > 0,
3725 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
3726 cannot witness the rule",
3727 );
3728 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3729 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3730 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3731 for (plane, got, want) in [
3732 ("luma", &dec.y, &frame.reconstruction.y),
3733 ("U", &dec.u, &frame.reconstruction.u),
3734 ("V", &dec.v, &frame.reconstruction.v),
3735 ] {
3736 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3737 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
3738 assert_eq!(
3739 got.len(),
3740 want.len(),
3741 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3742 got.len(),
3743 want.len()
3744 );
3745 }
3746 }
3747 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3748 assert_eq!(
3749 encoded.frames.len(),
3750 ff.len(),
3751 "frame count: ours vs ffmpeg"
3752 );
3753 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3754 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3755 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3756 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3757 }
3758 }
3759
3760 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
3761 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
3762 /// `write_compound_block` chain every smaller compound block takes, at a
3763 /// window it had never been exercised at. RED before this lane: the
3764 /// search passed an empty compound list at the 128 root, so the count was
3765 /// 0 and no such block existed to decode.
3766 ///
3767 /// Runs only inside `superblock_size_global_suite`.
3768 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
3769 let _knobs = crate::speed::knob_write();
3770 if !have_ffmpeg() {
3771 eprintln!("SKIP: no ffmpeg");
3772 return;
3773 }
3774 force_sb128(true);
3775 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
3776 std::fs::create_dir_all(&dir).unwrap();
3777 let clip = dir.join("testsrc2-1280x768.y4m");
3778 // Moving objects that occlude each other: a pan is coded by one
3779 // reference outright, and a compound pair only pays where the two
3780 // references disagree.
3781 let ok = Command::new("ffmpeg")
3782 .args(["-v", "error", "-y", "-f", "lavfi"])
3783 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3784 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
3785 .arg(&clip)
3786 .status()
3787 .expect("ffmpeg failed to run")
3788 .success();
3789 assert!(ok, "ffmpeg could not write the synthetic clip");
3790 let (width, height) = (1280usize, 768usize);
3791 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
3792 // The compound candidate wins the 128 block's own search on this pan
3793 // but the root then loses to its four cells, so the root is forced
3794 // (the residual arm is left at its default, off).
3795 force_b128_root(true);
3796 let _ = take_b128_compound_hits();
3797 let _ = crate::tile::take_sb128_compound_hits();
3798 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
3799 let (won, coded) = (
3800 take_b128_compound_hits(),
3801 crate::tile::take_sb128_compound_hits(),
3802 );
3803 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
3804 assert!(
3805 coded > 0,
3806 "no compound 128x128 block was coded on this clip"
3807 );
3808 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3809 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
3810 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3811 for (plane, got, want) in [
3812 ("luma", &dec.y, &frame.reconstruction.y),
3813 ("U", &dec.u, &frame.reconstruction.u),
3814 ("V", &dec.v, &frame.reconstruction.v),
3815 ] {
3816 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3817 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
3818 assert_eq!(
3819 got.len(),
3820 want.len(),
3821 "frame {i}: {plane} is {} samples, the reconstruction's is {}",
3822 got.len(),
3823 want.len()
3824 );
3825 }
3826 }
3827 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3828 assert_eq!(
3829 encoded.frames.len(),
3830 ff.len(),
3831 "frame count: ours vs ffmpeg"
3832 );
3833 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3834 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
3835 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
3836 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
3837 }
3838 }
3839
3840 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
3841 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
3842 /// square. Three passes over one `testsrc2` clip:
3843 ///
3844 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
3845 /// the 128x64 shape reads is exercised rather than the handful the RD
3846 /// would pick;
3847 /// * VERT forced the same way;
3848 /// * UNFORCED, which is the count the gate rows are read against -- the
3849 /// same clip with the RD free to choose among NONE / HORZ / VERT /
3850 /// four superblocks.
3851 ///
3852 /// Each pass is sample-exact against the encoder's own reconstruction
3853 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
3854 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
3855 /// before this lane by construction: `write_sb128_root` could only name
3856 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
3857 ///
3858 /// Runs only inside `superblock_size_global_suite`.
3859 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
3860 let _knobs = crate::speed::knob_write();
3861 if !have_ffmpeg() {
3862 eprintln!("SKIP: no ffmpeg");
3863 return;
3864 }
3865 force_sb128(true);
3866 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
3867 std::fs::create_dir_all(&dir).unwrap();
3868 let clip = dir.join("testsrc2-1280x768.y4m");
3869 let ok = Command::new("ffmpeg")
3870 .args(["-v", "error", "-y", "-f", "lavfi"])
3871 .args(["-i", "testsrc2=size=1280x768:rate=24"])
3872 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
3873 .arg(&clip)
3874 .status()
3875 .expect("ffmpeg failed to run")
3876 .success();
3877 assert!(ok, "ffmpeg could not write the synthetic clip");
3878 let (width, height) = (1280usize, 768usize);
3879 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
3880 let mut unforced = (0usize, 0usize);
3881 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
3882 force_b128_rect(force);
3883 let _ = take_b128_horz_hits();
3884 let _ = take_b128_vert_hits();
3885 let _ = crate::tile::take_sb128_horz_hits();
3886 let _ = crate::tile::take_sb128_vert_hits();
3887 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
3888 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
3889 let (coded_h, coded_v) = (
3890 crate::tile::take_sb128_horz_hits(),
3891 crate::tile::take_sb128_vert_hits(),
3892 );
3893 eprintln!(
3894 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
3895 {coded_h} 128x64 + {coded_v} 64x128 halves"
3896 );
3897 match force {
3898 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
3899 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
3900 // The unforced count is REPORTED, not asserted: it is the
3901 // number the gate is read against, and a zero here would be
3902 // an RD result, not a defect (the forced passes already prove
3903 // the writer and the reader agree on the shape).
3904 _ => unforced = (won_h, won_v),
3905 }
3906 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3907 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
3908 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
3909 for (plane, got, want) in [
3910 ("luma", &dec.y, &frame.reconstruction.y),
3911 ("U", &dec.u, &frame.reconstruction.u),
3912 ("V", &dec.v, &frame.reconstruction.v),
3913 ] {
3914 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
3915 assert_eq!(
3916 differ, 0,
3917 "{label} frame {i}: {plane} -- {differ} samples differ"
3918 );
3919 assert_eq!(
3920 got.len(),
3921 want.len(),
3922 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
3923 got.len(),
3924 want.len()
3925 );
3926 }
3927 }
3928 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3929 assert_eq!(
3930 encoded.frames.len(),
3931 ff.len(),
3932 "{label}: frame count: ours vs ffmpeg"
3933 );
3934 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
3935 assert_eq!(
3936 dec.y, frame.reconstruction.y,
3937 "{label} frame {i}: ffmpeg luma"
3938 );
3939 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
3940 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
3941 }
3942 }
3943 force_b128_rect(0);
3944 eprintln!(
3945 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
3946 unforced.0, unforced.1
3947 );
3948 }
3949
3950/// Restores the process-global 128-superblock state the folded cases move:
3951/// the sb128 mode back to its prior value, and every `force_b128_*` arm back
3952/// to off, so one case cannot leak into the next.
3953fn restore_superblock_globals(prior_sb128: u8) {
3954 super::split::ENC_SB128.store(prior_sb128, std::sync::atomic::Ordering::Relaxed);
3955 force_b128_residual(false);
3956 force_b128_root(false);
3957 force_b128_rectres(false);
3958 force_b128_rect(0);
3959 force_b128_ab(0);
3960}
3961
3962/// The ten cases that set the process-global superblock size, folded into
3963/// one ignored test so they never share a process with another such test.
3964/// Each case runs under `catch_unwind`; every failing name is reported.
3965///
3966/// cargo test -p ec-av1 --release --lib -- --ignored \
3967/// superblock_size_global_suite --nocapture
3968#[test]
3969#[ignore = "sets the process-global superblock size: run it alone"]
3970fn superblock_size_global_suite() {
3971 let prior = super::split::ENC_SB128.load(std::sync::atomic::Ordering::Relaxed);
3972 let cases: [(&str, fn()); 10] = [
3973 (
3974 "a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact",
3975 a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact,
3976 ),
3977 (
3978 "a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders",
3979 a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders,
3980 ),
3981 (
3982 "a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact",
3983 a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact,
3984 ),
3985 (
3986 "a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders",
3987 a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders,
3988 ),
3989 (
3990 "an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders",
3991 an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders,
3992 ),
3993 (
3994 "a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact",
3995 a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact,
3996 ),
3997 (
3998 "a_128_root_compound_block_decodes_exact_through_both_decoders",
3999 a_128_root_compound_block_decodes_exact_through_both_decoders,
4000 ),
4001 (
4002 "a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders",
4003 a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders,
4004 ),
4005 (
4006 "a_128_root_ab_shapes_decode_exact_through_both_decoders",
4007 super::more_tests::a_128_root_ab_shapes_decode_exact_through_both_decoders,
4008 ),
4009 (
4010 "a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact",
4011 crate::encoder::tests::a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact,
4012 ),
4013 ];
4014 let mut failures = Vec::new();
4015 for (name, case) in cases {
4016 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(case)).is_err() {
4017 failures.push(name);
4018 }
4019 restore_superblock_globals(prior);
4020 }
4021 assert!(failures.is_empty(), "failed cases: {failures:?}");
4022}