forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

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