forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

more_tests.rs1260 lines, 61.5 KiBHistoryRawDownload
1use super::*;
2use super::tests::*;
3
4
5
6 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
7 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
8 /// Five passes over the same `testsrc2` clip
9 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
10 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
11 /// context and every visit order the shape reads is exercised rather than
12 /// the handful the RD would pick, and then an UNFORCED pass whose
13 /// per-shape count is REPORTED (it is the number the gate rows are read
14 /// against).
15 ///
16 /// Each pass is sample-exact against the encoder's own reconstruction
17 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
18 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19 /// before this lane by construction: `write_sb128_root` could only name
20 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
21 ///
22 /// Runs only inside `superblock_size_global_suite`.
23 pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
24 let _knobs = crate::speed::knob_write();
25 force_sb128(true);
26 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
27 std::fs::create_dir_all(&dir).unwrap();
28 let clip = dir.join("testsrc2-1280x768.y4m");
29 let ok = ec_testkit::ffmpeg()
30 .args(["-v", "error", "-y", "-f", "lavfi"])
31 .args(["-i", "testsrc2=size=1280x768:rate=24"])
32 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
33 .arg(&clip)
34 .status()
35 .expect("ffmpeg failed to run")
36 .success();
37 assert!(ok, "ffmpeg could not write the synthetic clip");
38 let (width, height) = (1280usize, 768usize);
39 let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
40 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
41 let mut unforced = [0usize; 4];
42 for force in [4u8, 5, 6, 7, 0] {
43 force_b128_ab(force);
44 let label = if force == 0 {
45 "unforced"
46 } else {
47 names[usize::from(force) - 4]
48 };
49 let _ = take_b128_ab_hits();
50 let _ = crate::tile::take_sb128_ab_hits();
51 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
52 let won = take_b128_ab_hits();
53 let coded = crate::tile::take_sb128_ab_hits();
54 eprintln!(
55 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
56 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
57 );
58 if force == 0 {
59 // The unforced counts are REPORTED, not asserted: a zero here
60 // would be an RD result, not a defect (the four forced passes
61 // already prove the writer and the reader agree on the shape).
62 unforced = won;
63 } else {
64 let i = usize::from(force) - 4;
65 assert!(
66 coded[i] > 0,
67 "no {label} root was coded with {label} forced"
68 );
69 }
70 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
71 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
72 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
73 for (plane, got, want) in [
74 ("luma", &dec.y, &frame.reconstruction.y),
75 ("U", &dec.u, &frame.reconstruction.u),
76 ("V", &dec.v, &frame.reconstruction.v),
77 ] {
78 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
79 assert_eq!(
80 differ, 0,
81 "{label} frame {i}: {plane} -- {differ} samples differ"
82 );
83 assert_eq!(
84 got.len(),
85 want.len(),
86 "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
87 got.len(),
88 want.len()
89 );
90 }
91 }
92 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
93 assert_eq!(
94 encoded.frames.len(),
95 ff.len(),
96 "{label}: frame count: ours vs ffmpeg"
97 );
98 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
99 assert_eq!(
100 dec.y, frame.reconstruction.y,
101 "{label} frame {i}: ffmpeg luma"
102 );
103 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
104 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
105 }
106 }
107 force_b128_ab(0);
108 eprintln!(
109 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
110 unforced[0], unforced[1], unforced[2], unforced[3],
111 );
112 }
113
114 #[test]
115 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
116 let _knobs = crate::speed::knob_read();
117 let fctx = &crate::decode::FrameCtx::for_encoder();
118 // 256x128, not the 128x64 this started at: once a leaf could search
119 // its second reference (lane-av1comp4) the small card's every
120 // eligible block went to a compound winner, which commits its flat
121 // transform, and the split below stopped firing on content that
122 // still splits at every larger size ([[gate-blind-to-feature]] --
123 // the guard is right, the fixture had shrunk under it).
124 let (width, height) = (256usize, 128usize);
125 let pictures: Vec<Picture> = (0..5)
126 .map(|i| panned_test_card(width, height, i * 3))
127 .collect();
128 let _ = take_inter_tx_split_hits();
129 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
130 let raw = take_inter_tx_split_hits();
131 // Summed over the four block classes the census keys on (leaf/32x32 x
132 // single/compound): this assert is about the split firing at all.
133 let split = [
134 raw.iter().step_by(2).sum::<usize>(),
135 raw.iter().skip(1).step_by(2).sum::<usize>(),
136 ];
137 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
138 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
139 // content splits -- a green round trip in which the split never fires
140 // would prove only the flat path.
141 if tx_select() && tx_select_inter() {
142 assert!(split[1] > 0, "the inter var-tx split never fired");
143 }
144 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
145 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
146 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
147 let recon = &frame.reconstruction;
148 for (plane, got, want, stride) in [
149 ("luma", &dec.y, &recon.y, width),
150 ("U", &dec.u, &recon.u, width / 2),
151 ("V", &dec.v, &recon.v, width / 2),
152 ] {
153 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
154 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
155 panic!(
156 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
157 reconstruction {} ({} of {} samples differ)",
158 at % stride,
159 at / stride,
160 got[at],
161 want[at],
162 got.iter().zip(want).filter(|(a, b)| a != b).count(),
163 got.len(),
164 );
165 }
166 }
167 }
168 }
169
170 /// The rate term the mode search ranks every decision by has to be the
171 /// rate the writer then spends. The search prices a block's coefficients
172 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
173 /// against the default CDFs a tile starts from and the contexts of a
174 /// block whose neighbours coded nothing -- while the tile writer codes
175 /// them against a state that has been adapting all frame (the
176 /// price-the-narrowing class). This measures that drift: the sum of what
177 /// the search paid for the coefficients it kept, against the bytes the
178 /// writer actually emitted for the whole tile (which also carries the
179 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
180 /// expected to be the larger of the two).
181 #[test]
182 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
183 let _knobs = crate::speed::knob_read();
184 let fctx = &crate::decode::FrameCtx::for_encoder();
185 let (width, height) = (256usize, 128usize);
186 let pictures: Vec<Picture> = (0..5)
187 .map(|i| panned_test_card(width, height, i * 2))
188 .collect();
189 let _ = take_predicted_bits();
190 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
191 let predicted = take_predicted_bits();
192 assert_eq!(predicted.len(), encoded.frames.len());
193
194 eprintln!("frame predicted bits written bits drift");
195 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
196 // defect this gate exists to catch), a positive one is the written
197 // side carrying syntax the coefficient sum leaves out -- and since
198 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
199 // on that side, so the two directions no longer share a bound.
200 let mut worst_over: f64 = 0.0;
201 let mut worst_under: f64 = 0.0;
202 // The census is per CODED frame, so it is zipped in coding order --
203 // which is not display order under a pyramid.
204 let coded: Vec<&Encoded> = encoded
205 .coding_order
206 .iter()
207 .map(|&i| &encoded.frames[i])
208 .collect();
209 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
210 let written = frame.tile.len() as f64 * 8.0;
211 let drift = (written - bits) / written;
212 worst_over = worst_over.max(-drift);
213 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
214 // all (150-250 bits of tile, nearly all of it partition/mode/mv
215 // syntax the coefficient sum never counts), so its ratio measures
216 // that floor rather than any drift. Frames under 512 written bits
217 // are left out of the under-price bound for that reason; the
218 // over-price bound -- the defect direction, where the search pays
219 // MORE than the writer -- still covers every frame.
220 if written >= 512.0 {
221 worst_under = worst_under.max(drift);
222 }
223 eprintln!(
224 "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
225 drift * 100.0
226 );
227 }
228 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
229 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
230 // over-prices every frame but the last (its sum EXCLUDES the
231 // partition/mode/skip/mv syntax the written side carries, so the true
232 // coefficient over-price is larger still): the writer's CDFs adapt to
233 // the content while the search's stay at the defaults. The bound is
234 // set just above the worst measured point -- a widening drift is the
235 // thing this gate exists to catch.
236 assert!(
237 worst_over <= 0.16,
238 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
239 worst_over * 100.0
240 );
241 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
242 // the worst inter frame, where nearly every block now codes an MV
243 // residual and a reference the coefficient sum never counts. Re-measured
244 // at +29.6% once the encoder's grid published compound blocks properly
245 // (compound share 8.8% -> 11.5%): a compound block carries a second
246 // reference tree, a compound mode symbol and -- for the half-new modes
247 // -- an MV residual, none of which the coefficient sum counts.
248 // lane-av1txbits: pricing against the tables the frame's writer really
249 // starts from collapses the over-price above to nothing, so the whole
250 // remaining gap is the syntax the coefficient sum leaves out. That is
251 // the default on a non-screen frame since lane-av1price2 (this
252 // fixture is one), and it reads +32.6% here.
253 // lane-av1obmc: every eligible single-reference inter block now also
254 // carries a `motion_mode` symbol the coefficient sum never counts,
255 // and an OBMC block carries the more expensive of the two values --
256 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
257 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
258 // decisions, so this bound and the byte pins above FAIL BY DESIGN
259 // under it; the default path (no motion_mode syntax at all) is the
260 // one they are measured on.
261 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
262 // coding pyramid now, so the five frames are a key frame, a hidden
263 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
264 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
265 // near-empty leaves below it. Both bounds stand where they were.
266 // lane-av1rejudge: local warp is ON by default now, so every eligible
267 // single-reference block carries that same `motion_mode` symbol (a
268 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
269 // +34.9% here, one point past the OBMC reading above. The bound moves
270 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
271 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
272 // symbol and one or two magnitude symbols, none of which the
273 // coefficient sum counts either -- +36.9% here against the same
274 // fixture's +34.9% with `EC_AV1_CFL=0`.
275 // ... and a directional block whose `angle_delta_y` is no longer
276 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
277 assert!(
278 worst_under <= 0.40,
279 "the writer spent {:.2}% more than the search priced -- more than \
280 the mode/mv syntax outside the coefficient sum explains",
281 worst_under * 100.0
282 );
283 }
284
285 /// The census behind step (1) of the pricer lane: for every transform
286 /// block the writer really codes, what the search priced those levels at
287 /// against what the writer spent on them, split by table set and non-zero
288 /// count. One average hides the interesting part -- the classes the
289 /// estimate is systematically wrong about (all-zero blocks, the
290 /// one-coefficient blocks the inter search lives on) -- so the split is
291 /// printed and only the total is asserted on.
292 #[test]
293 fn pricer_error_census_by_block_class() {
294 let _knobs = crate::speed::knob_read();
295 let fctx = &crate::decode::FrameCtx::for_encoder();
296 let (width, height) = (256usize, 128usize);
297 let pictures: Vec<Picture> = (0..5)
298 .map(|i| panned_test_card(width, height, i * 2))
299 .collect();
300 crate::tile::pricer_census_on();
301 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
302 let rows = crate::tile::take_pricer_census();
303 assert!(!rows.is_empty(), "the census saw no transform block");
304
305 println!("| set | nz | blocks | priced bits | written bits | error |");
306 println!("|---|---|---|---|---|---|");
307 let (mut priced_all, mut written_all) = (0.0, 0.0);
308 for ((set, bucket), (blocks, priced, written)) in &rows {
309 priced_all += priced;
310 written_all += written;
311 println!(
312 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
313 crate::tile::census_bucket_label(*bucket),
314 if *written > 0.0 {
315 (priced - written) / written * 100.0
316 } else {
317 0.0
318 }
319 );
320 }
321 println!(
322 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
323 rows.values().map(|r| r.0).sum::<u64>(),
324 (priced_all - written_all) / written_all * 100.0
325 );
326 assert!(written_all > 0.0);
327 }
328
329 /// Low motion has to actually buy something: at least one inter frame of
330 /// a panning sequence has to cost fewer bytes than the key frame that
331 /// starts it, and the inter-block share it prints has to be non-zero --
332 /// a search that never picks an inter mode would still pass a rate gate
333 /// on a picture with no motion in it (the class this repo calls
334 /// gate-blind-to-feature), so the share is printed even though it is not
335 /// asserted on beyond being reachable at all.
336 #[test]
337 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
338 let _knobs = crate::speed::knob_read();
339 let fctx = &crate::decode::FrameCtx::for_encoder();
340 let (width, height) = (256usize, 128usize);
341 let pictures: Vec<Picture> = (0..5)
342 .map(|i| panned_test_card(width, height, i * 2))
343 .collect();
344 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
345
346 let key_bytes = encoded.frames[0].stream.len();
347 eprintln!("frame bytes inter share");
348 for (i, frame) in encoded.frames.iter().enumerate() {
349 eprintln!(
350 "{i:5} {:5} {:11.2}",
351 frame.stream.len(),
352 frame.inter_block_share
353 );
354 }
355 assert!(
356 encoded.frames[1..]
357 .iter()
358 .any(|f| f.stream.len() < key_bytes),
359 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
360 );
361 assert!(
362 encoded.frames[1..]
363 .iter()
364 .any(|f| f.inter_block_share > 0.0),
365 "no inter frame coded a single inter block -- the search never fired"
366 );
367 }
368
369 /// `frames` consecutive pictures out of a real clip, scaled to a whole
370 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
371 /// to an arbitrary count for the fixture regression gate below.
372 pub(super) fn clip_frames(
373 clip: &str,
374 skip: &str,
375 width: usize,
376 height: usize,
377 frames: usize,
378 ) -> Vec<Picture> {
379 clip_frames_vf(
380 clip,
381 skip,
382 &format!("scale={width}:{height}"),
383 width,
384 height,
385 frames,
386 )
387 }
388
389 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
390 /// for a native-resolution CROP instead of a downscale (the downscale is
391 /// what destroys a screen capture's exact repeats -- class
392 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
393 pub(super) fn clip_frames_vf(
394 clip: &str,
395 skip: &str,
396 vf: &str,
397 width: usize,
398 height: usize,
399 frames: usize,
400 ) -> Vec<Picture> {
401 // ONE definition of the gate's loader recipe, shared with
402 // `examples/enc_probe` so the instrument cannot arm a different source
403 // than the gate it reports on (class `instrument disagrees with the
404 // gate`; lane-probe).
405 crate::probe::source(clip, skip, vf, width, height, frames)
406 }
407
408 // -----------------------------------------------------------------------
409 // The encoder's standing BD-rate baseline against libaom and rav1e.
410 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
411 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
412 // agreeing with our encoder proves nothing about the bitstream.
413 // -----------------------------------------------------------------------
414
415 /// All-plane PSNR of a decoded picture against its source, on the same
416 /// 8-bit scale [`psnr`] uses.
417 pub(super) fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
418 let cat = |p: &Picture| {
419 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
420 v.extend_from_slice(&p.y);
421 v.extend_from_slice(&p.u);
422 v.extend_from_slice(&p.v);
423 v
424 };
425 psnr(&cat(decoded), &cat(source))
426 }
427
428 /// The pictures back as the planar 8-bit bytes an encoder reads.
429 pub(super) fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
430 let mut raw = Vec::new();
431 for p in source {
432 for plane in [&p.y, &p.u, &p.v] {
433 raw.extend(plane.iter().map(|&s| s as u8));
434 }
435 }
436 raw
437 }
438
439 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
440 /// through ffmpeg: one point per entry of `points`, each a quality flag
441 /// set. Returns the ladder ordered by fidelity and the total encode wall
442 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
443 /// so both curves are measured by the same decoder.
444 pub(super) fn external_ladder(
445 source: &[Picture],
446 width: usize,
447 height: usize,
448 encoder: &str,
449 points: &[Vec<String>],
450 ) -> (Vec<(f64, f64)>, f64) {
451 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
452 let dir = std::env::temp_dir();
453 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
454 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
455 let mut ladder = Vec::new();
456 let mut wall = 0.0;
457 for (i, params) in points.iter().enumerate() {
458 let obu = dir.join(format!(
459 "ec-av1-bd-{}-{encoder}-{i}.obu",
460 std::process::id()
461 ));
462 let start = std::time::Instant::now();
463 let out = ec_testkit::ffmpeg()
464 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
465 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
466 .arg(&raw_path)
467 .args(["-an", "-threads", "1"])
468 .args(["-g", &source.len().to_string(), "-c:v", encoder])
469 .args(params)
470 .args(["-f", "obu"])
471 .arg(&obu).output()
472 .expect("ffmpeg failed to run");
473 wall += start.elapsed().as_secs_f64();
474 assert!(
475 out.status.success(),
476 "{encoder} {params:?}: {}",
477 String::from_utf8_lossy(&out.stderr)
478 );
479 let stream = std::fs::read(&obu).expect("reference stream");
480 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
481 // lane-dkey: every reference point must also decode through OUR
482 // decoder, sample-exact against ffmpeg's decode of the same bytes.
483 // A BD table computed off streams we cannot read is a table about
484 // an encoder we cannot check; this is the assertion that would
485 // have caught the `force_integer_mv` defect (its stream decoded to
486 // 25 dB garbage while this gate stayed green) and the crf-5 key
487 // frame desync. A failure names the encoder, the point's flags and
488 // the first differing frame/plane/sample.
489 // lane-dpm1: a failing reference point is COLLECTED, not panicked
490 // on, so one run still prints the whole BD table and names every
491 // bad point instead of stopping at the first. The collection is
492 // asserted empty by [`assert_ladder_decodes`] at the end of each
493 // gate.
494 match crate::stream::decode_stream(&stream) {
495 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
496 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
497 ours.len(),
498 decoded.len(),
499 )),
500 Ok(ours) => {
501 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
502 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
503 note_ladder_failure(format!(
504 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
505 decoder decoded {got}, ffmpeg {want}"
506 ));
507 break;
508 }
509 }
510 }
511 Err(e) => note_ladder_failure(format!(
512 "{encoder} {params:?}: our decoder refused the stream ({e})"
513 )),
514 }
515 let mean: f64 = decoded
516 .iter()
517 .zip(source)
518 .map(|(d, s)| psnr_all(d, s))
519 .sum::<f64>()
520 / source.len() as f64;
521 ladder.push((mean, (stream.len() as f64).log10()));
522 let _ = std::fs::remove_file(&obu);
523 }
524 let _ = std::fs::remove_file(&raw_path);
525 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
526 (ladder, wall)
527 }
528
529 /// Every reference ladder point that did not decode sample-exactly
530 /// through our own decoder, collected across a whole gate run so the BD
531 /// table still prints and EVERY bad point is named
532 /// (`encoder params frame plane sample`) instead of only the first.
533 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
534
535 pub(super) fn note_ladder_failure(msg: String) {
536 eprintln!("LADDER DECODE FAILURE: {msg}");
537 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
538 }
539
540 /// Fail the gate at its END on everything [`external_ladder`] collected.
541 pub(super) fn assert_ladder_decodes() {
542 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
543 assert!(
544 failures.is_empty(),
545 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
546 failures.len(),
547 failures.join("\n"),
548 );
549 }
550
551 /// First differing sample between two pictures, as
552 /// `(plane, index, left, right)` -- so a gate failure names the plane and
553 /// the sample instead of just "differs". A length difference counts as a
554 /// mismatch of that plane at the first index past the shorter one.
555 pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
556 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
557 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
558 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
559 }
560 if l.len() != r.len() {
561 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
562 }
563 }
564 None
565 }
566
567 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
568 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
569 /// stream is decoded twice -- by ffmpeg and by our own
570 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
571 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
572 /// in Y, U and V over every shown frame in display order. That is itself
573 /// a gate: it proves the bitstream says what the encoder thinks, in the
574 /// only two decoders that read it.
575 pub(super) fn our_ladder(
576 name: &str,
577 source: &[Picture],
578 width: usize,
579 height: usize,
580 fctx: &crate::decode::FrameCtx,
581 ) -> (Vec<(f64, f64)>, f64) {
582 let mut ladder = Vec::new();
583 let mut wall = 0.0;
584 for &q in &[150u8, 120, 90, 60] {
585 let start = std::time::Instant::now();
586 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
587 // the gate has to be able to re-sweep it. 0.5 is the shipped one
588 // (`crate::encoder::DEADZONE`).
589 let deadzone = std::env::var("EC_AV1_DEADZONE")
590 .ok()
591 .and_then(|v| v.parse().ok())
592 .unwrap_or(0.5);
593 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
594 wall += start.elapsed().as_secs_f64();
595 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
596 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
597 assert_eq!(
598 ours.len(),
599 source.len(),
600 "{name} q={q}: our decoder's display-order frame count"
601 );
602 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
603 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
604 panic!(
605 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
606 {got}, the encoder reconstructed {want}"
607 );
608 }
609 }
610 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
611 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
612 panic!(
613 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
614 {got}, the encoder reconstructed {want}"
615 );
616 }
617 }
618 let per_frame: Vec<f64> = decoded
619 .iter()
620 .zip(source)
621 .map(|(d, s)| psnr_all(d, s))
622 .collect();
623 // lane-txrd: does a tool's loss start at the FIRST inter frame
624 // (a local mispricing) or grow down the GOP (propagation into
625 // the reference chain)? One line per q point answers it.
626 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
627 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
628 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
629 // lane-txrd: per PLANE, because an all-plane mean hides a
630 // collapse in one of them (class `metric blind to a plane`).
631 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
632 let v: Vec<String> = decoded
633 .iter()
634 .zip(source)
635 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
636 .collect();
637 v.join(" ")
638 };
639 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
640 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
641 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
642 }
643 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
644 ladder.push((mean, (encoded.stream.len() as f64).log10()));
645 }
646 // What this clip asked for and what the content gate left it coding
647 // under: a screen clip requests a pyramid and codes flat, and that
648 // difference is what keeps its row identical to the flat baseline
649 // (class `gate-blind-to-feature`).
650 eprintln!(
651 "{name}: sequence, pyramid requested {:?} effective {:?}",
652 crate::encoder::Pyramid::from_env(),
653 last_sequence_pyramid(),
654 );
655 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
656 (ladder, wall)
657 }
658
659 /// [`our_ladder`] through the streaming facade — the surface the editor's
660 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
661 /// each stream is also reordered (hidden `ALTREF` first,
662 /// `show_existing_frame` last per group) and each level is coded at its
663 /// own quantizer offset; without one it is the flat ladder, which
664 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
665 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
666 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
667 /// the whole ladder how many frames and how many bytes it spent, and the
668 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
669 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
670 /// flat path, so a requested pyramid can come back `None` here.
671 pub(super) fn our_ladder_facade(
672 name: &str,
673 source: &[Picture],
674 width: usize,
675 height: usize,
676 pyramid: Option<crate::encoder::Pyramid>,
677 ) -> (
678 Vec<(f64, f64)>,
679 f64,
680 [usize; 4],
681 [usize; 4],
682 Option<crate::encoder::Pyramid>,
683 ) {
684 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
685 let slot = |l: Level| match l {
686 Level::Key => 0,
687 Level::Arf => 1,
688 Level::Leaf => 2,
689 Level::ShowExisting => 3,
690 };
691 let mut ladder = Vec::new();
692 let mut wall = 0.0;
693 let mut effective = None;
694 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
695 for &q in &[150u8, 120, 90, 60] {
696 let config = EncoderConfig {
697 width,
698 height,
699 base_q_idx: q,
700 gop: source.len(),
701 colour: Colour::Unspecified,
702 tile_cols_log2: 0,
703 tile_rows_log2: 0,
704 };
705 let start = std::time::Instant::now();
706 let mut enc = match pyramid {
707 None => Av1Encoder::new(config).unwrap(),
708 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
709 };
710 let mut packets = Vec::new();
711 for picture in source {
712 packets.extend(enc.encode_frames(picture).unwrap());
713 }
714 packets.extend(enc.flush().unwrap());
715 wall += start.elapsed().as_secs_f64();
716 effective = enc.pyramid();
717 let mut stream = Vec::new();
718 for p in &packets {
719 counts[slot(p.level)] += 1;
720 bytes[slot(p.level)] += p.data.len();
721 stream.extend_from_slice(&p.data);
722 }
723 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
724 // correct if the DISPLAY-order output still has one frame per
725 // source picture, in the right order -- checked against our own
726 // decoder as well as ffmpeg's, both below.
727 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
728 assert_eq!(
729 ours.len(),
730 source.len(),
731 "{name} q={q}: our display-order count"
732 );
733 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
734 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
735 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
736 panic!(
737 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
738 decoded {got}, our decoder decoded {want}"
739 );
740 }
741 }
742 let mean: f64 = decoded
743 .iter()
744 .zip(source)
745 .map(|(d, s)| psnr_all(d, s))
746 .sum::<f64>()
747 / source.len() as f64;
748 ladder.push((mean, (stream.len() as f64).log10()));
749 }
750 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
751 (ladder, wall, counts, bytes, effective)
752 }
753
754 /// Byte-exactness gate for encoder work that is meant to change only
755 /// how long the encoder takes.
756 ///
757 /// The BD gate above measures quality, which a speed lane can move by a
758 /// hair without failing anything; this pins the streams themselves.
759 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
760 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
761 /// in the tile) and again on lane-av1mv's merge of it: an extra
762 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
763 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
764 /// prices coefficients against the tables the frame's writer really
765 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
766 /// decision change the BD gate judges. Re-pinned again on
767 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
768 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
769 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
770 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
771 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
772 /// by default ([`warp_on`], a sequence/frame header bit and a new
773 /// motion_mode symbol on eligible blocks) and
774 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
775 /// every inter frame's superblocks now code at their own lambda
776 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
777 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
778 /// and the two var-tx depth searches ([`tx32_depth_search`],
779 /// [`compound_var_tx`]) are on by default, all three re-judged on the
780 /// native gate's real film rows.
781 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
782 /// every block whose chroma takes it codes a different mode symbol, two
783 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
784 /// restores the previous streams. Re-pinned again in the same lane once
785 /// directional luma winners searched their `angle_delta_y`
786 /// (`EC_AV1_ANGLE=0` restores that half).
787 #[test]
788 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
789 // These are DEFAULT-PRESET pins: a speed preset switches search levers
790 // off, so it legitimately moves every byte. Encode at speed 0 whatever
791 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
792 let _knobs = crate::speed::knob_write();
793 let was = crate::speed::speed();
794 crate::speed::set_speed(0);
795 // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
796 // so a tree with no root `fixtures/` reported this gate green having
797 // compared nothing at all.
798 let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
799 let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4);
800 // FNV-1a over the stream: a witness that every coded bit is where it
801 // was, which a byte count alone is not.
802 let fnv = |b: &[u8]| {
803 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
804 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
805 })
806 };
807 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
808 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
809 // of 4, its leaves at q+8 and a `show_existing_frame` header per
810 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
811 // four frames; four pictures is one short mini-GOP, which is the
812 // shape that pays least (the ARF's own quality has no later group to
813 // carry it), so this is not the BD gate's number.
814 // Re-taken again on lane-av1cfl: the chroma search offers
815 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
816 // so every block taking either codes different syntax and different
817 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
818 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
819 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
820 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
821 // so these four pictures code as one truncated group -- a hidden
822 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
823 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
824 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
825 // Re-taken on lane-fintra: the sequence header sets
826 // `enable_filter_intra`, so every DC_PRED intra block of at most
827 // 32x32 without a luma palette carries a `use_filter_intra` flag and
828 // the blocks that take one code a filter-intra mode, a different
829 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
830 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
831 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
832 // (default pyramid `8:-32:16`, one truncated group of 8 with its
833 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
834 // root can code a REAL residual now (one TX_64X64 luma transform and
835 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
836 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
837 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
838 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
839 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
840 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
841 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
842 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
843 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
844 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
845 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
846 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
847 // these four pictures -- offers every superblock a 64x64 intra root
848 // now. `EC_AV1_I64=0` restores 8557 / 33345.
849 // Re-taken on lane-pricer: the inter RD search prices a single
850 // reference through the tree and the neighbour contexts the writer
851 // really codes it with, so every inter picture's reference decisions
852 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
853 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
854 // for `skip`/`is_inter` and for the whole compound reference tree, so
855 // every inter block's cost -- and with it the skip and reference
856 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
857 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
858 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
859 // single and compound are priced against the same syntax -- 8311 ->
860 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
861 // Re-taken on lane-newmv: the motion search charges its own rate term
862 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
863 // and each subpel stage re-runs from its own winner
864 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
865 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
866 // and 33014 -> 33090 at q=60.
867 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
868 // from libaom's objective tpl mapping, so every inter picture's
869 // quantizer grid -- and every decision priced against it -- moved
870 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
871 // at the merge of both lanes.
872 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
873 // per-superblock `delta_qindex` at 1.5x the preset's strength
874 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
875 // grids -- and every decision priced against them -- moved:
876 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
877 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
878 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
879 // pixels -- and the leaves that predict from them -- moved:
880 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
881 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
882 // the shipped stream did not move.
883 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
884 // picture is coded in 128x128 superblocks now, the inter ones
885 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
886 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
887 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
888 // by default, on top of the ARF temporal filter).
889 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
890 // candidates the 64 root already did ([`b128_compound`]), so every
891 // inter frame that carries `reference_select` codes different blocks
892 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
893 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
894 // Re-taken on lane-arftf: that filter's strength swept on the deciding
895 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
896 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
897 // 33017 at q=60 (the same LENGTH, different bytes).
898 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
899 // lane-rlclamp onto the 128 compound default.
900 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
901 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
902 // so every inter frame whose RD takes one codes a different partition
903 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
904 // quantizer the rect cut never wins its own comparison on this clip.
905 // `EC_AV1_B128HV=0` restores 8290 exactly.
906 let pins: [(u8, usize, u64); 2] = [
907 (150, 23666, 11535713837929557386),
908 (60, 102035, 3886390906684528357),
909 ];
910 let coded: Vec<(u8, usize, u64)> = pins
911 .iter()
912 .map(|&(q, _, _)| {
913 let e = encode_sequence(&source, q, 0.5).unwrap();
914 (q, e.stream.len(), fnv(&e.stream))
915 })
916 .collect();
917 crate::speed::set_speed(was);
918 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
919 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
920 }
921 }
922
923 /// A ladder is only a ladder if both axes rise together.
924 pub(super) fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
925 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
926 for w in ladder.windows(2) {
927 assert!(
928 w[1].0 > w[0].0 && w[1].1 > w[0].1,
929 "{name}: not monotone, {ladder:?}"
930 );
931 }
932 }
933
934 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
935 /// split by block class in lane-av1txdepth): depth 0 is one transform over
936 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
937 /// leaves and the 32x32 root, each single-reference or compound. A class
938 /// with no counts at all never reached `commit_inter_luma` -- which is
939 /// what its knob being off looks like (class `gate-blind-to-feature`).
940 pub(super) fn print_inter_tx_census(name: &str) {
941 let splits = take_inter_tx_split_hits();
942 let total: usize = splits.iter().sum();
943 let row = |label: &str, base: usize| {
944 let (n0, n1) = (splits[base], splits[base + 1]);
945 format!(
946 "{label} 0={n0} 1={n1} ({:.1}% split)",
947 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
948 )
949 };
950 eprintln!(
951 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
952 row("leaf single", 0),
953 row("leaf compound", 2),
954 row("32x32 single", 4),
955 row("32x32 compound", 6),
956 );
957 // lane-txrd: which types the two searches actually COMMITTED over
958 // this row's four encodes -- the gate could not say whether a type
959 // search fired at all (class `gate-blind-to-feature`).
960 const NAMES: [&str; 16] = [
961 "IDTX",
962 "DCT_DCT",
963 "ADST_ADST",
964 "ADST_DCT",
965 "DCT_ADST",
966 "V_DCT",
967 "H_DCT",
968 "FLIPADST_DCT",
969 "DCT_FLIPADST",
970 "FLIPADST_FLIPADST",
971 "ADST_FLIPADST",
972 "FLIPADST_ADST",
973 "V_ADST",
974 "H_ADST",
975 "V_FLIPADST",
976 "H_FLIPADST",
977 ];
978 let name_of = |t: usize| NAMES[t];
979 for (label, hits) in [
980 ("inter", take_inter_tx_type_hits()),
981 ("intra", take_tx_type_hits()),
982 ] {
983 let total: usize = hits.iter().sum();
984 let live: Vec<String> = hits
985 .iter()
986 .enumerate()
987 .filter(|&(_, &n)| n > 0)
988 .map(|(t, &n)| {
989 format!(
990 "{}={n} ({:.1}%)",
991 name_of(t),
992 100.0 * n as f64 / total.max(1) as f64
993 )
994 })
995 .collect();
996 eprintln!(
997 "{name}: {label} tx_type of {total} units -- {}",
998 live.join(" ")
999 );
1000 }
1001 let t = take_txrd_stats();
1002 if t[0] > 0 {
1003 eprintln!(
1004 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
1005 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
1006 t[0],
1007 t[1],
1008 t[3] as f64 / 64.0,
1009 t[2],
1010 t[4] as f64 / 64.0,
1011 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
1012 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
1013 );
1014 eprintln!(
1015 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
1016 flat: dsse {:+.2}%, dbits {:+.2}%)",
1017 t[5],
1018 t[6] as f64 / 64.0,
1019 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
1020 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
1021 );
1022 }
1023 }
1024
1025 /// The video stream's coded size, from ffprobe.
1026 pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> {
1027 crate::probe::dims(clip)
1028 }
1029
1030 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
1031 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
1032 /// superblock-aligned one, still centred and still even for 4:2:0.
1033 ///
1034 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
1035 /// superblocks by design, so no default gate row has a block the frame
1036 /// edge cuts through -- while every arbitrary export size does (3840x1608
1037 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
1038 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
1039 /// read on.
1040 pub(super) fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
1041 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
1042 let (w, h) = spec
1043 .split_once('x')
1044 .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
1045 let (cw, ch): (usize, usize) = (
1046 w.parse().expect("crop width"),
1047 h.parse().expect("crop height"),
1048 );
1049 let (nw, nh) = crate::probe::dims(clip)?;
1050 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
1051 let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1052 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
1053 }
1054
1055 /// The probe arms the gate's source (lane-probe, class `instrument
1056 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
1057 /// command line and had no `-ss`, so it read film B from frame 0 -- a
1058 /// black leader -- and coded 59 kB where the gate's own ladder point
1059 /// coded 89 kB of the same title; every census taken through it was
1060 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
1061 /// the shared loader honours the seek (arming the probe's way and the
1062 /// gate's way gives byte-identical streams, and dropping the seek does
1063 /// not), on a synthetic clip whose content moves over time.
1064 #[test]
1065 fn the_probe_arms_the_gates_source() {
1066 let _knobs = crate::speed::knob_write();
1067 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
1068 std::fs::create_dir_all(&dir).unwrap();
1069 let clip = dir.join("testsrc2.y4m");
1070 // 384x202: neither side is a multiple of 128, so the gate's centre
1071 // window is a real derivation and not the frame itself -- exactly the
1072 // shape film B has (3840x1608, never 3840x2160).
1073 let ok = ec_testkit::ffmpeg()
1074 .args([
1075 "-v",
1076 "error",
1077 "-y",
1078 "-f",
1079 "lavfi",
1080 "-i",
1081 "testsrc2=size=384x202:rate=10",
1082 ])
1083 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
1084 .arg(&clip)
1085 .status()
1086 .expect("ffmpeg failed to run")
1087 .success();
1088 assert!(ok, "ffmpeg could not write the synthetic clip");
1089 let path = clip.to_str().unwrap();
1090
1091 // The window: superblock-aligned, centred, even offsets.
1092 let (vf, w, h) = crate::probe::gate_crop(path);
1093 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
1094
1095 let (seek, q) = ("00:00:01", 150u8);
1096 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
1097 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
1098 assert!(
1099 gate.iter()
1100 .zip(&probe)
1101 .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
1102 "the probe's source differs from the gate's at the same window"
1103 );
1104 let bytes = |src: &[Picture]| {
1105 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
1106 .unwrap()
1107 .stream
1108 };
1109 assert_eq!(
1110 bytes(&gate),
1111 bytes(&probe),
1112 "probe and gate code different bytes"
1113 );
1114 // The two witnesses that both halves of the arming reach ffmpeg: the
1115 // seek, and the crop's own offset (the film-B defect in miniature --
1116 // the probe was reading `crop=..:568` of a 1608-high frame).
1117 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
1118 assert_ne!(
1119 bytes(&gate),
1120 bytes(&unseeked),
1121 "seeked and unseeked arming coded the same bytes -- the seek is inert"
1122 );
1123 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
1124 assert_ne!(
1125 bytes(&gate),
1126 bytes(&offset),
1127 "centred and top-aligned windows coded the same bytes -- the crop is inert"
1128 );
1129 std::fs::remove_dir_all(&dir).ok();
1130 }
1131
1132 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
1133 /// hardwire the REGULAR kernel, so the encoder could not have coded a
1134 /// SMOOTH or SHARP frame even if the header had said so -- the search,
1135 /// the trials, the recon and the frame header now all read
1136 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
1137 /// distinct stream (a filter that never reached the prediction would code
1138 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
1139 /// reconstructs every frame of each of them exactly, which is what proves
1140 /// the header and the prediction agree.
1141 #[test]
1142 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
1143 let _knobs = crate::speed::knob_write();
1144 let (width, height) = (256usize, 128usize);
1145 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
1146 // all three kernels would code the same bytes and the test would pass
1147 // on a wiring that does nothing (class `fixture proves the symbol, not
1148 // the signal`). `panned_test_card` shifts by whole pixels, so the
1149 // search finds the sub-pel positions off the reconstruction instead:
1150 // three frames of a slow diagonal pan.
1151 let pictures: Vec<Picture> = (0..3)
1152 .map(|i| panned_test_card(width, height, i * 3))
1153 .collect();
1154 let mut streams = Vec::new();
1155 for filter in [
1156 ec_av1_syntax::InterpolationFilter::Eighttap,
1157 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
1158 ec_av1_syntax::InterpolationFilter::EighttapSharp,
1159 ] {
1160 set_frame_interp(Some(filter));
1161 let fctx = &crate::decode::FrameCtx::for_encoder();
1162 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
1163 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
1164 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
1165 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
1166 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
1167 assert_eq!(
1168 decoded.y, frame.reconstruction.y,
1169 "{filter:?} frame {i}: luma"
1170 );
1171 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
1172 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
1173 }
1174 streams.push((filter, encoded.stream));
1175 }
1176 set_frame_interp(None);
1177 for (i, (fa, a)) in streams.iter().enumerate() {
1178 for (fb, b) in &streams[i + 1..] {
1179 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
1180 }
1181 }
1182 }
1183
1184 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
1185 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
1186 /// residual outright (`round_to_valid_mv` rounds it away first), so the
1187 /// finest vector the encoder could commit to was a quarter pel. With the
1188 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
1189 /// non-zero component and the search's fourth stage refines to the
1190 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
1191 /// on arm, and -- the part that makes it a signal rather than a symbol
1192 /// count (class `fixture proves the symbol, not the signal`) -- that some
1193 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
1194 /// all. Both streams are decoded by ffmpeg AND by this crate's own
1195 /// decoder and asserted sample-exact against the encoder's own
1196 /// reconstruction, which is what proves the header bit and the symbols
1197 /// agree.
1198 #[test]
1199 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
1200 let _knobs = crate::speed::knob_write();
1201 let (width, height) = (256usize, 128usize);
1202 let pictures: Vec<Picture> = (0..3)
1203 .map(|i| panned_test_card(width, height, i * 3))
1204 .collect();
1205 let mut arms = Vec::new();
1206 for hp in [false, true] {
1207 set_high_precision_mv(Some(hp));
1208 let _ = crate::tile::take_hp_symbols();
1209 let fctx = &crate::decode::FrameCtx::for_encoder();
1210 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
1211 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
1212 let (symbols, eighth) = crate::tile::take_hp_symbols();
1213 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
1214 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
1215 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
1216 assert_eq!(
1217 ours.len(),
1218 pictures.len(),
1219 "hp={hp}: our decoder frame count"
1220 );
1221 for (i, e) in encoded.frames.iter().enumerate() {
1222 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
1223 if let Some((plane, s, got, want)) =
1224 first_plane_mismatch(got, &e.reconstruction)
1225 {
1226 panic!(
1227 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
1228 the encoder reconstructed {want}"
1229 );
1230 }
1231 }
1232 }
1233 arms.push((symbols, eighth, encoded.stream));
1234 }
1235 set_high_precision_mv(None);
1236 let (off, on) = (&arms[0], &arms[1]);
1237 assert_eq!(
1238 off.0, 0,
1239 "a frame without the header bit codes no hp symbol"
1240 );
1241 assert!(
1242 on.0 > 0,
1243 "a high-precision frame codes hp symbols (got {})",
1244 on.0
1245 );
1246 assert!(
1247 on.1 > 0,
1248 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
1249 on.0
1250 );
1251 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
1252 println!(
1253 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
1254 off.0,
1255 off.2.len(),
1256 on.0,
1257 on.1,
1258 on.2.len()
1259 );
1260 }