forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

more_tests.rs3929 lines, 186.6 KiBHistoryRawDownload
1use super::*;
2use super::tests::*;
3use crate::intra::{D45_PRED, NON_DIRECTIONAL};
4use std::process::Command;
5
6
7 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
8 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
9 /// Five passes over the same `testsrc2` clip
10 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
11 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
12 /// context and every visit order the shape reads is exercised rather than
13 /// the handful the RD would pick, and then an UNFORCED pass whose
14 /// per-shape count is REPORTED (it is the number the gate rows are read
15 /// against).
16 ///
17 /// Each pass is sample-exact against the encoder's own reconstruction
18 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
19 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
20 /// before this lane by construction: `write_sb128_root` could only name
21 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
22 ///
23 /// Runs only inside `superblock_size_global_suite`.
24 pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
25 let _knobs = crate::speed::knob_write();
26 if !have_ffmpeg() {
27 eprintln!("SKIP: no ffmpeg");
28 return;
29 }
30 force_sb128(true);
31 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
32 std::fs::create_dir_all(&dir).unwrap();
33 let clip = dir.join("testsrc2-1280x768.y4m");
34 let ok = Command::new("ffmpeg")
35 .args(["-v", "error", "-y", "-f", "lavfi"])
36 .args(["-i", "testsrc2=size=1280x768:rate=24"])
37 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
38 .arg(&clip)
39 .status()
40 .expect("ffmpeg failed to run")
41 .success();
42 assert!(ok, "ffmpeg could not write the synthetic clip");
43 let (width, height) = (1280usize, 768usize);
44 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
45 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
46 let mut unforced = [0usize; 4];
47 for force in [4u8, 5, 6, 7, 0] {
48 force_b128_ab(force);
49 let label = if force == 0 {
50 "unforced"
51 } else {
52 names[usize::from(force) - 4]
53 };
54 let _ = take_b128_ab_hits();
55 let _ = crate::tile::take_sb128_ab_hits();
56 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
57 let won = take_b128_ab_hits();
58 let coded = crate::tile::take_sb128_ab_hits();
59 eprintln!(
60 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
61 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
62 );
63 if force == 0 {
64 // The unforced counts are REPORTED, not asserted: a zero here
65 // would be an RD result, not a defect (the four forced passes
66 // already prove the writer and the reader agree on the shape).
67 unforced = won;
68 } else {
69 let i = usize::from(force) - 4;
70 assert!(
71 coded[i] > 0,
72 "no {label} root was coded with {label} forced"
73 );
74 }
75 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
76 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
77 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
78 for (plane, got, want) in [
79 ("luma", &dec.y, &frame.reconstruction.y),
80 ("U", &dec.u, &frame.reconstruction.u),
81 ("V", &dec.v, &frame.reconstruction.v),
82 ] {
83 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
84 assert_eq!(
85 differ, 0,
86 "{label} frame {i}: {plane} -- {differ} samples differ"
87 );
88 assert_eq!(
89 got.len(),
90 want.len(),
91 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
92 got.len(),
93 want.len()
94 );
95 }
96 }
97 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
98 assert_eq!(
99 encoded.frames.len(),
100 ff.len(),
101 "{label}: frame count: ours vs ffmpeg"
102 );
103 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
104 assert_eq!(
105 dec.y, frame.reconstruction.y,
106 "{label} frame {i}: ffmpeg luma"
107 );
108 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
109 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
110 }
111 }
112 force_b128_ab(0);
113 eprintln!(
114 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
115 unforced[0], unforced[1], unforced[2], unforced[3],
116 );
117 }
118
119 #[test]
120 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
121 let _knobs = crate::speed::knob_read();
122 let fctx = &crate::decode::FrameCtx::for_encoder();
123 // 256x128, not the 128x64 this started at: once a leaf could search
124 // its second reference (lane-av1comp4) the small card's every
125 // eligible block went to a compound winner, which commits its flat
126 // transform, and the split below stopped firing on content that
127 // still splits at every larger size ([[gate-blind-to-feature]] --
128 // the guard is right, the fixture had shrunk under it).
129 let (width, height) = (256usize, 128usize);
130 let pictures: Vec<Picture> = (0..5)
131 .map(|i| panned_test_card(width, height, i * 3))
132 .collect();
133 let _ = take_inter_tx_split_hits();
134 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
135 let raw = take_inter_tx_split_hits();
136 // Summed over the four block classes the census keys on (leaf/32x32 x
137 // single/compound): this assert is about the split firing at all.
138 let split = [
139 raw.iter().step_by(2).sum::<usize>(),
140 raw.iter().skip(1).step_by(2).sum::<usize>(),
141 ];
142 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
143 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
144 // content splits -- a green round trip in which the split never fires
145 // would prove only the flat path.
146 if tx_select() && tx_select_inter() {
147 assert!(split[1] > 0, "the inter var-tx split never fired");
148 }
149 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
150 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
151 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
152 let recon = &frame.reconstruction;
153 for (plane, got, want, stride) in [
154 ("luma", &dec.y, &recon.y, width),
155 ("U", &dec.u, &recon.u, width / 2),
156 ("V", &dec.v, &recon.v, width / 2),
157 ] {
158 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
159 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
160 panic!(
161 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
162 reconstruction {} ({} of {} samples differ)",
163 at % stride,
164 at / stride,
165 got[at],
166 want[at],
167 got.iter().zip(want).filter(|(a, b)| a != b).count(),
168 got.len(),
169 );
170 }
171 }
172 }
173 }
174
175 /// The rate term the mode search ranks every decision by has to be the
176 /// rate the writer then spends. The search prices a block's coefficients
177 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
178 /// against the default CDFs a tile starts from and the contexts of a
179 /// block whose neighbours coded nothing -- while the tile writer codes
180 /// them against a state that has been adapting all frame (the
181 /// price-the-narrowing class). This measures that drift: the sum of what
182 /// the search paid for the coefficients it kept, against the bytes the
183 /// writer actually emitted for the whole tile (which also carries the
184 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
185 /// expected to be the larger of the two).
186 #[test]
187 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
188 let _knobs = crate::speed::knob_read();
189 let fctx = &crate::decode::FrameCtx::for_encoder();
190 let (width, height) = (256usize, 128usize);
191 let pictures: Vec<Picture> = (0..5)
192 .map(|i| panned_test_card(width, height, i * 2))
193 .collect();
194 let _ = take_predicted_bits();
195 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
196 let predicted = take_predicted_bits();
197 assert_eq!(predicted.len(), encoded.frames.len());
198
199 eprintln!("frame predicted bits written bits drift");
200 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
201 // defect this gate exists to catch), a positive one is the written
202 // side carrying syntax the coefficient sum leaves out -- and since
203 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
204 // on that side, so the two directions no longer share a bound.
205 let mut worst_over: f64 = 0.0;
206 let mut worst_under: f64 = 0.0;
207 // The census is per CODED frame, so it is zipped in coding order --
208 // which is not display order under a pyramid.
209 let coded: Vec<&Encoded> = encoded
210 .coding_order
211 .iter()
212 .map(|&i| &encoded.frames[i])
213 .collect();
214 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
215 let written = frame.tile.len() as f64 * 8.0;
216 let drift = (written - bits) / written;
217 worst_over = worst_over.max(-drift);
218 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
219 // all (150-250 bits of tile, nearly all of it partition/mode/mv
220 // syntax the coefficient sum never counts), so its ratio measures
221 // that floor rather than any drift. Frames under 512 written bits
222 // are left out of the under-price bound for that reason; the
223 // over-price bound -- the defect direction, where the search pays
224 // MORE than the writer -- still covers every frame.
225 if written >= 512.0 {
226 worst_under = worst_under.max(drift);
227 }
228 eprintln!(
229 "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
230 drift * 100.0
231 );
232 }
233 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
234 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
235 // over-prices every frame but the last (its sum EXCLUDES the
236 // partition/mode/skip/mv syntax the written side carries, so the true
237 // coefficient over-price is larger still): the writer's CDFs adapt to
238 // the content while the search's stay at the defaults. The bound is
239 // set just above the worst measured point -- a widening drift is the
240 // thing this gate exists to catch.
241 assert!(
242 worst_over <= 0.16,
243 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
244 worst_over * 100.0
245 );
246 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
247 // the worst inter frame, where nearly every block now codes an MV
248 // residual and a reference the coefficient sum never counts. Re-measured
249 // at +29.6% once the encoder's grid published compound blocks properly
250 // (compound share 8.8% -> 11.5%): a compound block carries a second
251 // reference tree, a compound mode symbol and -- for the half-new modes
252 // -- an MV residual, none of which the coefficient sum counts.
253 // lane-av1txbits: pricing against the tables the frame's writer really
254 // starts from collapses the over-price above to nothing, so the whole
255 // remaining gap is the syntax the coefficient sum leaves out. That is
256 // the default on a non-screen frame since lane-av1price2 (this
257 // fixture is one), and it reads +32.6% here.
258 // lane-av1obmc: every eligible single-reference inter block now also
259 // carries a `motion_mode` symbol the coefficient sum never counts,
260 // and an OBMC block carries the more expensive of the two values --
261 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
262 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
263 // decisions, so this bound and the byte pins above FAIL BY DESIGN
264 // under it; the default path (no motion_mode syntax at all) is the
265 // one they are measured on.
266 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
267 // coding pyramid now, so the five frames are a key frame, a hidden
268 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
269 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
270 // near-empty leaves below it. Both bounds stand where they were.
271 // lane-av1rejudge: local warp is ON by default now, so every eligible
272 // single-reference block carries that same `motion_mode` symbol (a
273 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
274 // +34.9% here, one point past the OBMC reading above. The bound moves
275 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
276 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
277 // symbol and one or two magnitude symbols, none of which the
278 // coefficient sum counts either -- +36.9% here against the same
279 // fixture's +34.9% with `EC_AV1_CFL=0`.
280 // ... and a directional block whose `angle_delta_y` is no longer
281 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
282 assert!(
283 worst_under <= 0.40,
284 "the writer spent {:.2}% more than the search priced -- more than \
285 the mode/mv syntax outside the coefficient sum explains",
286 worst_under * 100.0
287 );
288 }
289
290 /// The census behind step (1) of the pricer lane: for every transform
291 /// block the writer really codes, what the search priced those levels at
292 /// against what the writer spent on them, split by table set and non-zero
293 /// count. One average hides the interesting part -- the classes the
294 /// estimate is systematically wrong about (all-zero blocks, the
295 /// one-coefficient blocks the inter search lives on) -- so the split is
296 /// printed and only the total is asserted on.
297 #[test]
298 fn pricer_error_census_by_block_class() {
299 let _knobs = crate::speed::knob_read();
300 let fctx = &crate::decode::FrameCtx::for_encoder();
301 let (width, height) = (256usize, 128usize);
302 let pictures: Vec<Picture> = (0..5)
303 .map(|i| panned_test_card(width, height, i * 2))
304 .collect();
305 crate::tile::pricer_census_on();
306 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
307 let rows = crate::tile::take_pricer_census();
308 assert!(!rows.is_empty(), "the census saw no transform block");
309
310 println!("| set | nz | blocks | priced bits | written bits | error |");
311 println!("|---|---|---|---|---|---|");
312 let (mut priced_all, mut written_all) = (0.0, 0.0);
313 for ((set, bucket), (blocks, priced, written)) in &rows {
314 priced_all += priced;
315 written_all += written;
316 println!(
317 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
318 crate::tile::census_bucket_label(*bucket),
319 if *written > 0.0 {
320 (priced - written) / written * 100.0
321 } else {
322 0.0
323 }
324 );
325 }
326 println!(
327 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
328 rows.values().map(|r| r.0).sum::<u64>(),
329 (priced_all - written_all) / written_all * 100.0
330 );
331 assert!(written_all > 0.0);
332 }
333
334 /// Step (2) of the pricer lane: the same census, but on the REAL clips
335 /// the BD gate scores -- one film clip and the screen capture -- so the
336 /// question the film/screen split raises can be answered from data. Real
337 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
338 /// the screen capture larger, and the census says why: on a screen
339 /// capture the frame's own starting tables are the tables of a frame that
340 /// coded PALETTE and long runs of zero blocks, so they are far from the
341 /// tables the writer ends the frame with; the pricer error does not fall
342 /// the way it does on film.
343 ///
344 /// Not a gate -- it prints. Run it once per mode:
345 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
346 /// --ignored pricer_error_census_on_clips --nocapture
347 #[test]
348 #[ignore = "reads the real library, needs ffmpeg"]
349 fn pricer_error_census_on_clips() {
350 let _knobs = crate::speed::knob_write();
351 if !have_ffmpeg() {
352 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
353 return;
354 }
355 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first),
356 // so this probe reads the same tree the preflight validates. Its
357 // `assert!(!clips.is_empty())` below was already a hard failure, so no
358 // skip shape changes here — only the root does.
359 let fixtures = crate::library_fixture::root();
360 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
361 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
362 if film.exists() {
363 clips.push(("film 1080p".to_string(), film));
364 }
365 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
366 && let Some(p) = manifest
367 .lines()
368 .skip(1)
369 .filter_map(|l| l.split('\t').next())
370 .find(|p| {
371 p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()
372 })
373 {
374 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
375 }
376 assert!(!clips.is_empty(), "no source clip available");
377 let (width, height, frames) = (640usize, 384usize, 6usize);
378 for (name, path) in &clips {
379 let fctx = &crate::decode::FrameCtx::for_encoder();
380 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
381 SCREEN_FRAMES.iter().for_each(|c| {
382 c.store(0, std::sync::atomic::Ordering::Relaxed);
383 });
384 let _ = crate::tile::take_pricing_hits();
385 crate::tile::pricer_census_on();
386 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
387 let rows = crate::tile::take_pricer_census();
388 let (price_default, price_real) = crate::tile::take_pricing_hits();
389 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
390 println!(
391 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
392 {screen_on}, pricer armings default={price_default} real={price_real}"
393 );
394 println!("| set | nz | blocks | priced bits | written bits | error |");
395 println!("|---|---|---|---|---|---|");
396 let (mut priced_all, mut written_all) = (0.0, 0.0);
397 for ((set, bucket), (blocks, priced, written)) in &rows {
398 priced_all += priced;
399 written_all += written;
400 println!(
401 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
402 crate::tile::census_bucket_label(*bucket),
403 if *written > 0.0 {
404 (priced - written) / written * 100.0
405 } else {
406 0.0
407 }
408 );
409 }
410 println!(
411 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
412 rows.values().map(|r| r.0).sum::<u64>(),
413 (priced_all - written_all) / written_all * 100.0
414 );
415 assert!(
416 written_all > 0.0,
417 "{name}: the census saw no transform block"
418 );
419 }
420 }
421
422 /// Low motion has to actually buy something: at least one inter frame of
423 /// a panning sequence has to cost fewer bytes than the key frame that
424 /// starts it, and the inter-block share it prints has to be non-zero --
425 /// a search that never picks an inter mode would still pass a rate gate
426 /// on a picture with no motion in it (the class this repo calls
427 /// gate-blind-to-feature), so the share is printed even though it is not
428 /// asserted on beyond being reachable at all.
429 #[test]
430 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
431 let _knobs = crate::speed::knob_read();
432 let fctx = &crate::decode::FrameCtx::for_encoder();
433 let (width, height) = (256usize, 128usize);
434 let pictures: Vec<Picture> = (0..5)
435 .map(|i| panned_test_card(width, height, i * 2))
436 .collect();
437 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
438
439 let key_bytes = encoded.frames[0].stream.len();
440 eprintln!("frame bytes inter share");
441 for (i, frame) in encoded.frames.iter().enumerate() {
442 eprintln!(
443 "{i:5} {:5} {:11.2}",
444 frame.stream.len(),
445 frame.inter_block_share
446 );
447 }
448 assert!(
449 encoded.frames[1..]
450 .iter()
451 .any(|f| f.stream.len() < key_bytes),
452 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
453 );
454 assert!(
455 encoded.frames[1..]
456 .iter()
457 .any(|f| f.inter_block_share > 0.0),
458 "no inter frame coded a single inter block -- the search never fired"
459 );
460 }
461
462 /// A manual perf probe, not a gate: prints where a key frame's and an
463 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
464 /// measures before it optimizes rather than guessing. Run with
465 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
466 #[test]
467 #[ignore = "a perf probe, not a gate"]
468 fn stage_timing_breakdown() {
469 let _knobs = crate::speed::knob_read();
470 let fctx = &crate::decode::FrameCtx::for_encoder();
471 use std::time::Instant;
472
473 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
474 let picture = test_card(width, height);
475
476 let t = Instant::now();
477 let dc_only =
478 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
479 let dc_only_t = t.elapsed();
480
481 let t = Instant::now();
482 let non_directional =
483 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx)
484 .unwrap();
485 let non_directional_t = t.elapsed();
486
487 let t = Instant::now();
488 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
489 let all_modes_t = t.elapsed();
490
491 eprintln!(
492 "\n=== key frame {width}x{height} ===\n\
493 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
494 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
495 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
496 dc_only.stream.len(),
497 non_directional.stream.len(),
498 all_modes.stream.len(),
499 );
500
501 // One inter frame predicting off the key frame's own
502 // reconstruction, the (256, 256)-padded surface encode_sequence
503 // itself would hand encode_inter_frame.
504 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
505 let padded_pic = picture.padded_to(SUPERBLOCK);
506 let t = Instant::now();
507 let inter = encode_inter_frame(
508 &padded_pic,
509 &padded_ref,
510 100,
511 0.5,
512 1,
513 flat_order_hints(1, 0, false),
514 (width, height),
515 None,
516 None,
517 None,
518 None,
519 fctx,
520 None,
521 &[],
522 )
523 .unwrap();
524 let inter_t = t.elapsed();
525 eprintln!(
526 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
527 {:.2})",
528 inter.stream.len(),
529 inter.inter_block_share
530 );
531 }
532
533 // Isolated per-call cost of the trial pipeline's own stages, at both
534 // transform sizes the search runs, averaged over enough calls to
535 // rise above `Instant::now`'s own noise.
536 for side in [16usize, 32] {
537 const N: u32 = 20_000;
538 let residual: Vec<i32> = (0..side * side)
539 .map(|i| ((i * 37 % 61) as i32) - 30)
540 .collect();
541
542 let t = Instant::now();
543 let mut levels = Vec::new();
544 for _ in 0..N {
545 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
546 }
547 let forward_t = t.elapsed() / N;
548
549 let t = Instant::now();
550 for _ in 0..N {
551 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
552 }
553 let inverse_t = t.elapsed() / N;
554
555 let set = if side == 32 {
556 crate::cdf_state::TxbSet::Luma32
557 } else {
558 crate::cdf_state::TxbSet::Luma16
559 };
560 let t = Instant::now();
561 for _ in 0..N {
562 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
563 }
564 let entropy_t = t.elapsed() / N;
565
566 let above = vec![128u8; side * 2];
567 let left = vec![128u8; side * 2];
568 let mut prediction = vec![0u8; side * side];
569 let t = Instant::now();
570 for _ in 0..N {
571 intra_predict_u8(
572 D45_PRED,
573 0,
574 Some(&above),
575 Some(&left),
576 Some(128),
577 side,
578 side,
579 false,
580 false,
581 &mut prediction,
582 fctx,
583 );
584 }
585 let predict_t = t.elapsed() / N;
586
587 eprintln!(
588 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
589 predict (1 directional mode): {predict_t:>9.2?}\n\
590 forward_and_quantize: {forward_t:>9.2?}\n\
591 dequant_and_inverse: {inverse_t:>9.2?}\n\
592 coeff_bits: {entropy_t:>9.2?}"
593 );
594 }
595 }
596
597 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
598 /// plus what is left over once buckets 0/2/3 are subtracted.
599 ///
600 /// lane-av1probes: the two search-shaped buckets OVERLAP and the old
601 /// print denied it. Bucket 0 is not "the motion search": `stage_since(0,
602 /// ..)` fires only after `find_best_new_mv` and the global-MV search
603 /// (`encode.rs:11959`, `:12080`), so it is the NEWMV/GLOBAL sub-search
604 /// alone. Bucket 1 is EVERY `crate::mc::predict` call, from the search's
605 /// candidates *and* from a committed inter block's final prediction --
606 /// and that final prediction runs OUTSIDE any bucket-0 region. So bucket 1
607 /// is neither inside bucket 0 nor smaller than it, and a print that shows
608 /// it as "motion search (of which interpolation ...)" necessarily shows
609 /// a sub-number bigger than its parent. Measured: bucket 0 = 17.82 ms,
610 /// bucket 1 = 148.63 ms.
611 ///
612 /// Which number is real: BOTH timers are right; only the old ARITHMETIC
613 /// was wrong. Bucket 1 is now printed as its own top-level row, the
614 /// overlap is stated, and the residual is labelled for what it is -- it
615 /// absorbs the committed block's own interpolation, so it is not a pure
616 /// "13-mode intra candidate loop" figure either.
617 ///
618 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
619 #[test]
620 #[ignore = "a perf probe, not a gate"]
621 fn stage_timing_breakdown_inter() {
622 let _knobs = crate::speed::knob_read();
623 let fctx = &crate::decode::FrameCtx::for_encoder();
624 use std::time::Instant;
625
626 let (width, height) = (1280usize, 720);
627 let picture = test_card(width, height);
628 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
629 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
630 let padded_pic = picture.padded_to(SUPERBLOCK);
631
632 stage_reset();
633 let t = Instant::now();
634 let inter = encode_inter_frame(
635 &padded_pic,
636 &padded_ref,
637 100,
638 0.5,
639 1,
640 flat_order_hints(1, 0, false),
641 (width, height),
642 None,
643 None,
644 None,
645 None,
646 fctx,
647 None,
648 &[],
649 )
650 .unwrap();
651 let total_t = t.elapsed();
652 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
653 // Buckets 0 and 2 and 3 are disjoint and additive. Bucket 1 (every
654 // `mc::predict` call) is NOT added: it overlaps bucket 0 wherever a
655 // search candidate calls predict, and it also covers the committed
656 // block's final prediction, which no other bucket times. Adding it
657 // would double-count the overlap; leaving it out puts the committed
658 // prediction (and the intra candidate loop, RD glue, and the symbol
659 // lookups outside `coeff_bits`) into the residual, which is what the
660 // residual has always been.
661 let accounted = motion_search + transform_quant + entropy;
662 let other = total_t.saturating_sub(accounted);
663 let overlap = interpolation.saturating_sub(motion_search);
664
665 eprintln!(
666 "\n=== inter frame {width}x{height}, one frame ===\n\
667 total: {total_t:>9.2?} ({} bytes)\n\
668 NEWMV/GLOBAL sub-search (bucket 0): {motion_search:>9.2?}\n\
669 transform + quantize (bucket 2): {transform_quant:>9.2?}\n\
670 coeff_bits, entropy pricing (bucket 3): {entropy:>9.2?}\n\
671 buckets 0+2+3 accounted: {accounted:>9.2?}\n\
672 \n\
673 OVERLAPPING, not additive: every mc::predict call (bucket 1) {interpolation:>9.2?}\n\
674 \x20 -- of which {overlap:>9.2?} is OUTSIDE bucket 0 (a committed\n\
675 \x20 inter block's final prediction, which no bucket above times)\n\
676 \x20 and the rest is the search candidates' interpolation, already\n\
677 \x20 inside bucket 0. It is deliberately NOT added to the total.\n\
678 \n\
679 residual (13-mode intra candidate loop, the committed block's\n\
680 \x20 interpolation above, NEARESTMV's own predict, RD glue): {other:>9.2?}",
681 inter.stream.len(),
682 );
683 }
684
685 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
686 /// frames (a dark/flat one, a detailed one, a normal film one) at two
687 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
688 /// None`, the baseline this same build produces without
689 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
690 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
691 /// go in the lane report, which is where "ship as default" is decided --
692 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
693 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
694 #[test]
695 // The three clip paths are HARD-CODED ABSOLUTES under /home/user, not
696 // env-driven: off this workstation every row prints `SKIP <label>: <path>
697 // not present on this machine` and the run exits 0 with no numbers. It is
698 // a local-run probe; there is no fleet-host configuration that makes it
699 // measure anything.
700 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
701 pub(super) fn prune_k_quality_sweep() {
702 let _knobs = crate::speed::knob_read();
703 let fctx = &crate::decode::FrameCtx::for_encoder();
704 if !have_ffmpeg() {
705 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
706 return;
707 }
708 let (width, height) = (640usize, 352usize);
709 let frames: &[(&str, &str, &str)] = &[
710 // (label, clip, seek) -- a near-black scene, a busy one, and an
711 // ordinary film frame, each from a different real file.
712 (
713 "dark/flat",
714 "/home/user/Videos/reela.mp4",
715 "3",
716 ),
717 (
718 "detailed",
719 "/home/user/Downloads/reelb.mkv",
720 "1200",
721 ),
722 (
723 "film",
724 "/home/user/Videos/Films/reelc.mkv",
725 "600",
726 ),
727 ];
728 for &(label, clip, skip) in frames {
729 if !std::path::Path::new(clip).exists() {
730 eprintln!("SKIP {label}: {clip} not present on this machine");
731 continue;
732 }
733 let picture = clip_frame(clip, skip, width, height);
734 for &q in &[60u8, 150] {
735 // Note (process-global, not a memory question): this is
736 // a single-threaded #[ignore] probe, run by hand, never
737 // alongside other tests that read Search::top_k.
738 set_test_top_k_override(None);
739 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
740 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
741 eprint!(
742 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
743 baseline.stream.len(),
744 baseline_psnr
745 );
746 for &k in &[3usize, 4, 6] {
747 set_test_top_k_override(Some(k));
748 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
749 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
750 eprint!(
751 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
752 pruned.stream.len(),
753 pruned_psnr,
754 pruned_psnr - baseline_psnr
755 );
756 }
757 eprintln!();
758 }
759 }
760 set_test_top_k_override(None);
761 }
762
763 /// Two consecutive decoded frames from one clip, for an inter-frame
764 /// sweep -- [`clip_frame`] alone only ever gives one.
765 pub(super) fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
766 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
767 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
768 .args(["-vf", &format!("scale={width}:{height}")])
769 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())
770 .expect("ffmpeg failed to run");
771 assert!(
772 out.status.success(),
773 "ffmpeg: {}",
774 String::from_utf8_lossy(&out.stderr)
775 );
776 let (luma, chroma) = (width * height, width * height / 4);
777 let frame_len = luma + 2 * chroma;
778 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
779 std::array::from_fn(|i| {
780 let bytes = &out.stdout[i * frame_len..][..frame_len];
781 Picture {
782 width,
783 height,
784 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
785 u: bytes[luma..luma + chroma]
786 .iter()
787 .map(|&v| u16::from(v))
788 .collect(),
789 v: bytes[luma + chroma..]
790 .iter()
791 .map(|&v| u16::from(v))
792 .collect(),
793 }
794 })
795 }
796
797 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
798 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
799 /// then one inter frame off it (`search_inter_block`'s own intra
800 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
801 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
802 /// padding step complicates the comparison. Prints bytes and luma PSNR
803 /// for the inter frame alone, unpruned vs each `K`.
804 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
805 #[test]
806 // Same hard-coded /home/user clip paths as `prune_k_quality_sweep`;
807 // off this workstation it SKIPs all three rows and prints nothing.
808 #[ignore = "local-run only: the three clips are hard-coded /home/user paths, so off this workstation it SKIPs every row and prints nothing"]
809 pub(super) fn prune_k_quality_sweep_inter() {
810 let _knobs = crate::speed::knob_read();
811 let fctx = &crate::decode::FrameCtx::for_encoder();
812 if !have_ffmpeg() {
813 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
814 return;
815 }
816 let (width, height) = (1280usize, 704usize);
817 let frames: &[(&str, &str, &str)] = &[
818 (
819 "dark/flat",
820 "/home/user/Videos/reela.mp4",
821 "3",
822 ),
823 (
824 "detailed",
825 "/home/user/Downloads/reelb.mkv",
826 "1200",
827 ),
828 (
829 "film",
830 "/home/user/Videos/Films/reelc.mkv",
831 "600",
832 ),
833 ];
834 for &(label, clip, skip) in frames {
835 if !std::path::Path::new(clip).exists() {
836 eprintln!("SKIP {label}: {clip} not present on this machine");
837 continue;
838 }
839 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
840 for &q in &[60u8, 150] {
841 // Note (process-global, not a memory question): a
842 // single-threaded #[ignore] probe, run by hand, never
843 // alongside other tests that read Search::top_k.
844 set_test_top_k_override_inter(None);
845 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
846 let baseline = encode_inter_frame(
847 &inter_source,
848 &key.reconstruction,
849 q,
850 0.5,
851 1,
852 flat_order_hints(1, 0, false),
853 (width, height),
854 None,
855 None,
856 None,
857 None,
858 fctx,
859 None,
860 &[],
861 )
862 .unwrap();
863 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
864 eprint!(
865 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
866 baseline.stream.len(),
867 baseline_psnr
868 );
869 for &k in &[3usize, 4, 6] {
870 set_test_top_k_override_inter(Some(k));
871 let pruned = encode_inter_frame(
872 &inter_source,
873 &key.reconstruction,
874 q,
875 0.5,
876 1,
877 flat_order_hints(1, 0, false),
878 (width, height),
879 None,
880 None,
881 None,
882 None,
883 fctx,
884 None,
885 &[],
886 )
887 .unwrap();
888 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
889 eprint!(
890 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
891 pruned.stream.len(),
892 pruned_psnr,
893 pruned_psnr - baseline_psnr
894 );
895 }
896 eprintln!();
897 }
898 }
899 set_test_top_k_override_inter(None);
900 }
901
902 /// `frames` consecutive pictures out of a real clip, scaled to a whole
903 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
904 /// to an arbitrary count for the fixture regression gate below.
905 pub(super) fn clip_frames(
906 clip: &str,
907 skip: &str,
908 width: usize,
909 height: usize,
910 frames: usize,
911 ) -> Vec<Picture> {
912 clip_frames_vf(
913 clip,
914 skip,
915 &format!("scale={width}:{height}"),
916 width,
917 height,
918 frames,
919 )
920 }
921
922 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
923 /// for a native-resolution CROP instead of a downscale (the downscale is
924 /// what destroys a screen capture's exact repeats -- class
925 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
926 pub(super) fn clip_frames_vf(
927 clip: &str,
928 skip: &str,
929 vf: &str,
930 width: usize,
931 height: usize,
932 frames: usize,
933 ) -> Vec<Picture> {
934 // ONE definition of the gate's loader recipe, shared with
935 // `examples/enc_probe` so the instrument cannot arm a different source
936 // than the gate it reports on (class `instrument disagrees with the
937 // gate`; lane-probe).
938 crate::probe::source(clip, skip, vf, width, height, frames)
939 }
940
941 /// The standing regression gate on real content: 12 frames of a real
942 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
943 /// this crate's own input regardless of its own source codec), encoded
944 /// as an AV1 GOP and checked against three numeric floors so a
945 /// compatibility or quality regression fails the suite instead of
946 /// waiting for a downstream repo's gate to catch it (as happened for a
947 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
948 /// refusal, both caught only that way).
949 ///
950 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
951 /// that geometry is already covered elsewhere), chosen only so encode
952 /// time and gate numbers are not muddied by an edge-block class this
953 /// test is not about.
954 ///
955 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
956 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
957 /// below carry a margin off those measured numbers (PSNR floor =
958 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
959 #[test]
960 fn real_clip_encodes_within_its_quality_and_size_budget() {
961 let _knobs = crate::speed::knob_read();
962 let fctx = &crate::decode::FrameCtx::for_encoder();
963 if !have_ffmpeg() {
964 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
965 return;
966 }
967 // lane-av1clipprobe: the clip's absence was a bare `clip.exists()`
968 // -> SKIP with no env escape, so this gate reported green on a tree
969 // with no root `fixtures/`. The probe prints that one line (naming the
970 // resolved path) and fails under the require envs.
971 let Some(clip) = crate::library_fixture::require(
972 "video/h264-1080p-23.976-8bit.mp4",
973 "real_clip_encodes_within_its_quality_and_size_budget",
974 ) else {
975 return;
976 };
977 let (width, height, frame_count) = (640usize, 384usize, 12usize);
978 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
979 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
980 assert_eq!(encoded.frames.len(), frame_count);
981
982 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
983 // stream and hands back every frame -- a stream a downstream
984 // decoder refuses is the exact class of regression this gate
985 // exists for.
986 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
987 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
988
989 // Gate 2: quality vs the source did not silently collapse.
990 let mean_psnr: f64 = decoded
991 .iter()
992 .zip(&source)
993 .map(|(d, s)| psnr(&d.y, &s.y))
994 .sum::<f64>()
995 / frame_count as f64;
996 assert!(
997 mean_psnr >= 44.91,
998 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
999 );
1000
1001 // Gate 3: the stream did not silently bloat.
1002 assert!(
1003 encoded.stream.len() <= 80_340,
1004 "stream grew to {} bytes, over the 80340-byte ceiling",
1005 encoded.stream.len()
1006 );
1007 }
1008
1009 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
1010 /// straddle size: 640x384 is exact on both axes (32-aligned), so
1011 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
1012 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
1013 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
1014 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
1015 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
1016 /// card; this one is the real-clip gate, same three floors.
1017 ///
1018 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
1019 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
1020 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
1021 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
1022 #[test]
1023 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
1024 let _knobs = crate::speed::knob_read();
1025 let fctx = &crate::decode::FrameCtx::for_encoder();
1026 if !have_ffmpeg() {
1027 eprintln!(
1028 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
1029 no ffmpeg"
1030 );
1031 return;
1032 }
1033 // lane-av1clipprobe: see the sibling gate above -- the bare
1034 // `clip.exists()` -> SKIP had no env escape.
1035 let Some(clip) = crate::library_fixture::require(
1036 "video/h264-1080p-23.976-8bit.mp4",
1037 "real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size",
1038 ) else {
1039 return;
1040 };
1041 let (width, height, frame_count) = (704usize, 400usize, 8usize);
1042 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
1043 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
1044 assert_eq!(encoded.frames.len(), frame_count);
1045
1046 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
1047 // stream and hands back every frame.
1048 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
1049 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
1050
1051 // Gate 2: quality vs the source did not silently collapse.
1052 let mean_psnr: f64 = decoded
1053 .iter()
1054 .zip(&source)
1055 .map(|(d, s)| psnr(&d.y, &s.y))
1056 .sum::<f64>()
1057 / frame_count as f64;
1058 assert!(
1059 mean_psnr >= 44.98,
1060 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
1061 );
1062
1063 // Gate 3: the stream did not silently bloat.
1064 assert!(
1065 encoded.stream.len() <= 62_703,
1066 "stream grew to {} bytes, over the 62703-byte ceiling",
1067 encoded.stream.len()
1068 );
1069 }
1070
1071 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
1072 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
1073 /// facade -- timed end to end, so the edith export-time projection is a
1074 /// real number rather than a guess from the isolated key/inter numbers
1075 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
1076 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
1077 #[test]
1078 #[ignore = "a perf probe, not a gate"]
1079 fn sequence_bench_sanity() {
1080 let _knobs = crate::speed::knob_read();
1081 let fctx = &crate::decode::FrameCtx::for_encoder();
1082 use std::time::Instant;
1083 let (width, height) = (1280usize, 720usize);
1084 let pictures: Vec<Picture> = (0..24)
1085 .map(|i| panned_test_card(width, height, i * 3))
1086 .collect();
1087 let t = Instant::now();
1088 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
1089 let elapsed = t.elapsed();
1090 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
1091 eprintln!(
1092 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
1093 elapsed / 24
1094 );
1095 }
1096
1097 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
1098 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
1099 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
1100 /// -- --ignored --nocapture`.
1101 #[test]
1102 #[ignore = "a calibration probe, not a gate"]
1103 fn calibration_sweep_base_q_idx() {
1104 let _knobs = crate::speed::knob_read();
1105 let fctx = &crate::decode::FrameCtx::for_encoder();
1106 if !have_ffmpeg() {
1107 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
1108 return;
1109 }
1110 let (width, height, frames) = (640usize, 384usize, 12usize);
1111 for clip in [
1112 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
1113 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
1114 ] {
1115 // lane-av1clipprobe: the crate's one fixture root and its one
1116 // presence probe -- the bare `path.exists()` -> SKIP -> `continue`
1117 // had no env escape, and with every clip absent the sweep looped
1118 // zero times and passed.
1119 let Some(path) = crate::library_fixture::require(
1120 &format!("video/{clip}"),
1121 &format!("calibration_sweep_base_q_idx: {clip}"),
1122 ) else {
1123 continue;
1124 };
1125 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
1126 eprintln!("--- {clip} ---");
1127 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
1128 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
1129 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
1130 let mean_psnr: f64 = decoded
1131 .iter()
1132 .zip(&source)
1133 .map(|(d, s)| psnr(&d.y, &s.y))
1134 .sum::<f64>()
1135 / frames as f64;
1136 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
1137 eprintln!(
1138 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
1139 encoded.stream.len()
1140 );
1141 }
1142 }
1143 }
1144
1145 // -----------------------------------------------------------------------
1146 // The encoder's standing BD-rate baseline against libaom and rav1e.
1147 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
1148 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
1149 // agreeing with our encoder proves nothing about the bitstream.
1150 // -----------------------------------------------------------------------
1151
1152 /// All-plane PSNR of a decoded picture against its source, on the same
1153 /// 8-bit scale [`psnr`] uses.
1154 pub(super) fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
1155 let cat = |p: &Picture| {
1156 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
1157 v.extend_from_slice(&p.y);
1158 v.extend_from_slice(&p.u);
1159 v.extend_from_slice(&p.v);
1160 v
1161 };
1162 psnr(&cat(decoded), &cat(source))
1163 }
1164
1165 /// The pictures back as the planar 8-bit bytes an encoder reads.
1166 pub(super) fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
1167 let mut raw = Vec::new();
1168 for p in source {
1169 for plane in [&p.y, &p.u, &p.v] {
1170 raw.extend(plane.iter().map(|&s| s as u8));
1171 }
1172 }
1173 raw
1174 }
1175
1176 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
1177 /// through ffmpeg: one point per entry of `points`, each a quality flag
1178 /// set. Returns the ladder ordered by fidelity and the total encode wall
1179 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
1180 /// so both curves are measured by the same decoder.
1181 pub(super) fn external_ladder(
1182 source: &[Picture],
1183 width: usize,
1184 height: usize,
1185 encoder: &str,
1186 points: &[Vec<String>],
1187 ) -> (Vec<(f64, f64)>, f64) {
1188 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
1189 let dir = std::env::temp_dir();
1190 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
1191 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
1192 let mut ladder = Vec::new();
1193 let mut wall = 0.0;
1194 for (i, params) in points.iter().enumerate() {
1195 let obu = dir.join(format!(
1196 "ec-av1-bd-{}-{encoder}-{i}.obu",
1197 std::process::id()
1198 ));
1199 let start = std::time::Instant::now();
1200 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1201 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
1202 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
1203 .arg(&raw_path)
1204 .args(["-an", "-threads", "1"])
1205 .args(["-g", &source.len().to_string(), "-c:v", encoder])
1206 .args(params)
1207 .args(["-f", "obu"])
1208 .arg(&obu), None, |c| c.output())
1209 .expect("ffmpeg failed to run");
1210 wall += start.elapsed().as_secs_f64();
1211 assert!(
1212 out.status.success(),
1213 "{encoder} {params:?}: {}",
1214 String::from_utf8_lossy(&out.stderr)
1215 );
1216 let stream = std::fs::read(&obu).expect("reference stream");
1217 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
1218 // lane-dkey: every reference point must also decode through OUR
1219 // decoder, sample-exact against ffmpeg's decode of the same bytes.
1220 // A BD table computed off streams we cannot read is a table about
1221 // an encoder we cannot check; this is the assertion that would
1222 // have caught the `force_integer_mv` defect (its stream decoded to
1223 // 25 dB garbage while this gate stayed green) and the crf-5 key
1224 // frame desync. A failure names the encoder, the point's flags and
1225 // the first differing frame/plane/sample.
1226 // lane-dpm1: a failing reference point is COLLECTED, not panicked
1227 // on, so one run still prints the whole BD table and names every
1228 // bad point instead of stopping at the first. The collection is
1229 // asserted empty by [`assert_ladder_decodes`] at the end of each
1230 // gate.
1231 match crate::stream::decode_stream(&stream) {
1232 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
1233 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
1234 ours.len(),
1235 decoded.len(),
1236 )),
1237 Ok(ours) => {
1238 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
1239 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
1240 note_ladder_failure(format!(
1241 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
1242 decoder decoded {got}, ffmpeg {want}"
1243 ));
1244 break;
1245 }
1246 }
1247 }
1248 Err(e) => note_ladder_failure(format!(
1249 "{encoder} {params:?}: our decoder refused the stream ({e})"
1250 )),
1251 }
1252 let mean: f64 = decoded
1253 .iter()
1254 .zip(source)
1255 .map(|(d, s)| psnr_all(d, s))
1256 .sum::<f64>()
1257 / source.len() as f64;
1258 ladder.push((mean, (stream.len() as f64).log10()));
1259 let _ = std::fs::remove_file(&obu);
1260 }
1261 let _ = std::fs::remove_file(&raw_path);
1262 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
1263 (ladder, wall)
1264 }
1265
1266 /// Every reference ladder point that did not decode sample-exactly
1267 /// through our own decoder, collected across a whole gate run so the BD
1268 /// table still prints and EVERY bad point is named
1269 /// (`encoder params frame plane sample`) instead of only the first.
1270 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
1271
1272 pub(super) fn note_ladder_failure(msg: String) {
1273 eprintln!("LADDER DECODE FAILURE: {msg}");
1274 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
1275 }
1276
1277 /// Fail the gate at its END on everything [`external_ladder`] collected.
1278 pub(super) fn assert_ladder_decodes() {
1279 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
1280 assert!(
1281 failures.is_empty(),
1282 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
1283 failures.len(),
1284 failures.join("\n"),
1285 );
1286 }
1287
1288 /// First differing sample between two pictures, as
1289 /// `(plane, index, left, right)` -- so a gate failure names the plane and
1290 /// the sample instead of just "differs". A length difference counts as a
1291 /// mismatch of that plane at the first index past the shorter one.
1292 pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
1293 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
1294 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
1295 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
1296 }
1297 if l.len() != r.len() {
1298 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
1299 }
1300 }
1301 None
1302 }
1303
1304 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
1305 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
1306 /// stream is decoded twice -- by ffmpeg and by our own
1307 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
1308 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
1309 /// in Y, U and V over every shown frame in display order. That is itself
1310 /// a gate: it proves the bitstream says what the encoder thinks, in the
1311 /// only two decoders that read it.
1312 pub(super) fn our_ladder(
1313 name: &str,
1314 source: &[Picture],
1315 width: usize,
1316 height: usize,
1317 fctx: &crate::decode::FrameCtx,
1318 ) -> (Vec<(f64, f64)>, f64) {
1319 let mut ladder = Vec::new();
1320 let mut wall = 0.0;
1321 for &q in &[150u8, 120, 90, 60] {
1322 let start = std::time::Instant::now();
1323 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
1324 // the gate has to be able to re-sweep it. 0.5 is the shipped one
1325 // (`crate::encoder::DEADZONE`).
1326 let deadzone = std::env::var("EC_AV1_DEADZONE")
1327 .ok()
1328 .and_then(|v| v.parse().ok())
1329 .unwrap_or(0.5);
1330 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
1331 wall += start.elapsed().as_secs_f64();
1332 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
1333 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
1334 assert_eq!(
1335 ours.len(),
1336 source.len(),
1337 "{name} q={q}: our decoder's display-order frame count"
1338 );
1339 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
1340 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
1341 panic!(
1342 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
1343 {got}, the encoder reconstructed {want}"
1344 );
1345 }
1346 }
1347 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
1348 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
1349 panic!(
1350 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
1351 {got}, the encoder reconstructed {want}"
1352 );
1353 }
1354 }
1355 let per_frame: Vec<f64> = decoded
1356 .iter()
1357 .zip(source)
1358 .map(|(d, s)| psnr_all(d, s))
1359 .collect();
1360 // lane-txrd: does a tool's loss start at the FIRST inter frame
1361 // (a local mispricing) or grow down the GOP (propagation into
1362 // the reference chain)? One line per q point answers it.
1363 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
1364 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
1365 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
1366 // lane-txrd: per PLANE, because an all-plane mean hides a
1367 // collapse in one of them (class `metric blind to a plane`).
1368 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
1369 let v: Vec<String> = decoded
1370 .iter()
1371 .zip(source)
1372 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
1373 .collect();
1374 v.join(" ")
1375 };
1376 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
1377 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
1378 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
1379 }
1380 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
1381 ladder.push((mean, (encoded.stream.len() as f64).log10()));
1382 }
1383 // What this clip asked for and what the content gate left it coding
1384 // under: a screen clip requests a pyramid and codes flat, and that
1385 // difference is what keeps its row identical to the flat baseline
1386 // (class `gate-blind-to-feature`).
1387 eprintln!(
1388 "{name}: sequence, pyramid requested {:?} effective {:?}",
1389 crate::encoder::Pyramid::from_env(),
1390 last_sequence_pyramid(),
1391 );
1392 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
1393 (ladder, wall)
1394 }
1395
1396 /// [`our_ladder`] through the streaming facade — the surface the editor's
1397 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
1398 /// each stream is also reordered (hidden `ALTREF` first,
1399 /// `show_existing_frame` last per group) and each level is coded at its
1400 /// own quantizer offset; without one it is the flat ladder, which
1401 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1402 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
1403 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
1404 /// the whole ladder how many frames and how many bytes it spent, and the
1405 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
1406 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
1407 /// flat path, so a requested pyramid can come back `None` here.
1408 pub(super) fn our_ladder_facade(
1409 name: &str,
1410 source: &[Picture],
1411 width: usize,
1412 height: usize,
1413 pyramid: Option<crate::encoder::Pyramid>,
1414 ) -> (
1415 Vec<(f64, f64)>,
1416 f64,
1417 [usize; 4],
1418 [usize; 4],
1419 Option<crate::encoder::Pyramid>,
1420 ) {
1421 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
1422 let slot = |l: Level| match l {
1423 Level::Key => 0,
1424 Level::Arf => 1,
1425 Level::Leaf => 2,
1426 Level::ShowExisting => 3,
1427 };
1428 let mut ladder = Vec::new();
1429 let mut wall = 0.0;
1430 let mut effective = None;
1431 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
1432 for &q in &[150u8, 120, 90, 60] {
1433 let config = EncoderConfig {
1434 width,
1435 height,
1436 base_q_idx: q,
1437 gop: source.len(),
1438 colour: Colour::Unspecified,
1439 tile_cols_log2: 0,
1440 tile_rows_log2: 0,
1441 };
1442 let start = std::time::Instant::now();
1443 let mut enc = match pyramid {
1444 None => Av1Encoder::new(config).unwrap(),
1445 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
1446 };
1447 let mut packets = Vec::new();
1448 for picture in source {
1449 packets.extend(enc.encode_frames(picture).unwrap());
1450 }
1451 packets.extend(enc.flush().unwrap());
1452 wall += start.elapsed().as_secs_f64();
1453 effective = enc.pyramid();
1454 let mut stream = Vec::new();
1455 for p in &packets {
1456 counts[slot(p.level)] += 1;
1457 bytes[slot(p.level)] += p.data.len();
1458 stream.extend_from_slice(&p.data);
1459 }
1460 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
1461 // correct if the DISPLAY-order output still has one frame per
1462 // source picture, in the right order -- checked against our own
1463 // decoder as well as ffmpeg's, both below.
1464 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1465 assert_eq!(
1466 ours.len(),
1467 source.len(),
1468 "{name} q={q}: our display-order count"
1469 );
1470 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
1471 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
1472 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
1473 panic!(
1474 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
1475 decoded {got}, our decoder decoded {want}"
1476 );
1477 }
1478 }
1479 let mean: f64 = decoded
1480 .iter()
1481 .zip(source)
1482 .map(|(d, s)| psnr_all(d, s))
1483 .sum::<f64>()
1484 / source.len() as f64;
1485 ladder.push((mean, (stream.len() as f64).log10()));
1486 }
1487 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
1488 (ladder, wall, counts, bytes, effective)
1489 }
1490
1491 /// Byte-exactness gate for encoder work that is meant to change only
1492 /// how long the encoder takes.
1493 ///
1494 /// The BD gate above measures quality, which a speed lane can move by a
1495 /// hair without failing anything; this pins the streams themselves.
1496 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
1497 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
1498 /// in the tile) and again on lane-av1mv's merge of it: an extra
1499 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
1500 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
1501 /// prices coefficients against the tables the frame's writer really
1502 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
1503 /// decision change the BD gate judges. Re-pinned again on
1504 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
1505 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
1506 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
1507 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
1508 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
1509 /// by default ([`warp_on`], a sequence/frame header bit and a new
1510 /// motion_mode symbol on eligible blocks) and
1511 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
1512 /// every inter frame's superblocks now code at their own lambda
1513 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
1514 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
1515 /// and the two var-tx depth searches ([`tx32_depth_search`],
1516 /// [`compound_var_tx`]) are on by default, all three re-judged on the
1517 /// native gate's real film rows.
1518 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
1519 /// every block whose chroma takes it codes a different mode symbol, two
1520 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
1521 /// restores the previous streams. Re-pinned again in the same lane once
1522 /// directional luma winners searched their `angle_delta_y`
1523 /// (`EC_AV1_ANGLE=0` restores that half).
1524 #[test]
1525 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
1526 // These are DEFAULT-PRESET pins: a speed preset switches search levers
1527 // off, so it legitimately moves every byte. Encode at speed 0 whatever
1528 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
1529 let _knobs = crate::speed::knob_write();
1530 let was = crate::speed::speed();
1531 crate::speed::set_speed(0);
1532 if !have_ffmpeg() {
1533 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
1534 return;
1535 }
1536 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
1537 // so a tree with no root `fixtures/` reported this gate green having
1538 // compared nothing at all.
1539 let Some(clip) = crate::library_fixture::require(
1540 "video/h264-1080p-23.976-8bit.mp4",
1541 "the_encoders_own_streams_are_byte_identical_to_their_pins",
1542 ) else {
1543 return;
1544 };
1545 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
1546 // FNV-1a over the stream: a witness that every coded bit is where it
1547 // was, which a byte count alone is not.
1548 let fnv = |b: &[u8]| {
1549 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
1550 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
1551 })
1552 };
1553 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
1554 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
1555 // of 4, its leaves at q+8 and a `show_existing_frame` header per
1556 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
1557 // four frames; four pictures is one short mini-GOP, which is the
1558 // shape that pays least (the ARF's own quality has no later group to
1559 // carry it), so this is not the BD gate's number.
1560 // Re-taken again on lane-av1cfl: the chroma search offers
1561 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
1562 // so every block taking either codes different syntax and different
1563 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
1564 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
1565 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
1566 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
1567 // so these four pictures code as one truncated group -- a hidden
1568 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
1569 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
1570 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
1571 // Re-taken on lane-fintra: the sequence header sets
1572 // `enable_filter_intra`, so every DC_PRED intra block of at most
1573 // 32x32 without a luma palette carries a `use_filter_intra` flag and
1574 // the blocks that take one code a filter-intra mode, a different
1575 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
1576 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
1577 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
1578 // (default pyramid `8:-32:16`, one truncated group of 8 with its
1579 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
1580 // root can code a REAL residual now (one TX_64X64 luma transform and
1581 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
1582 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
1583 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
1584 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
1585 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
1586 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
1587 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
1588 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
1589 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
1590 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
1591 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
1592 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
1593 // these four pictures -- offers every superblock a 64x64 intra root
1594 // now. `EC_AV1_I64=0` restores 8557 / 33345.
1595 // Re-taken on lane-pricer: the inter RD search prices a single
1596 // reference through the tree and the neighbour contexts the writer
1597 // really codes it with, so every inter picture's reference decisions
1598 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
1599 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
1600 // for `skip`/`is_inter` and for the whole compound reference tree, so
1601 // every inter block's cost -- and with it the skip and reference
1602 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
1603 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
1604 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
1605 // single and compound are priced against the same syntax -- 8311 ->
1606 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
1607 // Re-taken on lane-newmv: the motion search charges its own rate term
1608 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
1609 // and each subpel stage re-runs from its own winner
1610 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
1611 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
1612 // and 33014 -> 33090 at q=60.
1613 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
1614 // from libaom's objective tpl mapping, so every inter picture's
1615 // quantizer grid -- and every decision priced against it -- moved
1616 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
1617 // at the merge of both lanes.
1618 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
1619 // per-superblock `delta_qindex` at 1.5x the preset's strength
1620 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
1621 // grids -- and every decision priced against them -- moved:
1622 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
1623 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
1624 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
1625 // pixels -- and the leaves that predict from them -- moved:
1626 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
1627 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
1628 // the shipped stream did not move.
1629 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
1630 // picture is coded in 128x128 superblocks now, the inter ones
1631 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
1632 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
1633 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
1634 // by default, on top of the ARF temporal filter).
1635 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
1636 // candidates the 64 root already did ([`b128_compound`]), so every
1637 // inter frame that carries `reference_select` codes different blocks
1638 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
1639 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
1640 // Re-taken on lane-arftf: that filter's strength swept on the deciding
1641 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
1642 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
1643 // 33017 at q=60 (the same LENGTH, different bytes).
1644 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
1645 // lane-rlclamp onto the 128 compound default.
1646 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
1647 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
1648 // so every inter frame whose RD takes one codes a different partition
1649 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
1650 // quantizer the rect cut never wins its own comparison on this clip.
1651 // `EC_AV1_B128HV=0` restores 8290 exactly.
1652 let pins: [(u8, usize, u64); 2] = [
1653 (150, 8291, 0x1f00bb0eb099a27f),
1654 (60, 33227, 0x57ee6b1f8eacd881),
1655 ];
1656 let coded: Vec<(u8, usize, u64)> = pins
1657 .iter()
1658 .map(|&(q, _, _)| {
1659 let e = encode_sequence(&source, q, 0.5).unwrap();
1660 (q, e.stream.len(), fnv(&e.stream))
1661 })
1662 .collect();
1663 crate::speed::set_speed(was);
1664 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
1665 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
1666 }
1667 }
1668
1669 /// A ladder is only a ladder if both axes rise together.
1670 pub(super) fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
1671 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
1672 for w in ladder.windows(2) {
1673 assert!(
1674 w[1].0 > w[0].0 && w[1].1 > w[0].1,
1675 "{name}: not monotone, {ladder:?}"
1676 );
1677 }
1678 }
1679
1680 /// The sweep behind [`screen_content`]'s constants
1681 /// (`unswept-decision-constants`), on the SAME five clips
1682 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
1683 /// same native crop: for each colour bound N the share of 16x16 luma
1684 /// blocks with 2..=N distinct colours, and the share of those whose
1685 /// per-pixel variance also clears a floor V -- libaom's
1686 /// `av1_set_screen_content_options` counts the variance-cleared blocks
1687 /// too (its `counts_2`, which gates intrabc), and without that term a
1688 /// smooth dark film frame reads as screen content.
1689 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
1690 #[test]
1691 #[ignore = "reads the real library"]
1692 fn probe_screen_detect() {
1693 let _knobs = crate::speed::knob_read();
1694 if !have_ffmpeg() {
1695 eprintln!("SKIP probe_screen_detect: no ffmpeg");
1696 return;
1697 }
1698 let limits = [4usize, 8, 16, 32, 64, 128];
1699 let floors = [0u64, 4, 16, 64, 256];
1700 // The census of one clip at one size: mean share, over the frames, of
1701 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
1702 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
1703 let mut acc = [[0f64; 5]; 6];
1704 for picture in frames {
1705 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1706 let mut hit = [[0usize; 5]; 6];
1707 let mut blocks = 0usize;
1708 for by in (0..ch).step_by(16) {
1709 for bx in (0..cw).step_by(16) {
1710 let mut seen = [false; 256];
1711 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1712 for row in 0..16 {
1713 for col in 0..16 {
1714 let v = y[(by + row) * cw + bx + col];
1715 sum += u64::from(v);
1716 sq += u64::from(v) * u64::from(v);
1717 if !seen[usize::from(v)] {
1718 seen[usize::from(v)] = true;
1719 colors += 1;
1720 }
1721 }
1722 }
1723 let var = (sq - sum * sum / 256) / 256;
1724 blocks += 1;
1725 for (li, &limit) in limits.iter().enumerate() {
1726 if colors > 1 && colors <= limit {
1727 for (fi, &floor) in floors.iter().enumerate() {
1728 hit[li][fi] += usize::from(var > floor);
1729 }
1730 }
1731 }
1732 }
1733 }
1734 for li in 0..6 {
1735 for fi in 0..5 {
1736 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
1737 }
1738 }
1739 }
1740 let n = frames.len().max(1) as f64;
1741 eprintln!(
1742 "{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:",
1743 frames.len()
1744 );
1745 eprintln!(
1746 " N \\ V |{}",
1747 floors.iter().map(|f| format!("{f:>8}")).collect::<String>()
1748 );
1749 for (li, &limit) in limits.iter().enumerate() {
1750 eprintln!(
1751 " {limit:>5} |{}",
1752 (0..5)
1753 .map(|fi| format!("{:>7.1}%", acc[li][fi] / n))
1754 .collect::<String>()
1755 );
1756 }
1757 };
1758 for (name, path, seek) in native_gate_clips() {
1759 let Some((nw, nh)) = probe_dims(&path) else {
1760 eprintln!("SKIP {name}: ffprobe gave no size");
1761 continue;
1762 };
1763 let cw = nw.min(1920) / 128 * 128;
1764 let ch = nh.min(1024) / 128 * 128;
1765 let (x, y0) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1766 let frames = clip_frames_vf(
1767 &path,
1768 &seek,
1769 &format!("crop={cw}:{ch}:{x}:{y0}"),
1770 cw,
1771 ch,
1772 12,
1773 );
1774 census(&name, &frames, cw, ch);
1775 // The 640x384 gate scales instead of cropping, and the scaling
1776 // changes the census (bars smooth out): the constants have to
1777 // separate at BOTH sizes.
1778 let small = clip_frames(&path, &seek, 640, 384, 12);
1779 census(&name, &small, 640, 384);
1780 }
1781 }
1782
1783 /// The detector against the WHOLE real library (class
1784 /// `unswept-decision-constants`, user rule "his data is the gate"):
1785 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
1786 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
1787 /// duration, four frames each, 8-bit 4:2:0, at native size or a
1788 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
1789 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
1790 /// Prints per file and offset the share of qualifying 16x16 blocks, the
1791 /// [`screen_content`] verdict and a content hint (mean luma, luma
1792 /// standard deviation, inter MAD), then sweeps the colour bound against
1793 /// the variance floor over the whole library: for each (N, V) the worst
1794 /// (highest) share among the camera/film rows against the best (lowest)
1795 /// among the screen-recording rows, so the rule with the widest gap can
1796 /// be read off. Rows carry the manifest index, codec and size only --
1797 /// no titles, no home paths.
1798 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
1799 #[test]
1800 #[ignore = "reads the real library"]
1801 fn probe_screen_library() {
1802 let _knobs = crate::speed::knob_read();
1803 if !have_ffmpeg() {
1804 eprintln!("SKIP probe_screen_library: no ffmpeg");
1805 return;
1806 }
1807 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
1808 let fixtures = crate::library_fixture::root();
1809 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
1810 else {
1811 eprintln!("SKIP probe_screen_library: no real-library manifest");
1812 return;
1813 };
1814 let limits = [4usize, 8, 16, 32, 64];
1815 let floors = [0u64, 4, 8, 16, 32, 64, 128];
1816 // Whatever ffmpeg gave us, without the exact-count assertion the
1817 // gate loaders make: a seek near the end of a clip returns fewer
1818 // frames, and that is a row to print, not a panic.
1819 let decode =
1820 |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
1821 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1822 .args(["-v", "error", "-ss", seek, "-i", clip])
1823 .args(["-frames:v", &n.to_string()])
1824 .args(["-vf", vf])
1825 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output());
1826 let Ok(out) = out else { return Vec::new() };
1827 if !out.status.success() {
1828 return Vec::new();
1829 }
1830 let (luma, chroma) = (w * h, w * h / 4);
1831 let frame_len = luma + 2 * chroma;
1832 (0..out.stdout.len() / frame_len)
1833 .map(|i| {
1834 let b = &out.stdout[i * frame_len..][..frame_len];
1835 Picture {
1836 width: w,
1837 height: h,
1838 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
1839 u: b[luma..luma + chroma]
1840 .iter()
1841 .map(|&v| u16::from(v))
1842 .collect(),
1843 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
1844 }
1845 })
1846 .collect()
1847 };
1848 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
1849 // variance > V, for every (N, V) of the sweep grid, over one frame.
1850 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
1851 let mut hit = [[0usize; 7]; 5];
1852 let mut blocks = 0usize;
1853 for by in (0..h).step_by(16) {
1854 for bx in (0..w).step_by(16) {
1855 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
1856 let mut seen = [false; 256];
1857 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1858 for row in 0..bh {
1859 for col in 0..bw {
1860 let v = y[(by + row) * w + bx + col];
1861 sum += u64::from(v);
1862 sq += u64::from(v) * u64::from(v);
1863 if !seen[usize::from(v)] {
1864 seen[usize::from(v)] = true;
1865 colors += 1;
1866 }
1867 }
1868 }
1869 let n = (bh * bw) as u64;
1870 let var = (sq - sum * sum / n) / n;
1871 blocks += 1;
1872 for (li, &limit) in limits.iter().enumerate() {
1873 if colors > 1 && colors <= limit {
1874 for (fi, &floor) in floors.iter().enumerate() {
1875 hit[li][fi] += usize::from(var > floor);
1876 }
1877 }
1878 }
1879 }
1880 }
1881 let mut out = [[0f64; 7]; 5];
1882 for li in 0..5 {
1883 for fi in 0..7 {
1884 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
1885 }
1886 }
1887 out
1888 };
1889 // (index, label, path, duration, screen-by-its-own-content). The
1890 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
1891 // are desktop recordings; everything else in this library is camera
1892 // or film material.
1893 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
1894 for (label, file) in [
1895 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
1896 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
1897 ] {
1898 let path = fixtures.join("video").join(file);
1899 if path.exists() {
1900 rows.push((
1901 "fx".into(),
1902 label.into(),
1903 path.to_str().unwrap().into(),
1904 10.0,
1905 false,
1906 ));
1907 }
1908 }
1909 for (i, line) in manifest.lines().skip(1).enumerate() {
1910 let f: Vec<&str> = line.split('\t').collect();
1911 if f.len() < 10 {
1912 continue;
1913 }
1914 let (path, codec) = (f[0], f[2]);
1915 if codec == "-" || codec.is_empty() {
1916 continue;
1917 }
1918 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
1919 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
1920 continue;
1921 };
1922 if !std::path::Path::new(path).exists() {
1923 eprintln!("SKIP {}: file is gone", i + 1);
1924 continue;
1925 }
1926 let name = path.rsplit('/').next().unwrap_or(path);
1927 let is_capture = path.contains("/OBS/")
1928 || (name.len() > 19
1929 && name.as_bytes()[4] == b'-'
1930 && name.as_bytes()[7] == b'-'
1931 && name.as_bytes()[10] == b' '
1932 && name.as_bytes()[13] == b'-');
1933 rows.push((
1934 format!("{}", i + 1),
1935 format!("{codec} {w}x{h}"),
1936 path.to_string(),
1937 f[8].parse::<f64>().unwrap_or(0.0),
1938 is_capture,
1939 ));
1940 }
1941 // Per (N, V): the worst camera/film row and the best screen row, so
1942 // the separation of the whole library is one subtraction.
1943 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
1944 eprintln!(
1945 "| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"
1946 );
1947 for (idx, label, path, dur, is_capture) in &rows {
1948 let Some((nw, nh)) = probe_dims(path) else {
1949 eprintln!("SKIP {idx}: ffprobe gave no size");
1950 continue;
1951 };
1952 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
1953 let (x, y0) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1954 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
1955 let mut file_grid = [[0f64; 7]; 5];
1956 let mut file_frames = 0usize;
1957 for pct in [10u32, 50, 90] {
1958 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
1959 let frames = decode(path, &seek, &vf, cw, ch, 4);
1960 if frames.is_empty() {
1961 eprintln!(
1962 "| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |",
1963 if *is_capture { "screen" } else { "camera" }
1964 );
1965 continue;
1966 }
1967 let (mut share, mut yes, mut mean, mut sd, mut mad) =
1968 (0f64, 0usize, 0f64, 0f64, 0f64);
1969 let mut prev: Option<Vec<u8>> = None;
1970 for picture in &frames {
1971 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1972 let grid = census(&y, cw, ch);
1973 for li in 0..5 {
1974 for fi in 0..7 {
1975 file_grid[li][fi] += grid[li][fi];
1976 }
1977 }
1978 file_frames += 1;
1979 // The shipped rule is (16 colours, var > 16): grid row 2,
1980 // floor 16 is column 3.
1981 share += grid[2][3];
1982 yes += usize::from(screen_content(&y, cw, cw, ch));
1983 let n = y.len() as f64;
1984 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
1985 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
1986 mean += sum / n;
1987 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
1988 if let Some(p) = &prev {
1989 mad += p
1990 .iter()
1991 .zip(&y)
1992 .map(|(&a, &b)| f64::from(a.abs_diff(b)))
1993 .sum::<f64>()
1994 / n;
1995 }
1996 prev = Some(y);
1997 }
1998 let f = frames.len() as f64;
1999 eprintln!(
2000 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
2001 if *is_capture { "screen" } else { "camera" },
2002 share / f,
2003 if yes * 2 > frames.len() {
2004 "SCREEN"
2005 } else {
2006 "camera"
2007 },
2008 frames.len(),
2009 mean / f,
2010 sd / f,
2011 mad / (f - 1.0).max(1.0),
2012 );
2013 }
2014 if file_frames == 0 {
2015 continue;
2016 }
2017 for li in 0..5 {
2018 for fi in 0..7 {
2019 let s = file_grid[li][fi] / file_frames as f64;
2020 match is_capture {
2021 true => scr_min[li][fi] = scr_min[li][fi].min(s),
2022 false => cam_max[li][fi] = cam_max[li][fi].max(s),
2023 }
2024 }
2025 }
2026 }
2027 eprintln!(
2028 "sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"
2029 );
2030 eprintln!(
2031 " N \\ V |{}",
2032 floors
2033 .iter()
2034 .map(|f| format!("{:>18}", format!("V>{f}")))
2035 .collect::<String>()
2036 );
2037 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
2038 for (li, &limit) in limits.iter().enumerate() {
2039 let mut row = String::new();
2040 for fi in 0..7 {
2041 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
2042 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
2043 if s - c > best {
2044 best = s - c;
2045 best_rule = (limit, floors[fi]);
2046 }
2047 }
2048 eprintln!(" {limit:>5} |{row}");
2049 }
2050 // The threshold sits at the midpoint of the widest gap; the shipped
2051 // constant is its reciprocal in whole parts of the frame.
2052 let (li, fi) = (
2053 limits.iter().position(|&l| l == best_rule.0).unwrap(),
2054 floors.iter().position(|&f| f == best_rule.1).unwrap(),
2055 );
2056 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
2057 eprintln!(
2058 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
2059 best_rule.0,
2060 best_rule.1,
2061 best,
2062 cam_max[li][fi],
2063 scr_min[li][fi],
2064 mid,
2065 (100.0 / mid.max(0.1)).round() as usize,
2066 );
2067 }
2068
2069 /// The missing instrument: what this encoder costs against libaom and
2070 /// rav1e at matched fidelity, and how long it takes to get there.
2071 ///
2072 /// Recipe, identical on all three sides: 12 consecutive frames of each
2073 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
2074 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
2075 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
2076 /// it by default), 4:2:0 8-bit in and out. Reference points:
2077 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
2078 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
2079 /// tile_cols=1:tile_rows=1:threads=1`
2080 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
2081 /// ffmpeg-decoded frames of each encoder's own stream.
2082 ///
2083 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
2084 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
2085 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
2086 /// four encodes of that ladder together):
2087 ///
2088 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
2089 /// |---|---|---|---|---|
2090 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
2091 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
2092 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
2093 ///
2094 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
2095 /// the encoder takes -- every stream it writes is byte-identical, so the
2096 /// BD columns are this box's own re-run of the same recipe rather than a
2097 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
2098 /// rav1e). What moved is the wall of the four encodes:
2099 ///
2100 /// | clip | wall ours before | after | instructions:u before -> after |
2101 /// |---|---|---|---|
2102 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
2103 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
2104 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
2105 ///
2106 /// Three exact steps, none of which touches a coded bit: the coefficient
2107 /// rate pricer stopped rebuilding every CDF table per candidate
2108 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
2109 /// tile once per candidate (`decode::FilterReplay`), and the forward
2110 /// transform stopped transforming the all-zero residual that 70% of its
2111 /// calls carry.
2112 ///
2113 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
2114 ///
2115 /// | step | 1080p | 2160p | screen |
2116 /// |---|---|---|---|
2117 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
2118 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
2119 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
2120 ///
2121 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
2122 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
2123 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
2124 /// -- all three decided on the REAL film rows of
2125 /// [`bd_rate_screen_native`], which this downscaled recipe does not
2126 /// carry:
2127 ///
2128 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
2129 /// |---|---|---|---|
2130 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
2131 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
2132 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
2133 ///
2134 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
2135 /// DEFAULT of the sequence path this gate codes through -- the bars are
2136 /// non-screen so they take it, the capture is gated flat:
2137 ///
2138 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
2139 /// |---|---|---|---|---|
2140 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
2141 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
2142 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
2143 ///
2144 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
2145 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
2146 /// facade arm -- which is what "one mini-GOP driver, two entry points"
2147 /// means here. This downscaled recipe HATES the pyramid (as it hates
2148 /// every knob the real film rows of `bd_rate_screen_native` keep, which
2149 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
2150 /// above. The capture's row is the flat row to the byte in both runs --
2151 /// that equality IS the content gate.
2152 ///
2153 /// Loop restoration is NOT in yet: it is the one filter whose parameters
2154 /// are per restoration UNIT inside the tile payload, so it needs both
2155 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
2156 /// buffer to solve against -- neither of which this frame-header-level
2157 /// search reaches.
2158 ///
2159 /// The baseline it replaced, before an inter frame's blocks chose their
2160 /// own partition, was +501.4/+504.4/+440.9 against libaom and
2161 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
2162 ///
2163 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
2164 /// fidelity, while spending far more time than either (the partition
2165 /// search's own cost, uncut: see the two intra-pruning variants measured
2166 /// and rejected in the lane report). No
2167 /// threshold is asserted yet -- this run sets the baseline; the gate
2168 /// asserts four monotone points per ladder, and at EVERY ladder point of
2169 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
2170 /// `crate::stream::decode_stream` -- and asserts the encoder's
2171 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
2172 /// and V over every shown frame in display order. A failure names the
2173 /// clip, the q, the frame, the plane and the first differing sample.
2174 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
2175 /// which exposes no per-packet reconstruction, so that path asserts the
2176 /// two decoders against each other on all three planes.)
2177 ///
2178 /// Run:
2179 /// cargo test -p ec-av1 --release --lib -- --ignored \
2180 /// bd_rate_vs_libaom_and_rav1e --nocapture
2181 #[test]
2182 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
2183 fn bd_rate_vs_libaom_and_rav1e() {
2184 let _knobs = crate::speed::knob_write();
2185 if !have_ffmpeg() {
2186 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
2187 return;
2188 }
2189 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
2190 let fixtures = crate::library_fixture::root();
2191 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
2192 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
2193 // rows for real content (the real rows live in the native gate).
2194 for (label, name) in [
2195 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
2196 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
2197 ] {
2198 // lane-av1clipprobe: the one probe, so a missing clip is RED under
2199 // the require envs instead of a drop-with-no-escape.
2200 if let Some(path) = crate::library_fixture::require(
2201 &format!("video/{name}"),
2202 &format!("bd_rate_vs_libaom_and_rav1e: {label}"),
2203 ) {
2204 clips.push((label.to_string(), path));
2205 }
2206 }
2207 // Screen capture: the repo carries no screen-capture fixture, so take
2208 // the first OBS recording the real-library manifest names.
2209 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
2210 Ok(manifest) => {
2211 let screen = manifest
2212 .lines()
2213 .skip(1)
2214 .filter_map(|l| l.split('\t').next())
2215 .find(|p| {
2216 p.contains("/OBS/")
2217 && p.ends_with(".mkv")
2218 && std::path::Path::new(p).exists()
2219 });
2220 match screen {
2221 Some(p) => clips.push((
2222 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
2223 std::path::PathBuf::from(p),
2224 )),
2225 None => {
2226 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
2227 }
2228 }
2229 }
2230 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
2231 }
2232 assert!(!clips.is_empty(), "no source clip available");
2233
2234 let (width, height, frames) = (640usize, 384usize, 12usize);
2235 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
2236 .iter()
2237 .map(|q| {
2238 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
2239 .map(String::from)
2240 .to_vec()
2241 })
2242 .collect();
2243 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
2244 .iter()
2245 .map(|q| {
2246 vec![
2247 "-rav1e-params".to_string(),
2248 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
2249 ]
2250 })
2251 .collect();
2252 println!(
2253 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
2254 );
2255 println!(
2256 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"
2257 );
2258 println!("|---|---|---|---|---|");
2259 for (name, path) in &clips {
2260 let fctx = &crate::decode::FrameCtx::for_encoder();
2261 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
2262 let _ = take_partition_hits();
2263 let _ = crate::tile::take_palette_hits();
2264 SCREEN_FRAMES.iter().for_each(|c| {
2265 c.store(0, std::sync::atomic::Ordering::Relaxed);
2266 });
2267 let _ = take_uv_mode_hits();
2268 let _ = crate::tile::take_inter_mode_hits();
2269 let _ = crate::tile::take_drl_hits();
2270 let _ = crate::tile::take_ref_hits();
2271 let _ = crate::tile::take_compound_mode_hits();
2272 let _ = crate::tile::take_compound_pair_hits();
2273 let _ = crate::tile::take_compound_size_hits();
2274 let _ = crate::tile::take_compound_leaf_mode_hits();
2275 let _ = take_b64_root_hits();
2276 let _ = take_b64_residual_hits();
2277 let _ = take_b64_compound_hits();
2278 let _ = crate::motion::take_census();
2279 // The entry-surface arm: run the SAME ladder through the
2280 // streaming facade the editor's export calls, which must print
2281 // the same BD numbers as the sequence path -- byte for byte the
2282 // same stream now that both drive one mini-GOP driver
2283 // (lane-av1pyrdef).
2284 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
2285 let (ours, ours_wall) = match facade {
2286 false => our_ladder(name, &source, width, height, fctx),
2287 true => {
2288 let pyramid = crate::encoder::Pyramid::from_env();
2289 let (ladder, wall, counts, bytes, effective) =
2290 our_ladder_facade(name, &source, width, height, pyramid);
2291 eprintln!(
2292 "{name}: facade, pyramid requested {pyramid:?} effective \
2293 {effective:?} -- frames key {} arf {} leaf {} \
2294 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
2295 counts[0],
2296 counts[1],
2297 counts[2],
2298 counts[3],
2299 bytes[0],
2300 bytes[1],
2301 bytes[2],
2302 bytes[3],
2303 );
2304 (ladder, wall)
2305 }
2306 };
2307 // How often the inter split actually fired over this clip's four
2308 // encodes, against the whole 32x32 that was the only outcome
2309 // before (gate-blind-to-feature).
2310 let [whole32, split32, whole16, split16] = take_partition_hits();
2311 // Which inter modes actually fired over this clip's four encodes,
2312 // and at which DRL index -- a mode nobody picks is a mode the BD
2313 // number cannot be crediting (gate-blind-to-feature).
2314 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
2315 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
2316 let refs = crate::tile::take_ref_hits();
2317 let modes_total = (nearest + near + global + new).max(1);
2318 eprintln!(
2319 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
2320 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
2321 {drl0}/{drl1}/{drl2}/{drl3}",
2322 100.0 * nearest as f64 / modes_total as f64,
2323 100.0 * near as f64 / modes_total as f64,
2324 100.0 * global as f64 / modes_total as f64,
2325 100.0 * new as f64 / modes_total as f64,
2326 );
2327 // The compound census: what share of the coded inter blocks took
2328 // a compound reference at all, which compound mode they took, and
2329 // which pair (gate-blind-to-feature -- a compound mode nobody
2330 // picks cannot be what a BD number credits).
2331 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
2332 // superblocks were left whole at all, and how many of those coded
2333 // a residual or took a compound reference.
2334 let (roots, root_res, root_comp) = (
2335 take_b64_root_hits(),
2336 take_b64_residual_hits(),
2337 take_b64_compound_hits(),
2338 );
2339 eprintln!(
2340 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
2341 );
2342 let comp_modes = crate::tile::take_compound_mode_hits();
2343 let comp_pairs = crate::tile::take_compound_pair_hits();
2344 let comp_sizes = crate::tile::take_compound_size_hits();
2345 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
2346 let comp_total: usize = comp_modes.iter().sum();
2347 eprintln!(
2348 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
2349 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
2350 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
2351 modes_total + comp_total,
2352 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
2353 comp_modes[0],
2354 comp_modes[1],
2355 comp_modes[2],
2356 comp_modes[3],
2357 comp_modes[6],
2358 comp_modes[7],
2359 comp_pairs[3],
2360 comp_pairs[6],
2361 );
2362 eprintln!(
2363 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
2364 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
2365 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], comp_leaf[7],
2366 );
2367 eprintln!(
2368 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
2369 comp_sizes[1], comp_sizes[2], comp_sizes[3],
2370 );
2371 // Where the wall-owning stage actually goes: how many candidate
2372 // evaluations (one `mc::predict` + SAD each) a search spends, how
2373 // many of them are subpel, and how often the winner is the seed
2374 // it started from -- the census the seeded search is judged by.
2375 let [
2376 calls,
2377 evals,
2378 subpel,
2379 rounds,
2380 near_pred,
2381 unmoved,
2382 widest,
2383 widest_moves,
2384 ] = crate::motion::take_census();
2385 let per = |n: u64| n as f64 / calls.max(1) as f64;
2386 eprintln!(
2387 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
2388 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
2389 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
2390 per(evals),
2391 100.0 * subpel as f64 / evals.max(1) as f64,
2392 per(rounds),
2393 100.0 * near_pred as f64 / calls.max(1) as f64,
2394 100.0 * unmoved as f64 / calls.max(1) as f64,
2395 );
2396 // lane-newmv, class `instrument at bound`: how often the winner
2397 // was walked to at the log stage's own WIDEST step -- a high
2398 // share means the search stops where its step lets it, not where
2399 // the content is.
2400 eprintln!(
2401 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
2402 100.0 * widest as f64 / calls.max(1) as f64,
2403 per(widest_moves),
2404 );
2405 eprintln!(
2406 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
2407 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
2408 );
2409 eprintln!(
2410 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
2411 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
2412 whole32 + split32,
2413 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
2414 whole16 + split16,
2415 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
2416 );
2417 // The deblocking level each of this clip's frames chose
2418 // (lane-av1filt): 0 everywhere would mean the filter never fires.
2419 let levels = crate::filter_search::take_chosen_levels();
2420 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
2421 let mean = |f: fn(&Chosen) -> u8| {
2422 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
2423 };
2424 eprintln!(
2425 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
2426 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
2427 levels.len(),
2428 mean(|l| l.0.0),
2429 mean(|l| l.0.1),
2430 mean(|l| l.1.0),
2431 mean(|l| l.1.1),
2432 mean(|l| l.2.0),
2433 mean(|l| l.2.1),
2434 );
2435 // How many strength presets each frame's CDEF list carried and
2436 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
2437 // everywhere would mean the per-unit choice never fires.
2438 let presets = crate::filter_search::take_cdef_presets();
2439 let mut by_bits = [0usize; 4];
2440 for (b, _) in &presets {
2441 by_bits[usize::from(*b)] += 1;
2442 }
2443 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
2444 let on_extra: usize = presets.iter().flat_map(|(_, c)| c.iter().skip(1)).sum();
2445 eprintln!(
2446 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
2447 on a non-default preset ({:.1}%)",
2448 by_bits[0],
2449 by_bits[1],
2450 by_bits[2],
2451 by_bits[3],
2452 on_extra,
2453 units,
2454 100.0 * on_extra as f64 / units.max(1) as f64
2455 );
2456 // How the 64x64 luma restoration units split between
2457 // RESTORE_NONE and Wiener (lane-av1lr).
2458 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
2459 eprintln!(
2460 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
2461 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
2462 );
2463 // Which chroma modes the search actually wins with, against the
2464 // unconditional DC_PRED that was the only outcome before
2465 // (gate-blind-to-feature).
2466 // Screen-content detection and the palette it turns on
2467 // (gate-blind-to-feature): how many frames set
2468 // `allow_screen_content_tools`, how many blocks took a palette,
2469 // and of what size. A film clip must print `screen frames on=0`.
2470 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
2471 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
2472 // Which tables the SEARCH priced against, per frame arming
2473 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
2474 // real starting ones. A film clip must show every inter arming on
2475 // the real side, a screen clip none of them.
2476 let (price_default, price_real) = crate::tile::take_pricing_hits();
2477 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
2478 let palette = crate::tile::take_palette_hits();
2479 eprintln!(
2480 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
2481 palette[0],
2482 (2..=8)
2483 .filter(|&n| palette[n] > 0)
2484 .map(|n| format!("{n}={}", palette[n]))
2485 .collect::<Vec<_>>()
2486 .join(" ")
2487 );
2488 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
2489 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
2490 // only ever fires at one magnitude is a search that never left
2491 // its first candidate (gate-blind-to-feature).
2492 // The luma angle-delta histogram (lane-av1cfl): how many
2493 // directional blocks won at each delta. All-zero would mean the
2494 // refinement never beat the base angle.
2495 let deltas = take_angle_delta_hits();
2496 if deltas.iter().sum::<usize>() > 0 {
2497 eprintln!(
2498 "{name}: angle_delta_y {}",
2499 deltas
2500 .iter()
2501 .enumerate()
2502 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
2503 .collect::<Vec<_>>()
2504 .join(" ")
2505 );
2506 }
2507 let alphas = take_cfl_alpha_hits();
2508 if alphas.iter().sum::<usize>() > 0 {
2509 eprintln!(
2510 "{name}: cfl |alpha| {}",
2511 alphas
2512 .iter()
2513 .enumerate()
2514 .filter(|&(_, &n)| n > 0)
2515 .map(|(a, &n)| format!("{a}={n}"))
2516 .collect::<Vec<_>>()
2517 .join(" ")
2518 );
2519 }
2520 let palette_uv = crate::tile::take_palette_uv_hits();
2521 eprintln!(
2522 "{name}: chroma palette blocks {} sizes {}",
2523 palette_uv[0],
2524 (2..=8)
2525 .filter(|&n| palette_uv[n] > 0)
2526 .map(|n| format!("{n}={}", palette_uv[n]))
2527 .collect::<Vec<_>>()
2528 .join(" ")
2529 );
2530 let uv = take_uv_mode_hits();
2531 let uv_total: usize = uv.iter().sum();
2532 eprintln!(
2533 "{name}: uv modes {}",
2534 uv.iter()
2535 .enumerate()
2536 .filter(|&(_, &n)| n > 0)
2537 .map(|(m, &n)| format!(
2538 "{}={n} ({:.1}%)",
2539 UV_MODE_NAMES[m],
2540 100.0 * n as f64 / uv_total.max(1) as f64
2541 ))
2542 .collect::<Vec<_>>()
2543 .join(" ")
2544 );
2545 // Which transform depth the intra blocks of this clip's key
2546 // frames resolved to (lane-av1tx): depth 0 is one transform over
2547 // the whole block, 1 and 2 its halvings.
2548 let depths = take_tx_depth_hits();
2549 let depth_total: usize = depths.iter().sum();
2550 eprintln!(
2551 "{name}: intra tx depths {}",
2552 depths
2553 .iter()
2554 .enumerate()
2555 .map(|(d, &n)| format!(
2556 "{d}={n} ({:.1}%)",
2557 100.0 * n as f64 / depth_total.max(1) as f64
2558 ))
2559 .collect::<Vec<_>>()
2560 .join(" ")
2561 );
2562 print_inter_tx_census(name);
2563 // lane-av1obmc: how many blocks actually CODED a motion_mode
2564 // symbol and which value they took, by footprint -- "OBMC is on"
2565 // as a measurement rather than a claim (class
2566 // `gate-blind-to-feature`).
2567 let mm = crate::tile::take_motion_mode_hits();
2568 eprintln!(
2569 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
2570 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
2571 eligible)",
2572 mm[0],
2573 mm[1],
2574 mm[2],
2575 mm[3],
2576 mm[4],
2577 mm[5],
2578 mm[6],
2579 mm[7],
2580 mm[8],
2581 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
2582 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
2583 mm.iter().sum::<usize>(),
2584 );
2585 let (aom, aom_wall) =
2586 external_ladder(&source, width, height, "libaom-av1", &aom_points);
2587 let (rav1e, rav1e_wall) =
2588 external_ladder(&source, width, height, "librav1e", &rav1e_points);
2589 assert_monotone(&format!("{name}: ours"), &ours);
2590 assert_monotone(&format!("{name}: libaom"), &aom);
2591 assert_monotone(&format!("{name}: rav1e"), &rav1e);
2592 let points = ours
2593 .iter()
2594 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2595 .collect::<Vec<_>>()
2596 .join(", ");
2597 println!(
2598 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
2599 bd_rate(&aom, &ours) * 100.0,
2600 bd_rate(&rav1e, &ours) * 100.0,
2601 );
2602 println!(
2603 "| references | libaom {} | rav1e {} | | |",
2604 aom.iter()
2605 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2606 .collect::<Vec<_>>()
2607 .join(", "),
2608 rav1e
2609 .iter()
2610 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
2611 .collect::<Vec<_>>()
2612 .join(", "),
2613 );
2614 }
2615 assert_ladder_decodes();
2616 }
2617 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
2618 /// split by block class in lane-av1txdepth): depth 0 is one transform over
2619 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
2620 /// leaves and the 32x32 root, each single-reference or compound. A class
2621 /// with no counts at all never reached `commit_inter_luma` -- which is
2622 /// what its knob being off looks like (class `gate-blind-to-feature`).
2623 pub(super) fn print_inter_tx_census(name: &str) {
2624 let splits = take_inter_tx_split_hits();
2625 let total: usize = splits.iter().sum();
2626 let row = |label: &str, base: usize| {
2627 let (n0, n1) = (splits[base], splits[base + 1]);
2628 format!(
2629 "{label} 0={n0} 1={n1} ({:.1}% split)",
2630 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
2631 )
2632 };
2633 eprintln!(
2634 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
2635 row("leaf single", 0),
2636 row("leaf compound", 2),
2637 row("32x32 single", 4),
2638 row("32x32 compound", 6),
2639 );
2640 // lane-txrd: which types the two searches actually COMMITTED over
2641 // this row's four encodes -- the gate could not say whether a type
2642 // search fired at all (class `gate-blind-to-feature`).
2643 const NAMES: [&str; 16] = [
2644 "IDTX",
2645 "DCT_DCT",
2646 "ADST_ADST",
2647 "ADST_DCT",
2648 "DCT_ADST",
2649 "V_DCT",
2650 "H_DCT",
2651 "FLIPADST_DCT",
2652 "DCT_FLIPADST",
2653 "FLIPADST_FLIPADST",
2654 "ADST_FLIPADST",
2655 "FLIPADST_ADST",
2656 "V_ADST",
2657 "H_ADST",
2658 "V_FLIPADST",
2659 "H_FLIPADST",
2660 ];
2661 let name_of = |t: usize| NAMES[t];
2662 for (label, hits) in [
2663 ("inter", take_inter_tx_type_hits()),
2664 ("intra", take_tx_type_hits()),
2665 ] {
2666 let total: usize = hits.iter().sum();
2667 let live: Vec<String> = hits
2668 .iter()
2669 .enumerate()
2670 .filter(|&(_, &n)| n > 0)
2671 .map(|(t, &n)| {
2672 format!(
2673 "{}={n} ({:.1}%)",
2674 name_of(t),
2675 100.0 * n as f64 / total.max(1) as f64
2676 )
2677 })
2678 .collect();
2679 eprintln!(
2680 "{name}: {label} tx_type of {total} units -- {}",
2681 live.join(" ")
2682 );
2683 }
2684 let t = take_txrd_stats();
2685 if t[0] > 0 {
2686 eprintln!(
2687 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
2688 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
2689 t[0],
2690 t[1],
2691 t[3] as f64 / 64.0,
2692 t[2],
2693 t[4] as f64 / 64.0,
2694 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
2695 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
2696 );
2697 eprintln!(
2698 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
2699 flat: dsse {:+.2}%, dbits {:+.2}%)",
2700 t[5],
2701 t[6] as f64 / 64.0,
2702 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
2703 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
2704 );
2705 }
2706 }
2707
2708 /// The video stream's coded size, from ffprobe.
2709 pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> {
2710 crate::probe::dims(clip)
2711 }
2712
2713 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
2714 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
2715 /// superblock-aligned one, still centred and still even for 4:2:0.
2716 ///
2717 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
2718 /// superblocks by design, so no default gate row has a block the frame
2719 /// edge cuts through -- while every arbitrary export size does (3840x1608
2720 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
2721 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
2722 /// read on.
2723 pub(super) fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
2724 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
2725 let (w, h) = spec
2726 .split_once('x')
2727 .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
2728 let (cw, ch): (usize, usize) = (
2729 w.parse().expect("crop width"),
2730 h.parse().expect("crop height"),
2731 );
2732 let (nw, nh) = crate::probe::dims(clip)?;
2733 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
2734 let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
2735 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
2736 }
2737
2738 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
2739 /// with `probe_screen_detect` so the detector sweep measures exactly the
2740 /// clips the keep table is read off. Selector env vars as documented on
2741 /// the gate; a missing clip prints a SKIP and drops its row.
2742 pub(super) fn native_gate_clips() -> Vec<(String, String, String)> {
2743 // lane-av1clipprobe: the crate's one fixture root (EC_FIXTURES first).
2744 let fixtures = crate::library_fixture::root();
2745 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
2746 let (film, film4k, screen) = (
2747 on("EC_AV1_NATIVE_FILM"),
2748 on("EC_AV1_NATIVE_FILM4K"),
2749 on("EC_AV1_NATIVE_SCREEN"),
2750 );
2751 // No selector at all means every clip; any selector means that subset.
2752 let all = !(film || film4k || screen);
2753 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
2754 // not film -- they print as "bars" so no reader takes them for real
2755 // content -- and the two rows below them are the real AV1 films.
2756 let mut clips: Vec<(String, String, String)> = Vec::new();
2757 for (want, label, file) in [
2758 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
2759 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
2760 ] {
2761 if !want {
2762 continue;
2763 }
2764 // lane-av1clipprobe: the one probe, so a missing clip is RED under
2765 // the require envs instead of a dropped row with no escape.
2766 if let Some(path) = crate::library_fixture::require(
2767 &format!("video/{file}"),
2768 &format!("the native BD-rate gate: {label}"),
2769 ) {
2770 clips.push((
2771 label.to_string(),
2772 path.to_str().unwrap().to_string(),
2773 "0".into(),
2774 ));
2775 }
2776 }
2777 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
2778 // The real films, taken out of the real-library manifest by codec and
2779 // coded width so no title and no home path lives in this file. Each
2780 // seek is PINNED (class `seeded fixture not reproducible`) at a
2781 // moving, non-black window -- a black leader would make every arm
2782 // read +0.000 (class `flat sample window`). Both sources are 10-bit
2783 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
2784 // what all three encoders see, so the comparison stays
2785 // encoder-vs-encoder.
2786 let pick = |width: &str| -> Option<String> {
2787 let m = manifest.as_ref().ok()?;
2788 m.lines()
2789 .skip(1)
2790 .map(|l| l.split('\t').collect::<Vec<_>>())
2791 .find(|f| {
2792 f.len() > 4
2793 && f[2] == "av1"
2794 && f[3] == width
2795 && std::path::Path::new(f[0]).exists()
2796 })
2797 .map(|f| f[0].to_string())
2798 };
2799 for (want, label, width, seek) in [
2800 (all || film, "film A (1080p source)", "1920", "00:35:00"),
2801 (
2802 all || film4k,
2803 "film B (2160p HDR source)",
2804 "3840",
2805 "00:40:00",
2806 ),
2807 ] {
2808 if !want {
2809 continue;
2810 }
2811 match pick(width) {
2812 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
2813 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
2814 }
2815 }
2816 if all || screen {
2817 match &manifest {
2818 Ok(manifest) => match manifest
2819 .lines()
2820 .skip(1)
2821 .filter_map(|l| l.split('\t').next())
2822 .find(|p| {
2823 p.contains("/OBS/")
2824 && p.ends_with(".mkv")
2825 && std::path::Path::new(p).exists()
2826 }) {
2827 Some(p) => clips.push((
2828 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
2829 p.to_string(),
2830 "0".into(),
2831 )),
2832 None => {
2833 eprintln!("SKIP screen capture: no OBS recording in the manifest exists")
2834 }
2835 },
2836 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
2837 }
2838 }
2839 clips
2840 }
2841
2842 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
2843 /// downscales the OBS capture to 640x384, which destroys exactly the
2844 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
2845 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
2846 /// on that recipe is taken on content the tool cannot serve. This arm
2847 /// crops -- never scales -- a superblock-aligned window out of the middle
2848 /// of the capture at its own resolution (at most 1920x1024, so the wall
2849 /// stays in the minutes) and runs the same 12-frame, four-quantizer
2850 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
2851 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
2852 /// sample-exactness assertion `our_ladder` makes.
2853 ///
2854 /// It is its own `--ignored` test so the default gate's wall does not
2855 /// grow. Every variant is an environment knob, and each of those is a
2856 /// `OnceLock` read once per process, so a variant is a separate run:
2857 ///
2858 /// cargo test -p ec-av1 --release --lib -- --ignored \
2859 /// bd_rate_screen_native --nocapture # baseline
2860 /// EC_AV1_INTRABC=1 ... same command # intra block copy
2861 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
2862 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
2863 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
2864 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
2865 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
2866 ///
2867 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
2868 /// through (lane-av1pyrdef); the run prints the requested and the
2869 /// effective pyramid per clip, and a screen clip's effective one is
2870 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
2871 /// streaming facade instead, which prints the per-level frame and byte
2872 /// census and asserts ffmpeg's decode against our own decoder on all
2873 /// three planes in display order; both arms code the same bytes
2874 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
2875 ///
2876 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
2877 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
2878 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
2879 /// cost -- so every "film" column in the historical tables of this file
2880 /// is that generator, not film. The real content is `film A`, `film B`
2881 /// (native crops out of the two AV1 films the real-library manifest
2882 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
2883 /// decision only the bars rows support is not supported.
2884 ///
2885 /// Measured 2026-09-07, the five rows before and after the screen
2886 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
2887 /// BOTH real films were classified as screen content on 48/48 frames, so
2888 /// their coefficients were priced against the DEFAULT CDFs and the
2889 /// palette search ran over film; after, both are non-screen (0/48) and
2890 /// the capture is unchanged at 48/48:
2891 ///
2892 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
2893 /// |---|---|---|---|
2894 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
2895 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
2896 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
2897 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
2898 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
2899 ///
2900 /// Both bars rows and the capture are byte-identical across that change
2901 /// (their classification never moved); the palette search over film was
2902 /// costing roughly a tenth of the film rows' wall.
2903 ///
2904 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
2905 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
2906 /// the capture is gated flat and does not move a byte:
2907 ///
2908 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
2909 /// |---|---|---|---|---|
2910 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
2911 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
2912 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
2913 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
2914 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
2915 ///
2916 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
2917 /// which is the point of the shared driver: the two entry points code one
2918 /// stream. The bars rows are fixtures (recorded, never a decision); the
2919 /// two real films are what the pyramid ships for.
2920 ///
2921 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
2922 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
2923 /// setting any one of them keeps only the selected rows (the two 1080p
2924 /// rows, the two 2160p rows, the capture row respectively). A missing
2925 /// real film SKIPs its row; it never fails the gate.
2926 #[test]
2927 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
2928 fn bd_rate_screen_native() {
2929 let _knobs = crate::speed::knob_read();
2930 native_bd_arm("bd_rate_screen_native", 12, false);
2931 }
2932
2933 /// The LONG-GOP arm of the native BD gate: the same recipe as
2934 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
2935 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
2936 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
2937 /// reaches libaom as `--kf-max-dist=48` and rav1e as
2938 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
2939 /// inter pictures.
2940 ///
2941 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
2942 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
2943 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
2944 /// above 12 codes the same stream there -- the shipped `16` was measured
2945 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
2946 /// group (class `instrument at bound` / `gate blind to feature`). The
2947 /// user's exports are long GOPs, so the pyramid shape is decided here.
2948 ///
2949 /// cargo test -p ec-av1 --release --lib -- --ignored \
2950 /// bd_rate_film_long_gop --nocapture
2951 ///
2952 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
2953 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
2954 /// Read every row off the log's own "pyramid requested/effective" print,
2955 /// never off the argument order of the runs (lane-pyr3 misattributed
2956 /// three rows that way).
2957 ///
2958 /// Table: `lanes/pyr4.sweep.txt`.
2959 #[test]
2960 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
2961 fn bd_rate_film_long_gop() {
2962 let _knobs = crate::speed::knob_write();
2963 native_bd_arm("bd_rate_film_long_gop", 48, true);
2964 }
2965
2966 /// The shared driver of the two native BD arms above: `frames` pictures
2967 /// per row (the sequence's `gop` is the same number, so one key frame),
2968 /// four quantizers, `films_only` dropping every row but the two real
2969 /// films.
2970 pub(super) fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
2971 if !have_ffmpeg() {
2972 eprintln!("SKIP {label}: no ffmpeg");
2973 return;
2974 }
2975 let mut clips = native_gate_clips();
2976 if films_only {
2977 clips.retain(|(name, _, _)| name.starts_with("film "));
2978 }
2979 if clips.is_empty() {
2980 eprintln!("SKIP {label}: no clip");
2981 return;
2982 }
2983
2984 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
2985 .iter()
2986 .map(|q| {
2987 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
2988 .map(String::from)
2989 .to_vec()
2990 })
2991 .collect();
2992 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
2993 .iter()
2994 .map(|q| {
2995 vec![
2996 "-rav1e-params".to_string(),
2997 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
2998 ]
2999 })
3000 .collect();
3001 println!(
3002 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
3003 intrabc {}, palette maxcolors {}",
3004 armed_tiles(),
3005 crate::par::tile_threads(),
3006 intrabc_enabled(),
3007 palette_max_colors(),
3008 );
3009 println!(
3010 "| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"
3011 );
3012 println!("|---|---|---|---|---|");
3013 for (name, path, seek) in &clips {
3014 let fctx = &crate::decode::FrameCtx::for_encoder();
3015 if probe_dims(path).is_none() {
3016 eprintln!("SKIP {name}: ffprobe gave no size");
3017 continue;
3018 }
3019 // A whole number of 128-wide superblocks, at most 1920x1024, out
3020 // of the middle of the frame; the offsets stay even for 4:2:0.
3021 // ONE definition, shared with `examples/enc_probe` so the probe
3022 // cannot measure a different window than this gate (lane-probe).
3023 let (vf, cw, ch) = match native_crop_override(path) {
3024 Some(over) => over,
3025 None => crate::probe::gate_crop(path),
3026 };
3027 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
3028 SCREEN_FRAMES.iter().for_each(|c| {
3029 c.store(0, std::sync::atomic::Ordering::Relaxed);
3030 });
3031 let _ = crate::tile::take_palette_hits();
3032 let _ = crate::tile::take_palette_uv_hits();
3033 let _ = crate::tile::take_intrabc_hits();
3034 let _ = take_intrabc_search();
3035 let _ = crate::tile::take_filter_intra_hits();
3036 let _ = take_edge_census();
3037 // The sequence path itself codes the pyramid now
3038 // (lane-av1pyrdef), and prints what it requested and what the
3039 // content gate left effective.
3040 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
3041 // lane-sse: the blocks the true frame edge cuts through, and how
3042 // much of their RAW squared error sat in the padding the encoder
3043 // invented past it -- what the inside-only score stopped ranking
3044 // on. Empty on a superblock-aligned crop, which is every default
3045 // gate row (class `gate-blind-to-feature`).
3046 if edge_census() {
3047 for (side, n, inside, padding) in take_edge_census() {
3048 eprintln!(
3049 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
3050 padding_sse={padding} ({:.1}% of raw)",
3051 100.0 * padding as f64 / (inside + padding).max(1) as f64,
3052 );
3053 }
3054 }
3055 // gate-blind-to-feature: what the screen tools actually did at
3056 // native resolution, over this clip's four encodes.
3057 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
3058 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
3059 // Which tables the SEARCH priced against, per frame arming
3060 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
3061 // real starting ones. A film clip must show every inter arming on
3062 // the real side, a screen clip none of them.
3063 let (price_default, price_real) = crate::tile::take_pricing_hits();
3064 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
3065 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
3066 // superblocks stayed whole, and how many of those coded a
3067 // residual, split that residual's luma, or took a compound
3068 // reference (class `gate-blind-to-feature`).
3069 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
3070 // the superblocks offered the trial were coded whole.
3071 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
3072 eprintln!(
3073 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
3074 {i64_edge} on a superblock the frame edge cuts",
3075 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
3076 );
3077 eprintln!(
3078 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
3079 {} (search) / {} (writer); rect/AB pieces with a residual \
3080 {} (search) / {} (writer)",
3081 take_b128_none_hits(),
3082 crate::tile::take_sb128_none_hits(),
3083 take_b128_residual_hits(),
3084 crate::tile::take_sb128_residual_hits(),
3085 take_b128_rectres_hits(),
3086 crate::tile::take_sb128_rectres_hits(),
3087 );
3088 eprintln!(
3089 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
3090 take_b64_root_hits(),
3091 take_b64_residual_hits(),
3092 take_b64_var_tx_hits(),
3093 take_b64_compound_hits(),
3094 );
3095 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
3096 // of every priced block): what the deadzone quantiser handed the
3097 // RDOQ pass and what the pass changed, over every TRIAL block of
3098 // this row's four encodes -- not over the coded stream, so it is
3099 // the bits AT STAKE in the search, not in the bitstream.
3100 let rq = crate::tile::take_rdoq_stats();
3101 if rq[0] > 0 {
3102 eprintln!(
3103 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
3104 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
3105 rq[0],
3106 rq[1],
3107 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
3108 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
3109 rq[4],
3110 rq[5],
3111 rq[7] as f64 / 64.0,
3112 rq[6] as f64 / 64.0,
3113 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
3114 );
3115 }
3116 // lane-av1obmc2: the same motion_mode census the 640x384 gate
3117 // prints (class `gate-blind-to-feature`) -- how many blocks coded
3118 // the symbol at each footprint and how many took OBMC. Without it
3119 // the native table, which is the standing keep table, could not
3120 // say whether the tool fired at all.
3121 let mm = crate::tile::take_motion_mode_hits();
3122 eprintln!(
3123 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
3124 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
3125 eligible)",
3126 mm[0],
3127 mm[1],
3128 mm[2],
3129 mm[3],
3130 mm[4],
3131 mm[5],
3132 mm[6],
3133 mm[7],
3134 mm[8],
3135 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
3136 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
3137 mm.iter().sum::<usize>(),
3138 );
3139 print_inter_tx_census(name);
3140 // lane-last2 (class `gate-blind-to-feature`): which reference the
3141 // 32x32-and-below inter blocks of this clip's four encodes chose.
3142 // The native table is the standing keep table, so a second past
3143 // reference that never won a block has to be visible HERE and not
3144 // only in a synthetic witness.
3145 let rh = crate::encode::take_ref_frame_hits();
3146 let rtot: usize = rh.iter().sum();
3147 eprintln!(
3148 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
3149 (LAST2 {:.1}%)",
3150 rh[1],
3151 rh[2],
3152 rh[4],
3153 rh[7],
3154 rtot,
3155 100.0 * rh[2] as f64 / rtot.max(1) as f64,
3156 );
3157 let palette = crate::tile::take_palette_hits();
3158 let palette_uv = crate::tile::take_palette_uv_hits();
3159 let ibc = crate::tile::take_intrabc_hits();
3160 let search = take_intrabc_search();
3161 eprintln!(
3162 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
3163 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
3164 won {})",
3165 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
3166 palette[0],
3167 palette_uv[0],
3168 ibc[0],
3169 search[0],
3170 search[1],
3171 search[2],
3172 );
3173 // gate-blind-to-feature: how often the five recursive filter-intra
3174 // modes actually won a block over this clip's four encodes -- a
3175 // tool that never fires is not measured by the row above it.
3176 let fi = crate::tile::take_filter_intra_hits();
3177 eprintln!(
3178 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
3179 filter_intra_on(),
3180 fi[0],
3181 fi[1],
3182 fi[2],
3183 fi[3],
3184 fi[4],
3185 fi[5],
3186 );
3187 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
3188 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
3189 assert_monotone(&format!("{name}: ours"), &ours);
3190 assert_monotone(&format!("{name}: libaom"), &aom);
3191 assert_monotone(&format!("{name}: rav1e"), &rav1e);
3192 let points = ours
3193 .iter()
3194 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
3195 .collect::<Vec<_>>()
3196 .join(", ");
3197 println!(
3198 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
3199 bd_rate(&aom, &ours) * 100.0,
3200 bd_rate(&rav1e, &ours) * 100.0,
3201 );
3202 // lane-pareto2: the two references at THEIR fast presets, plus
3203 // SVT-AV1, measured in the SAME arm as the row above -- the only
3204 // way the wall column of a Pareto table means anything (class:
3205 // wall tables are comparable only inside one interleaved batch).
3206 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
3207 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
3208 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
3209 [50, 100, 150, 200]
3210 .iter()
3211 .map(|q| {
3212 vec![
3213 "-rav1e-params".to_string(),
3214 format!(
3215 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
3216 ),
3217 ]
3218 })
3219 .collect()
3220 };
3221 let aom_at = |cu: u32| -> Vec<Vec<String>> {
3222 [5, 20, 35, 45]
3223 .iter()
3224 .map(|q| {
3225 vec![
3226 "-cpu-used".to_string(),
3227 cu.to_string(),
3228 "-b:v".to_string(),
3229 "0".to_string(),
3230 "-crf".to_string(),
3231 q.to_string(),
3232 ]
3233 })
3234 .collect()
3235 };
3236 let svt_at = |pr: u32| -> Vec<Vec<String>> {
3237 [20, 35, 45, 55]
3238 .iter()
3239 .map(|q| {
3240 vec![
3241 "-preset".to_string(),
3242 pr.to_string(),
3243 "-crf".to_string(),
3244 q.to_string(),
3245 "-svtav1-params".to_string(),
3246 "lp=1".to_string(),
3247 ]
3248 })
3249 .collect()
3250 };
3251 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
3252 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
3253 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
3254 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
3255 ];
3256 if have_encoder("libsvtav1") {
3257 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
3258 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
3259 } else {
3260 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
3261 }
3262 for (label, encoder, points) in arms {
3263 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
3264 // A REFERENCE stream our decoder cannot read is a note in
3265 // this table, not a gate failure: these rows exist to
3266 // price the references, and `assert_ladder_decodes` keeps
3267 // its teeth for the two ladders the keep table is read off.
3268 let notes =
3269 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
3270 if !notes.is_empty() {
3271 eprintln!(
3272 "{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)",
3273 notes.len()
3274 );
3275 }
3276 assert_monotone(&format!("{name}: {label}"), &lad);
3277 println!(
3278 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
3279 bd_rate(&aom, &lad) * 100.0,
3280 bd_rate(&rav1e, &lad) * 100.0,
3281 );
3282 }
3283 }
3284 }
3285 assert_ladder_decodes();
3286 }
3287
3288 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
3289 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
3290 /// on the two film clips at their native gate crop. The 2160p clip loses
3291 /// at every arm of the propagating map and the named suspect was that its
3292 /// heavily filtered flat cells give a tiny denominator, so the dependence
3293 /// ratio explodes exactly where coding is cheap; this prints the numbers
3294 /// that confirm or refute it.
3295 #[test]
3296 // Reads ONLY `fixtures/video/h264-{1080p,2160p}-23.976-8bit.mp4` -- the
3297 // COLOUR-BARS fixtures, in a centred crop. It never opens a film, so the
3298 // old reason ("the film fixtures") sent readers looking for content the
3299 // test cannot read. 0.9 s; prints the per-cell intra-MAD distribution.
3300 #[ignore = "0.9 s; reads only the fixtures/video COLOUR-BARS clips (not the films) and prints the per-cell intra-MAD distribution"]
3301 pub(super) fn tpl_intra_denominator_histogram() {
3302 let _knobs = crate::speed::knob_read();
3303 if !have_ffmpeg() {
3304 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
3305 return;
3306 }
3307 for (label, file) in [
3308 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
3309 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
3310 ] {
3311 // lane-av1clipprobe: the one probe, so a missing clip is RED under
3312 // the require envs. With both clips absent this histogram used to
3313 // loop zero times and pass having printed nothing.
3314 let Some(path) = crate::library_fixture::require(
3315 &format!("video/{file}"),
3316 &format!("tpl_intra_denominator_histogram: {label}"),
3317 ) else {
3318 continue;
3319 };
3320 let path = path.to_str().unwrap();
3321 let Some((nw, nh)) = probe_dims(path) else {
3322 eprintln!("SKIP {label}: ffprobe gave no size");
3323 continue;
3324 };
3325 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
3326 let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
3327 let source = clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
3328 let mut costs: Vec<f64> = Vec::new();
3329 for pic in &source {
3330 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
3331 costs.extend(
3332 super::tpl_intra_costs(&y8, cw, ch)
3333 .iter()
3334 .map(|&c| f64::from(c)),
3335 );
3336 }
3337 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
3338 let mut sorted = costs.clone();
3339 sorted.sort_by(f64::total_cmp);
3340 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
3341 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
3342 eprintln!(
3343 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
3344 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
3345 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
3346 below 1.0x {} ({:.1}%)",
3347 costs.len(),
3348 q(0.0),
3349 q(0.01),
3350 q(0.05),
3351 q(0.25),
3352 q(0.50),
3353 q(0.75),
3354 q(0.99),
3355 q(1.0),
3356 below(0.25),
3357 100.0 * below(0.25) as f64 / costs.len() as f64,
3358 below(0.5),
3359 100.0 * below(0.5) as f64 / costs.len() as f64,
3360 below(1.0),
3361 100.0 * below(1.0) as f64 / costs.len() as f64,
3362 );
3363 }
3364 }
3365
3366 /// The probe arms the gate's source (lane-probe, class `instrument
3367 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
3368 /// command line and had no `-ss`, so it read film B from frame 0 -- a
3369 /// black leader -- and coded 59 kB where the gate's own ladder point
3370 /// coded 89 kB of the same title; every census taken through it was
3371 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
3372 /// the shared loader honours the seek (arming the probe's way and the
3373 /// gate's way gives byte-identical streams, and dropping the seek does
3374 /// not), on a synthetic clip whose content moves over time.
3375 #[test]
3376 fn the_probe_arms_the_gates_source() {
3377 let _knobs = crate::speed::knob_write();
3378 if !have_ffmpeg() {
3379 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
3380 return;
3381 }
3382 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
3383 std::fs::create_dir_all(&dir).unwrap();
3384 let clip = dir.join("testsrc2.y4m");
3385 // 384x202: neither side is a multiple of 128, so the gate's centre
3386 // window is a real derivation and not the frame itself -- exactly the
3387 // shape film B has (3840x1608, never 3840x2160).
3388 let ok = Command::new("ffmpeg")
3389 .args([
3390 "-v",
3391 "error",
3392 "-y",
3393 "-f",
3394 "lavfi",
3395 "-i",
3396 "testsrc2=size=384x202:rate=10",
3397 ])
3398 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
3399 .arg(&clip)
3400 .status()
3401 .expect("ffmpeg failed to run")
3402 .success();
3403 assert!(ok, "ffmpeg could not write the synthetic clip");
3404 let path = clip.to_str().unwrap();
3405
3406 // The window: superblock-aligned, centred, even offsets.
3407 let (vf, w, h) = crate::probe::gate_crop(path);
3408 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
3409
3410 let (seek, q) = ("00:00:01", 150u8);
3411 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
3412 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
3413 assert!(
3414 gate.iter()
3415 .zip(&probe)
3416 .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
3417 "the probe's source differs from the gate's at the same window"
3418 );
3419 let bytes = |src: &[Picture]| {
3420 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
3421 .unwrap()
3422 .stream
3423 };
3424 assert_eq!(
3425 bytes(&gate),
3426 bytes(&probe),
3427 "probe and gate code different bytes"
3428 );
3429 // The two witnesses that both halves of the arming reach ffmpeg: the
3430 // seek, and the crop's own offset (the film-B defect in miniature --
3431 // the probe was reading `crop=..:568` of a 1608-high frame).
3432 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
3433 assert_ne!(
3434 bytes(&gate),
3435 bytes(&unseeked),
3436 "seeked and unseeked arming coded the same bytes -- the seek is inert"
3437 );
3438 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
3439 assert_ne!(
3440 bytes(&gate),
3441 bytes(&offset),
3442 "centred and top-aligned windows coded the same bytes -- the crop is inert"
3443 );
3444 std::fs::remove_dir_all(&dir).ok();
3445 }
3446
3447 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
3448 /// point inside the test binary, to compare against `examples/enc_probe`.
3449 #[test]
3450 // Panics on the first `env::var(...).unwrap()` when unset -- it needs FIVE
3451 // variables, not "a clip": `EC_PARITY_DIMS`, `EC_PARITY_FRAMES`,
3452 // `EC_PARITY_Q`, `EC_PARITY_CLIP`, `EC_PARITY_SS`, `EC_PARITY_VF`. Prints
3453 // one PARITY line (bytes + fnv1a of the stream) to diff against
3454 // `examples/enc_probe`.
3455 #[ignore = "diagnostic: needs EC_PARITY_{DIMS,FRAMES,Q,CLIP,SS,VF} -- all five, it unwraps the first missing one; prints one PARITY hash line"]
3456 pub(super) fn probe_parity_point() {
3457 let _knobs = crate::speed::knob_write();
3458 let g = |k: &str| std::env::var(k).unwrap();
3459 let (w, h) = g("EC_PARITY_DIMS")
3460 .split_once(':')
3461 .map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap()))
3462 .unwrap();
3463 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
3464 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
3465 let source = clip_frames_vf(
3466 &g("EC_PARITY_CLIP"),
3467 &g("EC_PARITY_SS"),
3468 &g("EC_PARITY_VF"),
3469 w,
3470 h,
3471 frames,
3472 );
3473 let fctx = &crate::decode::FrameCtx::for_encoder();
3474 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
3475 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
3476 for &b in &e.stream {
3477 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
3478 }
3479 eprintln!(
3480 "PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
3481 e.stream.len(),
3482 crate::speed::speed(),
3483 crate::encoder::Pyramid::from_env(),
3484 last_sequence_pyramid()
3485 );
3486 }
3487 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
3488 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
3489 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
3490 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
3491 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
3492 /// the census's far row measures were already banked by `arf_altref`.
3493 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
3494 /// best-of-two SAD shares are read against the fire share the gate census
3495 /// prints (`references ... LAST2 n (n%)`) and the refutation in
3496 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
3497 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
3498 /// `LAST`, the backward `ALTREF`, and the rate term price in.
3499 ///
3500 /// The measurement is on the gate's own window and loader (`gate_crop`,
3501 /// 12 pictures) of the two real films: every 16x16 luma block of every
3502 /// picture gets one full-pel diamond search against the NEAR reference
3503 /// and the same search against the FAR one, at the two lags the pyramid
3504 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
3505 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
3506 /// reference wins at all and by more than 10%, and -- the number the
3507 /// decision is taken on -- the total SAD of best-of-{near, far} against
3508 /// the total SAD of near alone, which is the prediction energy a second
3509 /// reference could remove before any rate is paid for naming it.
3510 ///
3511 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
3512 #[test]
3513 #[ignore = "reads the real films"]
3514 fn last2_census() {
3515 if !have_ffmpeg() {
3516 eprintln!("SKIP last2_census: no ffmpeg");
3517 return;
3518 }
3519 const SIDE: usize = 16;
3520 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
3521 // `None` when the displaced block leaves the picture.
3522 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
3523 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
3524 if sy < 0 || sx < 0 {
3525 return None;
3526 }
3527 let (sy, sx) = (sy as usize, sx as usize);
3528 if sy + SIDE > r.height || sx + SIDE > r.width {
3529 return None;
3530 }
3531 let mut acc = 0u64;
3532 for row in 0..SIDE {
3533 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
3534 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
3535 acc += c
3536 .iter()
3537 .zip(p)
3538 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
3539 .sum::<u64>();
3540 }
3541 Some(acc)
3542 };
3543 // A log-step diamond from the zero motion vector: the cheapest search
3544 // that still finds real pans. Both references get exactly this one,
3545 // so the comparison is search-fair.
3546 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
3547 let mut best = (
3548 sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX),
3549 (0isize, 0isize),
3550 );
3551 let mut step = 16isize;
3552 while step >= 1 {
3553 let centre = best.1;
3554 for (dy, dx) in [
3555 (-1, -1),
3556 (-1, 0),
3557 (-1, 1),
3558 (0, -1),
3559 (0, 1),
3560 (1, -1),
3561 (1, 0),
3562 (1, 1),
3563 ] {
3564 let mv = (centre.0 + dy * step, centre.1 + dx * step);
3565 if let Some(s) = sad(cur, r, bx, by, mv)
3566 && s < best.0
3567 {
3568 best = (s, mv);
3569 }
3570 }
3571 step /= 2;
3572 }
3573 best.0
3574 };
3575 println!(
3576 "| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"
3577 );
3578 println!("|---|---|---|---|---|---|---|---|");
3579 for (name, path, seek) in native_gate_clips() {
3580 if !name.starts_with("film ") {
3581 continue;
3582 }
3583 let (vf, cw, ch) = crate::probe::gate_crop(&path);
3584 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
3585 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
3586 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
3587 let (mut near_sad, mut best_sad) = (0u64, 0u64);
3588 for i in far..pictures.len() {
3589 let cur = &pictures[i];
3590 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
3591 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
3592 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
3593 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
3594 blocks += 1;
3595 wins += u64::from(f < n);
3596 big += u64::from(f as f64 * 1.1 < n as f64);
3597 near_sad += n;
3598 best_sad += n.min(f);
3599 }
3600 }
3601 }
3602 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
3603 println!(
3604 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
3605 pct(wins),
3606 pct(big),
3607 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
3608 );
3609 }
3610 }
3611 }
3612
3613 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
3614 /// temporal filter of its SOURCE would take off it, priced before any
3615 /// encoder change (class `gate-blind-to-feature`).
3616 ///
3617 /// The stream census says our top ARF costs 6992 B a frame against
3618 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
3619 /// quality, and that 61% of the gap is residual, not syntax. Two
3620 /// explanations are separable here without an encoder: our anchor
3621 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
3622 /// the residual it codes at that lag is dominated by film grain, which no
3623 /// motion search can predict (source noise). So, per ARF position of the
3624 /// gate's own 48-picture window:
3625 ///
3626 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
3627 /// * the same at lag 8 with the CURRENT picture temporally filtered --
3628 /// a libaom-shaped motion-compensated average of the +-2 display
3629 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
3630 /// energy an ARF temporal filter would remove, and
3631 /// * PSNR of that filtered picture against the unfiltered one, the
3632 /// CEILING the filtered ARF's own PSNR is then measured under (the
3633 /// BD gate scores against the unfiltered source).
3634 ///
3635 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
3636 /// --ignored arf_pred_census --nocapture
3637 #[test]
3638 #[ignore = "reads the real films"]
3639 fn arf_pred_census() {
3640 if !have_ffmpeg() {
3641 eprintln!("SKIP arf_pred_census: no ffmpeg");
3642 return;
3643 }
3644 const SIDE: usize = 16;
3645 let strength: f64 = std::env::var("EC_ARF_TF_S")
3646 .ok()
3647 .and_then(|v| v.parse().ok())
3648 .unwrap_or(30.0);
3649 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
3650 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
3651 // when the displaced block leaves the picture.
3652 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
3653 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
3654 if sy < 0 || sx < 0 {
3655 return None;
3656 }
3657 let (sy, sx) = (sy as usize, sx as usize);
3658 if sy + SIDE > r.height || sx + SIDE > r.width {
3659 return None;
3660 }
3661 let mut acc = 0u64;
3662 for row in 0..SIDE {
3663 let c = &cur[row * cw..][..SIDE];
3664 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
3665 acc += c
3666 .iter()
3667 .zip(p)
3668 .map(|(&a, &b)| u64::from(a.abs_diff(b)))
3669 .sum::<u64>();
3670 }
3671 Some((acc, (sy, sx)))
3672 };
3673 // The same log-step diamond `last2_census` uses, so the two censuses'
3674 // SADs are comparable.
3675 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
3676 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
3677 Some(v) => v,
3678 None => return (u64::MAX, (by, bx)),
3679 };
3680 let mut centre = (0isize, 0isize);
3681 let mut step = 16isize;
3682 while step >= 1 {
3683 let from = centre;
3684 for (dy, dx) in [
3685 (-1, -1),
3686 (-1, 0),
3687 (-1, 1),
3688 (0, -1),
3689 (0, 1),
3690 (1, -1),
3691 (1, 0),
3692 (1, 1),
3693 ] {
3694 let mv = (from.0 + dy * step, from.1 + dx * step);
3695 if let Some(s) = at(cur, cw, r, bx, by, mv)
3696 && s.0 < best.0
3697 {
3698 best = s;
3699 centre = mv;
3700 }
3701 }
3702 step /= 2;
3703 }
3704 best
3705 };
3706 println!(
3707 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
3708 );
3709 println!("|---|---|---|---|---|---|---|");
3710 for (name, path, seek) in native_gate_clips() {
3711 if !name.starts_with("film ") {
3712 continue;
3713 }
3714 let (vf, cw, ch) = crate::probe::gate_crop(&path);
3715 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
3716 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
3717 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
3718 for i in (8..pictures.len()).step_by(8) {
3719 arfs += 1;
3720 let cur = &pictures[i];
3721 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
3722 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
3723 let block: Vec<u16> = (0..SIDE)
3724 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
3725 .collect();
3726 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
3727 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
3728 // The temporal filter: each +-2 display neighbour is
3729 // motion-compensated onto this block and averaged in
3730 // with libaom's shape, a weight that falls with the
3731 // match's own mean squared error.
3732 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
3733 let mut wsum = 1.0f64;
3734 // `EC_ARF_TF_PAST=1` restricts the filter to the
3735 // DISPLAY-PAST neighbours -- the only ones the
3736 // encoder's own group buffer holds when it codes its
3737 // top ARF (the group's future is not buffered yet).
3738 let offs: &[isize] = match past {
3739 true => &[-2, -1],
3740 false => &[-2, -1, 1, 2],
3741 };
3742 for &d in offs {
3743 let j = i as isize + d;
3744 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
3745 else {
3746 continue;
3747 };
3748 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
3749 let mut sse = 0f64;
3750 for row in 0..SIDE {
3751 for col in 0..SIDE {
3752 let d = f64::from(block[row * SIDE + col])
3753 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
3754 sse += d * d;
3755 }
3756 }
3757 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
3758 for row in 0..SIDE {
3759 for col in 0..SIDE {
3760 acc[row * SIDE + col] +=
3761 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
3762 }
3763 }
3764 wsum += w;
3765 }
3766 let filtered: Vec<u16> = acc
3767 .iter()
3768 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
3769 .collect();
3770 for (a, b) in filtered.iter().zip(&block) {
3771 let d = f64::from(*a) - f64::from(*b);
3772 tf_sse += d * d;
3773 }
3774 tf_px += (SIDE * SIDE) as u64;
3775 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
3776 px += (SIDE * SIDE) as u64;
3777 }
3778 }
3779 }
3780 let per = |v: u64| v as f64 / px.max(1) as f64;
3781 let mse = tf_sse / tf_px.max(1) as f64;
3782 println!(
3783 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
3784 per(n8),
3785 per(n4),
3786 per(ntf),
3787 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
3788 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
3789 );
3790 }
3791 }
3792
3793 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
3794 /// hardwire the REGULAR kernel, so the encoder could not have coded a
3795 /// SMOOTH or SHARP frame even if the header had said so -- the search,
3796 /// the trials, the recon and the frame header now all read
3797 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
3798 /// distinct stream (a filter that never reached the prediction would code
3799 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
3800 /// reconstructs every frame of each of them exactly, which is what proves
3801 /// the header and the prediction agree.
3802 #[test]
3803 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
3804 let _knobs = crate::speed::knob_write();
3805 if !have_ffmpeg() {
3806 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
3807 return;
3808 }
3809 let (width, height) = (256usize, 128usize);
3810 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
3811 // all three kernels would code the same bytes and the test would pass
3812 // on a wiring that does nothing (class `fixture proves the symbol, not
3813 // the signal`). `panned_test_card` shifts by whole pixels, so the
3814 // search finds the sub-pel positions off the reconstruction instead:
3815 // three frames of a slow diagonal pan.
3816 let pictures: Vec<Picture> = (0..3)
3817 .map(|i| panned_test_card(width, height, i * 3))
3818 .collect();
3819 let mut streams = Vec::new();
3820 for filter in [
3821 ec_av1_syntax::InterpolationFilter::Eighttap,
3822 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
3823 ec_av1_syntax::InterpolationFilter::EighttapSharp,
3824 ] {
3825 set_frame_interp(Some(filter));
3826 let fctx = &crate::decode::FrameCtx::for_encoder();
3827 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
3828 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
3829 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3830 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
3831 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
3832 assert_eq!(
3833 decoded.y, frame.reconstruction.y,
3834 "{filter:?} frame {i}: luma"
3835 );
3836 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
3837 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
3838 }
3839 streams.push((filter, encoded.stream));
3840 }
3841 set_frame_interp(None);
3842 for (i, (fa, a)) in streams.iter().enumerate() {
3843 for (fb, b) in &streams[i + 1..] {
3844 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
3845 }
3846 }
3847 }
3848
3849 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
3850 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
3851 /// residual outright (`round_to_valid_mv` rounds it away first), so the
3852 /// finest vector the encoder could commit to was a quarter pel. With the
3853 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
3854 /// non-zero component and the search's fourth stage refines to the
3855 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
3856 /// on arm, and -- the part that makes it a signal rather than a symbol
3857 /// count (class `fixture proves the symbol, not the signal`) -- that some
3858 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
3859 /// all. Both streams are decoded by ffmpeg AND by this crate's own
3860 /// decoder and asserted sample-exact against the encoder's own
3861 /// reconstruction, which is what proves the header bit and the symbols
3862 /// agree.
3863 #[test]
3864 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
3865 let _knobs = crate::speed::knob_write();
3866 if !have_ffmpeg() {
3867 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
3868 return;
3869 }
3870 let (width, height) = (256usize, 128usize);
3871 let pictures: Vec<Picture> = (0..3)
3872 .map(|i| panned_test_card(width, height, i * 3))
3873 .collect();
3874 let mut arms = Vec::new();
3875 for hp in [false, true] {
3876 set_high_precision_mv(Some(hp));
3877 let _ = crate::tile::take_hp_symbols();
3878 let fctx = &crate::decode::FrameCtx::for_encoder();
3879 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
3880 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
3881 let (symbols, eighth) = crate::tile::take_hp_symbols();
3882 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
3883 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
3884 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
3885 assert_eq!(
3886 ours.len(),
3887 pictures.len(),
3888 "hp={hp}: our decoder frame count"
3889 );
3890 for (i, e) in encoded.frames.iter().enumerate() {
3891 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
3892 if let Some((plane, s, got, want)) =
3893 first_plane_mismatch(got, &e.reconstruction)
3894 {
3895 panic!(
3896 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
3897 the encoder reconstructed {want}"
3898 );
3899 }
3900 }
3901 }
3902 arms.push((symbols, eighth, encoded.stream));
3903 }
3904 set_high_precision_mv(None);
3905 let (off, on) = (&arms[0], &arms[1]);
3906 assert_eq!(
3907 off.0, 0,
3908 "a frame without the header bit codes no hp symbol"
3909 );
3910 assert!(
3911 on.0 > 0,
3912 "a high-precision frame codes hp symbols (got {})",
3913 on.0
3914 );
3915 assert!(
3916 on.1 > 0,
3917 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
3918 on.0
3919 );
3920 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
3921 println!(
3922 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
3923 off.0,
3924 off.2.len(),
3925 on.0,
3926 on.1,
3927 on.2.len()
3928 );
3929 }