forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tests.rs3932 lines, 171.6 KiBHistoryRawDownload
1 use super::*;
2 use std::process::{Command, Stdio};
3
4 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
5 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
6 /// aomenc gate decodes its stream through ffmpeg and is meaningless
7 /// without it -- turns it into a hard failure. Without this the require
8 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
9 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
10 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
11 fn have_ffmpeg() -> bool {
12 let present = Command::new("ffmpeg")
13 .arg("-version")
14 .stdout(Stdio::null())
15 .stderr(Stdio::null())
16 .status()
17 .is_ok_and(|s| s.success());
18 assert!(
19 present
20 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
21 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
22 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
23 );
24 present
25 }
26
27 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
28 let mut picture = Picture::grey(width, height);
29 for y in 0..height {
30 for x in 0..width {
31 let sx = (x + shift) % width;
32 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
33 }
34 }
35 for y in 0..height / 2 {
36 for x in 0..width / 2 {
37 let i = y * (width / 2) + x;
38 picture.u[i] = ((100 + shift * 4) % 256) as u16;
39 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
40 }
41 }
42 picture
43 }
44
45 /// Drives a whole stream through the facade the way a caller must since
46 /// it holds one picture of lookahead: every picture through
47 /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
48 fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
49 let mut packets = Vec::with_capacity(pictures.len());
50 for (i, picture) in pictures.iter().enumerate() {
51 packets.extend(
52 enc.encode_frames(picture)
53 .unwrap_or_else(|e| panic!("picture {i}: {e}")),
54 );
55 }
56 packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
57 packets
58 }
59
60 /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
61 /// counts and leaf count match the packets a real run emits, at three
62 /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
63 /// the run's budget exactly (`gop` frame targets, no more and no less).
64 ///
65 /// Both halves matter: a shape that misses a level (the old model priced
66 /// ONE hidden frame per group when the mid level had made it two) splits
67 /// the budget by weights that do not add up to the run.
68 #[test]
69 fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
70 let _knobs = crate::speed::knob_read();
71 let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
72 let quarters = Pyramid {
73 quarter_q_offset: Some(-20),
74 ..Pyramid::default()
75 };
76 let two_level = Pyramid {
77 mid_q_offset: None,
78 ..Pyramid::default()
79 };
80 for (gop, pyramid) in [
81 (48, Pyramid::default()),
82 (12, Pyramid::default()),
83 (48, quarters),
84 (48, two_level),
85 ] {
86 let config = EncoderConfig {
87 width: 64,
88 height: 64,
89 base_q_idx: 100,
90 gop,
91 colour: Colour::Bt709Limited,
92 tile_cols_log2: 0,
93 tile_rows_log2: 0,
94 };
95 let rate = RateTarget::BytesPerFrame(2_000);
96 let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
97 let packets = encode_all(&mut enc, &pictures[..gop]);
98 let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
99 let (hidden, leaves) = gop_shape(pyramid, gop);
100 let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
101 assert_eq!(
102 (hidden_frames, leaves, 1),
103 (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
104 "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
105 );
106 assert_eq!(
107 hidden_frames + leaves + 1,
108 gop,
109 "gop {gop}: every picture is coded exactly once"
110 );
111 // The plan adds up: one leaf's target times the run's whole
112 // weight is the run's whole budget.
113 let target_bytes = 2_000.0;
114 let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
115 let planned = loop_.target[0]
116 + loop_.target[2]
117 * (leaves as f64
118 + hidden
119 .iter()
120 .map(|&(o, n)| n as f64 * loop_.weight(o))
121 .sum::<f64>());
122 assert!(
123 (planned - target_bytes * gop as f64).abs() < 1.0,
124 "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
125 target_bytes * gop as f64
126 );
127 }
128 }
129
130 /// A level at its quantizer BOUND hands its unspent bytes to the levels
131 /// that can still move ([[vorbis-rate-loop-windup]]'s class in the
132 /// small), and it does so AT ONCE, not once the bound level's frames are
133 /// all coded: the loop is driven by a synthetic per-level model where the
134 /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255
135 /// clamp) and spends half its plan, and the leaves' target must jump to
136 /// the run's remainder with EVERY remaining hidden frame priced at that
137 /// measured rate. The old division -- whole remainder over whole
138 /// remaining weight -- handed most of the shortfall straight back to the
139 /// hidden slot (which carries most of the pyramid's weight and cannot
140 /// spend it), so the leaves only saw the surplus at the end of the run,
141 /// when there was nothing left to code with it.
142 #[test]
143 fn a_bound_level_hands_its_unspent_bytes_to_the_others() {
144 let pyramid = Pyramid::default();
145 let (gop, target_bytes) = (48usize, 2_000.0);
146 let (hidden, leaves) = gop_shape(pyramid, gop);
147 let run_bytes = target_bytes * gop as f64;
148 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
149 let scale0 = rl.target[2];
150 let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();
151 // The key codes exactly its plan; the first hidden frame is at the
152 // floor and spends half of its.
153 let key_bytes = rl.target[0].round();
154 rl.update(Level::Key, 0, 100, key_bytes as usize);
155 let (offset, n0) = hidden[0];
156 let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round();
157 rl.update(Level::Arf, offset, 0, arf_bytes as usize);
158 // Every frame of THAT LEVEL still to come is priced at what the bound
159 // one measured -- and only that level: its slot-mates (the mid ARF)
160 // sit at their own offset and are still free to follow the plan.
161 // Everything else shares the rest.
162 let want = (run_bytes - key_bytes - arf_bytes * n0 as f64)
163 / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset));
164 assert!(
165 want < scale0 * RateLoop::REPLAN_CLAMP,
166 "this arm must not reach the windup bound: {want:.1} vs {:.1}",
167 scale0 * RateLoop::REPLAN_CLAMP
168 );
169 assert!(
170 (rl.target[2] - want).abs() < 1e-6,
171 "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
172 give {:.3})",
173 rl.target[2],
174 (run_bytes - key_bytes - arf_bytes)
175 / (leaves as f64 + hidden_weight - rl.weight(offset))
176 );
177 // And the re-plan stays BOUNDED: hidden levels that spend nothing at
178 // all cannot run the leaves' target away.
179 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
180 rl.update(Level::Key, 0, 100, key_bytes as usize);
181 for &(offset, n) in &hidden {
182 for _ in 0..n {
183 rl.update(Level::Arf, offset, 0, 1);
184 }
185 }
186 assert!(
187 rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,
188 "the re-plan is unbounded: leaf target {:.1} past {:.1}",
189 rl.target[2],
190 scale0 * RateLoop::REPLAN_CLAMP
191 );
192 // ... and BOTH ways: a re-plan that reached zero would stop the loop
193 // dead (`update` returns on a non-positive target).
194 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
195 rl.update(Level::Key, 0, 100, key_bytes as usize);
196 for &(offset, n) in &hidden {
197 for _ in 0..n {
198 rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);
199 }
200 }
201 assert!(
202 rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9,
203 "the re-plan froze the loop: leaf target {:.1} under {:.1}",
204 rl.target[2],
205 scale0 * RateLoop::REPLAN_FLOOR
206 );
207 }
208
209 /// The mini-GOP layout leaves no short tail group, and leaves the long
210 /// GOP the fixed rule already coded alone: 47 inter pictures are
211 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
212 /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
213 #[test]
214 fn the_mini_gop_layout_leaves_no_short_tail() {
215 let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
216 let (mut left, mut out) = (remaining, Vec::new());
217 while left > 0 {
218 let g = group_target(left, mini_gop, absorb).min(left);
219 assert!(g > 0);
220 out.push(g);
221 left -= g;
222 }
223 out
224 };
225 // gop 48: what mini_gop 8 already coded, under either rule.
226 assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
227 assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
228 // gop 12: 8 + 3 becomes one group of 11.
229 assert_eq!(groups(11, 8, false), vec![8, 3]);
230 assert_eq!(groups(11, 8, true), vec![11]);
231 // A run shorter than a group is one group, as before (the 4-picture
232 // pin clip).
233 assert_eq!(groups(3, 8, true), vec![3]);
234 // No group is ever below half the shape, and none is over 1.5x it.
235 for mini_gop in 2..=16 {
236 for remaining in 1..=64 {
237 for g in groups(remaining, mini_gop, true) {
238 assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
239 assert!(
240 g * 2 >= mini_gop || remaining < mini_gop,
241 "{remaining}/{mini_gop}: short tail {g}"
242 );
243 }
244 }
245 }
246 }
247
248 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
249 /// in order.
250 fn concat(packets: &[Packet]) -> Vec<u8> {
251 packets.iter().flat_map(|p| p.data.clone()).collect()
252 }
253
254 /// The facade's latency contract (lane-av1facade, deepened on
255 /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
256 /// their picture back and return an empty packet, every later call
257 /// returns the packet of the picture that many frames earlier, and
258 /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
259 /// exactly one non-empty packet per picture, `depth - 1` calls later.
260 #[test]
261 fn one_in_one_out_delayed_by_the_lookahead_depth() {
262 let _knobs = crate::speed::knob_read();
263 let config = EncoderConfig {
264 width: 64,
265 height: 64,
266 base_q_idx: 100,
267 gop: 2,
268 colour: Colour::Bt709Limited,
269 tile_cols_log2: 0,
270 tile_rows_log2: 0,
271 };
272 let delay = crate::encode::tpl_depth() as u64 - 1;
273 let pictures = delay + 5;
274 let mut enc = Av1Encoder::new(config).unwrap();
275 for t in 0..pictures {
276 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
277 if t < delay {
278 assert!(packet.data.is_empty(), "call {t} holds its picture back");
279 continue;
280 }
281 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
282 assert_eq!(packet.order, t - delay, "picture {t}: order");
283 }
284 let tail = enc.flush().unwrap();
285 assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
286 for (i, p) in tail.iter().enumerate() {
287 assert_eq!(
288 p.order,
289 pictures - delay + i as u64,
290 "flushed packet {i}: order"
291 );
292 assert!(!p.data.is_empty(), "flushed packet {i}: empty");
293 }
294 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
295 }
296
297 /// A screen-like card: hard-edged 4-pixel bands of two flat luma values
298 /// with a moving block over the lower half — few colours per 16x16 block
299 /// at high variance, which is exactly what
300 /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
301 /// gate below runs the real detector rather than an override.
302 fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
303 let mut picture = Picture::grey(width, height);
304 for y in 0..height {
305 for x in 0..width {
306 let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
307 let over = y >= height / 2 && (x + shift) % width < width / 3;
308 picture.y[y * width + x] = if over { 128 } else { band };
309 }
310 }
311 picture
312 }
313
314 /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
315 /// lane-av1pyrdef): the streaming facade — what the editor's export
316 /// drives — codes byte for byte what [`crate::encode::encode_sequence`]
317 /// codes, which is the path the BD gate measures. Both now drive ONE
318 /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
319 /// identity is by construction; this pins it anyway, over both content
320 /// classes the content gate splits:
321 ///
322 /// * film-like (the gate's own clip when the fixture is there, a
323 /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
324 /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
325 /// paths' whole streams are identical;
326 /// * screen-like: the content gate drops BOTH paths back to flat, one
327 /// packet per picture, identical frame by frame as well as whole.
328 ///
329 /// Never skipped, since a skipped identity gate is the defect it is meant
330 /// to catch.
331 #[test]
332 fn the_facade_codes_the_same_bytes_as_encode_sequence() {
333 let _knobs = crate::speed::knob_read();
334 let frames = 12usize;
335 let film = h264_clip_frames("the facade identity film arm", 640, 384, frames)
336 .unwrap_or_else(|| {
337 // The probe inside already printed the ONE line naming the
338 // resolved path and the escape hatch, so this is a note about
339 // what runs instead — not a second SKIP.
340 eprintln!(" ...so the film arm runs on a synthetic card, not real film");
341 (0..frames).map(|t| test_card(64, 64, t)).collect()
342 });
343 let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
344 let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
345 for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
346 let (width, height) = (pictures[0].width, pictures[0].height);
347 for q in [150u8, 60] {
348 let config = EncoderConfig {
349 width,
350 height,
351 base_q_idx: q,
352 // One key frame then all inter, which is
353 // `encode_sequence`'s only shape, and the gate's recipe.
354 gop: frames,
355 // `encode_sequence` writes an unspecified colour config.
356 colour: Colour::Unspecified,
357 tile_cols_log2: 0,
358 tile_rows_log2: 0,
359 };
360 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
361 let mut packets = Vec::new();
362 for picture in pictures {
363 packets.extend(enc.encode_frames(picture).unwrap());
364 }
365 packets.extend(enc.flush().unwrap());
366 assert_eq!(
367 enc.pyramid().is_none(),
368 is_screen,
369 "{content} q={q}: the content gate read this clip the other way round"
370 );
371 let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
372 assert_eq!(
373 (
374 packets.iter().map(|p| p.data.len()).sum::<usize>(),
375 concat(&packets)
376 ),
377 (sequence.stream.len(), sequence.stream.clone()),
378 "{content} q={q}: the facade's stream is not the sequence path's"
379 );
380 assert_eq!(
381 sequence.frames.len(),
382 frames,
383 "{content} q={q}: one entry per picture, in display order"
384 );
385 if is_screen {
386 assert_eq!(
387 packets.len(),
388 frames,
389 "{content} q={q}: one packet per picture"
390 );
391 for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
392 let cropped = crate::encode::crop_encoded(coded, width, height);
393 assert_eq!(
394 (packet.data.len(), packet.data.clone()),
395 (cropped.stream.len(), cropped.stream.clone()),
396 "{content} q={q} frame {i}: the facade's bytes are not the \
397 sequence path's"
398 );
399 }
400 } else {
401 assert!(
402 packets.iter().any(|p| p.level == Level::Arf),
403 "{content} q={q}: a non-screen stream coded no hidden frame"
404 );
405 }
406 }
407 }
408 }
409
410 /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
411 /// the caller but applied only to camera material. Over screen content
412 /// the encoder must drop back to the flat path and code byte for byte
413 /// what a flat encoder codes — that is what keeps the BD gate's screen
414 /// row identical to the flat baseline — and over non-screen content the
415 /// same request must still reorder (class `gate-blind-to-feature`: a gate
416 /// that only checked the screen half would pass with the pyramid deleted).
417 #[test]
418 fn the_content_gate_keeps_screen_streams_flat() {
419 let _knobs = crate::speed::knob_read();
420 let frames = 8usize;
421 let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
422 let config = EncoderConfig {
423 width: 64,
424 height: 64,
425 base_q_idx: 120,
426 gop: frames,
427 colour: Colour::Unspecified,
428 tile_cols_log2: 0,
429 tile_rows_log2: 0,
430 };
431 crate::encode::force_screen(Some(true));
432 let mut flat = Av1Encoder::new(config).unwrap();
433 let flat_packets = encode_all(&mut flat, &pictures);
434 let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
435 let gated_packets = encode_all(&mut gated, &pictures);
436 assert_eq!(
437 gated.pyramid(),
438 None,
439 "the gate left a screen stream on the pyramid"
440 );
441 assert_eq!(
442 concat(&gated_packets),
443 concat(&flat_packets),
444 "a screen stream's bytes are not the flat path's"
445 );
446 crate::encode::force_screen(Some(false));
447 let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
448 let kept_packets = encode_all(&mut kept, &pictures);
449 assert_eq!(
450 kept.pyramid(),
451 Some(Pyramid::default()),
452 "the gate ate a film stream"
453 );
454 assert!(
455 kept_packets.iter().any(|p| p.level == Level::Arf),
456 "a non-screen stream coded no hidden frame"
457 );
458 crate::encode::force_screen(None);
459 }
460
461 /// A key frame every `gop` pictures, inter otherwise — checked against
462 /// what the facade itself reports, and (below) against what `ffprobe`
463 /// reads back out of the coded bytes.
464 #[test]
465 fn gop_cadence_is_honored() {
466 let _knobs = crate::speed::knob_read();
467 let config = EncoderConfig {
468 width: 64,
469 height: 64,
470 base_q_idx: 100,
471 gop: 3,
472 colour: Colour::Unspecified,
473 tile_cols_log2: 0,
474 tile_rows_log2: 0,
475 };
476 let mut enc = Av1Encoder::new(config).unwrap();
477 let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
478 let keys: Vec<bool> = encode_all(&mut enc, &pictures)
479 .iter()
480 .map(|p| p.key)
481 .collect();
482 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
483 }
484
485 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
486 let path = std::env::temp_dir().join(format!(
487 "ec-av1-facade-probe-{}-{}.obu",
488 std::process::id(),
489 std::ptr::addr_of!(stream) as usize
490 ));
491 std::fs::write(&path, stream).expect("writing the probe stream");
492 let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")
493 .args([
494 "-v",
495 "error",
496 "-f",
497 "obu",
498 "-select_streams",
499 "v:0",
500 "-show_entries",
501 "frame=key_frame,width,height",
502 "-of",
503 "csv=p=0",
504 ])
505 .arg(&path), None, |c| c.output())
506 .expect("ffprobe failed to run");
507 let _ = std::fs::remove_file(&path);
508 assert!(
509 out.status.success(),
510 "ffprobe refused the stream: {}",
511 String::from_utf8_lossy(&out.stderr)
512 );
513 String::from_utf8_lossy(&out.stdout)
514 .lines()
515 .map(|line| {
516 let mut f = line.trim().split(',');
517 let key: u32 = f.next().unwrap().parse().unwrap();
518 let width: u32 = f.next().unwrap().parse().unwrap();
519 let height: u32 = f.next().unwrap().parse().unwrap();
520 (key == 1, width, height)
521 })
522 .collect()
523 }
524
525 fn ffprobe_colour(stream: &[u8]) -> String {
526 let path = std::env::temp_dir().join(format!(
527 "ec-av1-facade-colour-probe-{}-{}.obu",
528 std::process::id(),
529 std::ptr::addr_of!(stream) as usize
530 ));
531 std::fs::write(&path, stream).expect("writing the probe stream");
532 let out = crate::tool_cache::cached_output_io(Command::new("ffprobe")
533 .args([
534 "-v",
535 "error",
536 "-f",
537 "obu",
538 "-select_streams",
539 "v:0",
540 "-show_entries",
541 "stream=color_primaries,color_transfer,color_space,color_range",
542 "-of",
543 "csv=p=0",
544 ])
545 .arg(&path), None, |c| c.output())
546 .expect("ffprobe failed to run");
547 let _ = std::fs::remove_file(&path);
548 assert!(
549 out.status.success(),
550 "ffprobe refused the stream: {}",
551 String::from_utf8_lossy(&out.stderr)
552 );
553 String::from_utf8_lossy(&out.stdout).trim().to_string()
554 }
555
556 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
557 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
558 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
559 /// coded size confirm what the facade already reported.
560 #[test]
561 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
562 let _knobs = crate::speed::knob_read();
563 if !have_ffmpeg() {
564 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
565 return;
566 }
567 let (width, height) = (96usize, 96usize);
568 let config = EncoderConfig {
569 width,
570 height,
571 base_q_idx: 120,
572 gop: 15,
573 colour: Colour::Bt709Limited,
574 tile_cols_log2: 0,
575 tile_rows_log2: 0,
576 };
577 let mut enc = Av1Encoder::new(config).unwrap();
578 assert_eq!(enc.display_size(), (width, height));
579 let (coded_w, coded_h) = enc.coded_size();
580 assert_eq!(
581 (coded_w, coded_h),
582 (
583 width.next_multiple_of(SUPERBLOCK),
584 height.next_multiple_of(SUPERBLOCK)
585 )
586 );
587
588 let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect();
589 let packets: Vec<Packet> = encode_all(&mut enc, &pictures);
590 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
591 assert_eq!(
592 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
593 expect_key,
594 "facade's own key/inter flags"
595 );
596
597 let stream = concat(&packets);
598 let frames = ffprobe_frames(&stream);
599 assert_eq!(frames.len(), 30, "ffprobe frame count");
600 for (t, (key, w, h)) in frames.iter().enumerate() {
601 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
602 assert_eq!(
603 (*w, *h),
604 (width as u32, height as u32),
605 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
606 );
607 }
608 }
609
610 /// The configured colour properties are what `ffprobe` reports back,
611 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
612 /// is the default a player assumes and the one this test would silently
613 /// pass without wiring for (`ffprobe` reports "unknown" for the
614 /// hardcoded "unspecified" this crate wrote before the facade existed,
615 /// which is a visibly different string).
616 #[test]
617 fn bt709_limited_colour_is_reported_by_ffprobe() {
618 let _knobs = crate::speed::knob_read();
619 if !have_ffmpeg() {
620 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
621 return;
622 }
623 let config = EncoderConfig {
624 width: 64,
625 height: 64,
626 base_q_idx: 100,
627 gop: 4,
628 colour: Colour::Bt709Limited,
629 tile_cols_log2: 0,
630 tile_rows_log2: 0,
631 };
632 let mut enc = Av1Encoder::new(config).unwrap();
633 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
634 let colour = ffprobe_colour(&packets[0].data);
635 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
636 }
637
638 /// The same, for BT.601: a different set of CICP integers must produce a
639 /// different string, or the wiring could be a no-op that happens to read
640 /// as BT.709 for every input.
641 #[test]
642 fn bt601_limited_colour_is_reported_by_ffprobe() {
643 let _knobs = crate::speed::knob_read();
644 if !have_ffmpeg() {
645 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
646 return;
647 }
648 let config = EncoderConfig {
649 width: 64,
650 height: 64,
651 base_q_idx: 100,
652 gop: 4,
653 colour: Colour::Bt601Limited,
654 tile_cols_log2: 0,
655 tile_rows_log2: 0,
656 };
657 let mut enc = Av1Encoder::new(config).unwrap();
658 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
659 let colour = ffprobe_colour(&packets[0].data);
660 assert_eq!(
661 colour, "tv,smpte170m,smpte170m,smpte170m",
662 "ffprobe colour fields"
663 );
664 }
665
666 /// A frame whose size does not match the encoder's configured geometry
667 /// is refused by name.
668 #[test]
669 fn geometry_mismatch_is_refused() {
670 let _knobs = crate::speed::knob_read();
671 let config = EncoderConfig {
672 width: 64,
673 height: 64,
674 base_q_idx: 100,
675 gop: 4,
676 colour: Colour::Bt709Limited,
677 tile_cols_log2: 0,
678 tile_rows_log2: 0,
679 };
680 let mut enc = Av1Encoder::new(config).unwrap();
681 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
682 assert!(err.to_string().contains("64x64"), "{err}");
683 }
684
685 /// `gop == 0` is refused at construction, not the first `encode()` call.
686 #[test]
687 fn zero_gop_is_refused() {
688 let _knobs = crate::speed::knob_read();
689 let config = EncoderConfig {
690 width: 64,
691 height: 64,
692 base_q_idx: 100,
693 gop: 0,
694 colour: Colour::Bt709Limited,
695 tile_cols_log2: 0,
696 tile_rows_log2: 0,
697 };
698 let err = Av1Encoder::new(config).unwrap_err();
699 assert!(err.to_string().contains("gop"), "{err}");
700 }
701
702 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
703 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
704 /// to this facade's own input size, and re-coded through the facade so the
705 /// rate-target surface is exercised at the entry point a caller actually
706 /// drives.
707 ///
708 /// lane-av1clipprobe: the ABSENCE of this clip used to be a bare
709 /// `clip.exists()` -> `None`, and every caller turned that into a `SKIP`
710 /// line and a return -- so a tree with no root `fixtures/` printed
711 /// `SKIP the 1080p tile round trip: no fixture` and libtest reported `ok`:
712 /// green with nothing asserted, and no env that made it RED. The presence
713 /// check now lives in the crate's one library-fixture probe
714 /// (`library_fixture::require_at`), which fails under `EC_REQUIRE_FIXTURES` /
715 /// `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC` and otherwise prints
716 /// that ONE line.
717 fn h264_clip_frames(
718 what: &str,
719 width: usize,
720 height: usize,
721 frames: usize,
722 ) -> Option<Vec<Picture>> {
723 if !have_ffmpeg() {
724 eprintln!("SKIP {what}: no ffmpeg");
725 return None;
726 }
727 // lane-av1speed3: the wall tables below are read on REAL film as
728 // well as on the colour-bar fixture (`bars` vs `film` in the BD
729 // gate's own vocabulary), and the film crop lives outside the repo --
730 // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other
731 // caller still gets the fixture.
732 //
733 // lane-av1clipprobe: the default path resolves through `EC_FIXTURES`
734 // first, which is the root `scripts/verify-fixture-library.sh`
735 // validates -- so the preflight's verdict and these bytes are the same
736 // tree, and GREEN-with-an-absent-root is no longer reachable by
737 // pointing EC_FIXTURES somewhere the gates do not read.
738 let clip = match std::env::var("EC_AV1_WALL_CLIP") {
739 Ok(p) => std::path::PathBuf::from(p),
740 Err(_) => crate::library_fixture::path("video/h264-1080p-23.976-8bit.mp4"),
741 };
742 // `what` is the CALLING GATE's name, carried in so that both exits from
743 // this function print exactly one line naming it: the ffmpeg line
744 // above, and the probe's line naming the resolved path. Callers
745 // therefore `return` on `None` WITHOUT printing a second one -- the
746 // second "no fixture" line per gate was the noise that hid this defect.
747 let clip = crate::library_fixture::require_at(clip, what)?;
748 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
749 .args(["-v", "error", "-i", clip.to_str().unwrap()])
750 .args(["-frames:v", &frames.to_string()])
751 .args(["-vf", &format!("scale={width}:{height}")])
752 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())
753 .expect("ffmpeg failed to run");
754 assert!(
755 out.status.success(),
756 "{}",
757 String::from_utf8_lossy(&out.stderr)
758 );
759 let (luma, chroma) = (width * height, width * height / 4);
760 let frame_len = luma + 2 * chroma;
761 assert_eq!(
762 out.stdout.len(),
763 frame_len * frames,
764 "expected {frames} 4:2:0 frames"
765 );
766 Some(
767 (0..frames)
768 .map(|i| {
769 let bytes = &out.stdout[i * frame_len..][..frame_len];
770 Picture {
771 width,
772 height,
773 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
774 u: bytes[luma..luma + chroma]
775 .iter()
776 .map(|&v| u16::from(v))
777 .collect(),
778 v: bytes[luma + chroma..]
779 .iter()
780 .map(|&v| u16::from(v))
781 .collect(),
782 }
783 })
784 .collect(),
785 )
786 }
787
788 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
789 /// coded size within ±20% of `frames * target` once the first few
790 /// frames' settling has been discarded (the key frame's own reference
791 /// state and the controller's first couple of steps).
792 #[test]
793 fn bytes_per_frame_target_settles_within_20_percent() {
794 let _knobs = crate::speed::knob_read();
795 let Some(pictures) = h264_clip_frames(
796 "bytes_per_frame_target_settles_within_20_percent",
797 640,
798 384,
799 24,
800 ) else {
801 return;
802 };
803 let target_bytes = 4_000u32;
804 let config = EncoderConfig {
805 width: 640,
806 height: 384,
807 base_q_idx: 100,
808 gop: 24,
809 colour: Colour::Bt709Limited,
810 tile_cols_log2: 0,
811 tile_rows_log2: 0,
812 };
813 let mut enc =
814 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
815 let sizes: Vec<usize> = encode_all(&mut enc, &pictures)
816 .iter()
817 .map(|p| p.data.len())
818 .collect();
819 // Discard the key frame (always far larger than an inter target) and
820 // the next 4 inter frames the loop needs to step toward it.
821 let settled = &sizes[5..];
822 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
823 let low = f64::from(target_bytes) * 0.8;
824 let high = f64::from(target_bytes) * 1.2;
825 assert!(
826 mean >= low && mean <= high,
827 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
828 );
829 }
830
831 /// One (bitrate, pyramid) arm's tally, built on the worker thread and
832 /// handed back through the progress channel
833 /// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL,
834 /// so a miss reads as WHICH level's model is off rather than as one
835 /// aggregate percentage.
836 struct ArmResult {
837 /// [`RateLoop::target`] as the arm's own encoder computed it.
838 targets: [f64; 3],
839 coded: usize,
840 bytes: [usize; 4],
841 count: [usize; 4],
842 }
843
844 impl ArmResult {
845 fn take(&mut self, packets: Vec<Packet>) {
846 for packet in packets {
847 self.coded += packet.data.len();
848 let i = match packet.level {
849 Level::Key => 0,
850 Level::Arf => 1,
851 Level::Leaf => 2,
852 Level::ShowExisting => 3,
853 };
854 self.bytes[i] += packet.data.len();
855 self.count[i] += 1;
856 }
857 }
858 }
859
860 /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
861 /// target over 48 frames of a real clip, flat and under a pyramid alike,
862 /// across a 5x span of bitrates. This is the accuracy claim of the
863 /// target-bitrate mode: no two-pass, no lookahead, just each frame's size
864 /// predicted from the previous frame of its own level, one clamped
865 /// proportional step, and the level model
866 /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
867 ///
868 /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
869 /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
870 /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
871 /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
872 /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
873 /// `leaf_q_offset`, so this clip cannot be made to spend much past
874 /// 2.4 Mbit/s under the default pyramid however the budget is split.
875 ///
876 /// # Bounded
877 ///
878 /// Each arm's encode runs on a worker thread under a per-CALL
879 /// wall-clock ceiling, so this gate FAILS rather than hanging when an
880 /// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host
881 /// and 30min on another, both here, both with the test thread spinning
882 /// and no child process for the crate's child timeout to reap). The cost
883 /// is real and is why the budget is not tight: the two high bitrate arms
884 /// walk `q_idx` from the seed 100 down into the 20s to spend an
885 /// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs
886 /// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100.
887 /// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack.
888 ///
889 /// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the
890 /// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid
891 /// constructors nest three deep -- `with_pyramid_and_rate_target` ->
892 /// `with_pyramid` -> `new` -- and each level materialises the struct in
893 /// an unoptimized build, so ~840 KB of stack was live at the innermost
894 /// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts:
895 /// `fatal runtime error: stack overflow, aborting`, reproduced on the
896 /// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via
897 /// `coredumpctl debug`.
898 ///
899 /// Boxing the snapshot brought the struct to 18168 bytes. This gate pins
900 /// that: it builds BOTH constructors on a thread with a deliberately
901 /// tight stack, so the old layout ABORTS THE PROCESS and the new one
902 /// returns. It runs in milliseconds, where proving the same thing through
903 /// the 48-frame gate takes 6m35s.
904 ///
905 /// Both thresholds were swept, in an unoptimized build:
906 ///
907 /// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) |
908 /// |---|---|---|
909 /// | 256 KiB | overflow | overflow |
910 /// | 384 KiB | overflow | ok |
911 /// | 512 KiB | overflow | ok |
912 /// | 1 MiB | **overflow** | **ok** |
913 /// | 2 MiB | **overflow** (libtest's default) | ok |
914 /// | 3 MiB | ok | ok |
915 ///
916 /// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what
917 /// the old one did, so it is nowhere near either threshold and cannot
918 /// flake. The pre-fix row at 1 MiB is the red -- which is also why
919 /// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a
920 /// workspace-local band-aid this gate makes unnecessary for this struct.
921 ///
922 /// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep
923 /// above is reproduced.
924 #[test]
925 fn the_pyramid_constructors_fit_on_a_tight_stack() {
926 // 1 MiB: see the threshold table on this test. Red before the Box,
927 // green after, with 2.7x margin either way.
928 const STACK: usize = 1024 * 1024;
929 let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
930 .ok()
931 .and_then(|v| v.parse().ok())
932 .unwrap_or(STACK);
933 let config = EncoderConfig {
934 width: 640,
935 height: 384,
936 base_q_idx: 100,
937 gop: 48,
938 colour: Colour::Bt709Limited,
939 tile_cols_log2: 0,
940 tile_rows_log2: 0,
941 };
942 let rate = RateTarget::Bitrate {
943 bits_per_second: 1_536_000,
944 frames_per_second: 24.0,
945 };
946 let handle = std::thread::Builder::new()
947 .stack_size(stack)
948 .spawn(move || {
949 let flat = Av1Encoder::with_rate_target(config, rate)
950 .expect("with_rate_target")
951 .rate_loop
952 .is_some();
953 let pyr =
954 Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
955 .expect("with_pyramid_and_rate_target")
956 .pyramid
957 .is_some();
958 (flat, pyr)
959 })
960 .expect("spawn tight-stack thread");
961 let (flat, pyr) = handle
962 .join()
963 .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack"));
964 assert!(flat, "with_rate_target lost its rate loop");
965 assert!(pyr, "with_pyramid_and_rate_target lost its pyramid");
966 eprintln!(
967 "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned",
968 std::mem::size_of::<Av1Encoder>()
969 );
970 }
971
972 #[test]
973 fn bitrate_target_lands_within_5_percent_over_48_frames() {
974 let _knobs = crate::speed::knob_read();
975 let (width, height, frames) = (640usize, 384usize, 48usize);
976 let Some(pictures) = h264_clip_frames(
977 "bitrate_target_lands_within_5_percent_over_48_frames",
978 width,
979 height,
980 frames,
981 ) else {
982 return;
983 };
984 let fps = 24.0;
985 let pictures = std::sync::Arc::new(pictures);
986 for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
987 let config = EncoderConfig {
988 width,
989 height,
990 base_q_idx: 100,
991 gop: frames,
992 colour: Colour::Bt709Limited,
993 tile_cols_log2: 0,
994 tile_rows_log2: 0,
995 };
996 let rate = RateTarget::Bitrate {
997 bits_per_second,
998 frames_per_second: fps,
999 };
1000 for pyramid in [None, Some(Pyramid::default())] {
1001 let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some());
1002 // lane-av1enchang: a BACKSTOP, not a fix. This gate is NOT
1003 // hung and NOT regressed -- it is a ~7 hour test in an
1004 // unoptimized build (measured: the whole `ec-av1` lib suite
1005 // takes 24341s, and this test is the largest single item in
1006 // it), and it PASSES. What it lacked was any way to FAIL: a
1007 // future non-terminating encode would wedge the suite for
1008 // hours with no diagnostic, which is exactly how wave3j and
1009 // wave3h were lost. So the arm runs on a worker thread and
1010 // THIS thread watches a per-CALL deadline, purely so that
1011 // case reports itself.
1012 //
1013 // The budget is PER CALL, not per test, and it is valued from
1014 // a measured run so it cannot turn a correct-but-slow build
1015 // red. Measured on this gate's own workload (48 frames of
1016 // 640x384): one `encode_frames` call is 0.78s..1.04s
1017 // optimized and 8.6s..12.2s debug on the flat arms. A
1018 // PYRAMID call codes a whole mini-GOP at once, so its worst
1019 // single call is `Pyramid::default().mini_gop` frames
1020 // (~9), i.e. ~110s debug. 1800s is therefore ~16x that
1021 // worst honest call: no plausible host trips it, and a real
1022 // non-terminating encode is reported in 30 minutes instead
1023 // of never. `EC_AV1_ENCODE_CALL_BUDGET_SECS` overrides it,
1024 // which is how the backstop is proven to bite.
1025 let budget = std::time::Duration::from_secs(
1026 std::env::var("EC_AV1_ENCODE_CALL_BUDGET_SECS")
1027 .ok()
1028 .and_then(|v| v.parse().ok())
1029 .unwrap_or(1800),
1030 );
1031 let total = pictures.len() + 1;
1032 // Shared, not cloned: the 48 decoded frames are ~35 MB of
1033 // `u16` luma+chroma, and all eight arms want the same ones.
1034 let pictures = std::sync::Arc::clone(&pictures);
1035 // `None` is a progress ticket: THIS call returned. `Some` is
1036 // the arm's result, sent after `flush` -- which is itself a
1037 // call that can spin, so it needs a ticket too, not a bare
1038 // `join` that would block forever.
1039 let (tx, rx) = std::sync::mpsc::channel::<Option<ArmResult>>();
1040 let worker = std::thread::spawn(move || {
1041 let mut enc = match pyramid {
1042 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
1043 Some(p) => {
1044 Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap()
1045 }
1046 };
1047 let targets = enc.rate_loop.as_ref().unwrap().target;
1048 let mut out = ArmResult {
1049 targets,
1050 coded: 0,
1051 bytes: [0; 4],
1052 count: [0; 4],
1053 };
1054 for picture in pictures.iter() {
1055 out.take(enc.encode_frames(picture).unwrap());
1056 if tx.send(None).is_err() {
1057 return;
1058 }
1059 }
1060 out.take(enc.flush().unwrap());
1061 let _ = tx.send(Some(out));
1062 });
1063 let started = std::time::Instant::now();
1064 let mut calls = 0usize;
1065 let out = loop {
1066 match rx.recv_timeout(budget) {
1067 // The result IS the last thing the worker sends, so
1068 // receiving it means every call returned. A worker
1069 // that panicked sends nothing and arrives as
1070 // `Disconnected` below, which re-joins it and
1071 // surfaces the real panic.
1072 Ok(Some(out)) => break out,
1073 Ok(None) => calls += 1,
1074 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!(
1075 "AV1 bitrate gate SLOW, NOT HUNG: the {arm} arm's encode did not \
1076 return within {}s (arm elapsed {:.0}s, stuck on call {} of {total} \
1077 -- the call that never came back). This gate is a ~7 hour test in \
1078 an unoptimized build and it PASSES, so a red here is NOT a slow \
1079 host: the budget is per CALL and the worst honest call measured \
1080 is ~1s optimized / ~110s debug on a pyramid arm, so reaching this \
1081 panic means an encode call that is NOT RETURNING. \
1082 EC_AV1_ENCODE_CALL_BUDGET_SECS raises the budget.",
1083 budget.as_secs(),
1084 started.elapsed().as_secs_f64(),
1085 calls + 1,
1086 ),
1087 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
1088 worker.join().expect("encode worker panicked");
1089 panic!("AV1 encode worker for {arm} died without a result");
1090 }
1091 }
1092 };
1093 let ArmResult {
1094 targets,
1095 coded,
1096 bytes,
1097 count,
1098 } = out;
1099 let seconds = frames as f64 / fps;
1100 let achieved = coded as f64 * 8.0 / seconds;
1101 let error = achieved / f64::from(bits_per_second) - 1.0;
1102 let per = |i: usize| match count[i] {
1103 0 => "-".to_string(),
1104 n => format!("{n}x{}", bytes[i] / n),
1105 };
1106 eprintln!(
1107 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
1108 = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
1109 coded key {} arf {} leaf {}",
1110 pyramid.is_some(),
1111 100.0 * error,
1112 targets[0],
1113 targets[1],
1114 targets[2],
1115 per(0),
1116 per(1),
1117 per(2),
1118 );
1119 assert!(
1120 error.abs() <= 0.05,
1121 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
1122 (pyramid {})",
1123 100.0 * error,
1124 pyramid.is_some(),
1125 );
1126 }
1127 }
1128 }
1129 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
1130 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
1131 /// clip's full range of content (so a scene cut can't be the one frame
1132 /// that breaks the bound).
1133 ///
1134 /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
1135 /// that has coded nothing yet is still sitting on the caller's
1136 /// `base_q_idx` guess, and its first step is the acquisition jump, not
1137 /// windup. Exactly one frame is exempt -- the loop below asserts the
1138 /// bound on every frame after it, which is where a scene cut would
1139 /// break it.
1140 #[test]
1141 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
1142 let _knobs = crate::speed::knob_read();
1143 let Some(pictures) = h264_clip_frames(
1144 "bytes_per_frame_controller_never_oscillates_past_its_clamp",
1145 640,
1146 384,
1147 24,
1148 ) else {
1149 return;
1150 };
1151 let config = EncoderConfig {
1152 width: 640,
1153 height: 384,
1154 base_q_idx: 100,
1155 gop: 24,
1156 colour: Colour::Bt709Limited,
1157 tile_cols_log2: 0,
1158 tile_rows_log2: 0,
1159 };
1160 let mut enc =
1161 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
1162 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1163 // The first frame this encoder EMITS is several `encode_frames` calls
1164 // in (the lookahead queue holds the earlier ones), so the seeding
1165 // step is not frame zero -- it is the first frame `q` moves at all.
1166 let mut seeded = false;
1167 let mut seed_frame = None;
1168 for (frame, picture) in pictures.iter().enumerate() {
1169 enc.encode_frames(picture).unwrap();
1170 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1171 let step = (i32::from(q) - i32::from(prev_q)).abs();
1172 if step > 0 && !seeded {
1173 seeded = true;
1174 seed_frame = Some(frame);
1175 } else {
1176 assert!(
1177 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
1178 "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
1179 RateLoop::STEP_CLAMP
1180 );
1181 }
1182 prev_q = q;
1183 }
1184 assert!(
1185 seed_frame.is_some(),
1186 "the controller never steered at all -- the bound below is vacuous"
1187 );
1188 }
1189
1190 fn psnr(a: &[u16], b: &[u16]) -> f64 {
1191 let squared: f64 = a
1192 .iter()
1193 .zip(b)
1194 .map(|(&x, &y)| {
1195 let d = f64::from(x) - f64::from(y);
1196 d * d
1197 })
1198 .sum();
1199 if squared == 0.0 {
1200 return f64::INFINITY;
1201 }
1202 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
1203 }
1204
1205 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
1206 /// entry per coded frame, in order — this facade's own equivalent of
1207 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
1208 /// PSNR check needs the decoded pixels, not just the coded byte count.
1209 fn ffmpeg_decode_planes(
1210 stream: &[u8],
1211 width: usize,
1212 height: usize,
1213 ) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
1214 let path = std::env::temp_dir().join(format!(
1215 "ec-av1-facade-rate-decode-{}-{}.obu",
1216 std::process::id(),
1217 std::ptr::addr_of!(stream) as usize
1218 ));
1219 std::fs::write(&path, stream).expect("writing the decode probe stream");
1220 let out = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
1221 .args(["-v", "error", "-f", "obu", "-i"])
1222 .arg(&path)
1223 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]), None, |c| c.output())
1224 .expect("ffmpeg failed to run");
1225 let _ = std::fs::remove_file(&path);
1226 assert!(
1227 out.status.success(),
1228 "{}",
1229 String::from_utf8_lossy(&out.stderr)
1230 );
1231 let (luma, chroma) = (width * height, width * height / 4);
1232 let frame_len = luma + 2 * chroma;
1233 out.stdout
1234 .chunks_exact(frame_len)
1235 .map(|f| {
1236 (
1237 f[..luma].to_vec(),
1238 f[luma..luma + chroma].to_vec(),
1239 f[luma + chroma..].to_vec(),
1240 )
1241 })
1242 .collect()
1243 }
1244
1245 /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare.
1246 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
1247 ffmpeg_decode_planes(stream, width, height)
1248 .into_iter()
1249 .map(|(y, _, _)| y)
1250 .collect()
1251 }
1252
1253 /// lane-palw: OUR encoder's own witness for the writer half of the
1254 /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall,
1255 /// so the bottom superblock row's palette blocks hang 8 luma rows off the
1256 /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN
1257 /// corner only and replicates it outward, and the writer used to code the
1258 /// full block grid -- symbols a conformant decoder never reads, so
1259 /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode
1260 /// (unclamped on both sides) agreed with itself. Class
1261 /// `writer-phantom-units-past-edge`.
1262 ///
1263 /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's
1264 /// export calls), and compared on EVERY plane -- a chroma palette map is
1265 /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero
1266 /// so the row cannot pass on a stream that cuts no palette map (class
1267 /// gate-blind-to-feature).
1268 #[test]
1269 fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
1270 const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
1271 let _knobs = crate::speed::knob_read();
1272 let _gate_lock = crate::stream::tests::lock_gate_counters();
1273 let (width, height) = (384usize, 152usize);
1274 // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
1275 // most two luma values, so the palette arm wins across the WHOLE
1276 // frame -- including the bottom superblock row, whose 16x16 blocks at
1277 // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid.
1278 // `screen_card`'s 4-px bands fire only 9 palettes here and none of
1279 // them at the cut edge (class gate-blind-to-feature).
1280 let card = |shift: usize| -> Picture {
1281 let mut picture = Picture::grey(width, height);
1282 for y in 0..height {
1283 for x in 0..width {
1284 let cell = ((x + shift) / 8 + y / 8) % 2;
1285 picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
1286 }
1287 }
1288 picture
1289 };
1290 let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
1291 let config = EncoderConfig {
1292 width,
1293 height,
1294 base_q_idx: 60,
1295 gop: 2,
1296 colour: Colour::Bt709Limited,
1297 tile_cols_log2: 0,
1298 tile_rows_log2: 0,
1299 };
1300 let mut enc = Av1Encoder::new(config).unwrap();
1301 crate::tile::reset_palette_cut_maps_written();
1302 let mut stream = Vec::new();
1303 for packet in encode_all(&mut enc, &sources) {
1304 stream.extend_from_slice(&packet.data);
1305 }
1306 eprintln!(
1307 "{NAME}: {} cut colour-index maps written",
1308 crate::tile::palette_cut_maps_written()
1309 );
1310 assert!(
1311 crate::tile::palette_cut_maps_written() > 0,
1312 "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
1313 );
1314 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1315 assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
1316 if !have_ffmpeg() {
1317 eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg");
1318 return;
1319 }
1320 let theirs = ffmpeg_decode_planes(&stream, width, height);
1321 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
1322 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1323 for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
1324 let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
1325 if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
1326 let w = if plane == "luma" { width } else { width / 2 };
1327 panic!(
1328 "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
1329 at % w,
1330 at / w,
1331 got[at],
1332 want[at],
1333 );
1334 }
1335 assert_eq!(
1336 got.len(),
1337 want.len(),
1338 "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}",
1339 got.len(),
1340 want.len()
1341 );
1342 }
1343 }
1344 }
1345
1346 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
1347 /// mini-GOP is coded before the leaves that precede it in display order,
1348 /// and a `show_existing_frame` header puts it back. This pins the shape
1349 /// (one packet per source picture plus one `show_existing_frame` per
1350 /// group, `dts` monotone, `order` NOT monotone) and then decodes the
1351 /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
1352 /// the two display-order outputs to agree sample for sample — the
1353 /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
1354 /// output, or output twice, or output in the wrong position, changes the
1355 /// display-order list and fails here.
1356 #[test]
1357 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1358 // `take_ref_frame_hits` is a process-global counter: a reader-locked
1359 // sibling encoding at the same time zeroes it between our encode and
1360 // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
1361 // exclusive lock.
1362 let _knobs = crate::speed::knob_write();
1363 pyramid_round_trip(
1364 Pyramid {
1365 mini_gop: 4,
1366 mid_q_offset: None,
1367 ..Pyramid::default()
1368 },
1369 2,
1370 );
1371 }
1372
1373 /// The same round trip over a THREE-level group (`mid_q_offset`): each
1374 /// mini-GOP now codes two hidden frames -- the top ARF at the group's
1375 /// last picture and the mid ARF at the middle of the leaf run -- and
1376 /// re-outputs both with `show_existing_frame`, so a mid frame emitted in
1377 /// the wrong display position, or twice, fails the display-order compare
1378 /// against ffmpeg exactly as a top ARF does.
1379 #[test]
1380 fn a_three_level_pyramid_stream_decodes_in_display_order() {
1381 let _knobs = crate::speed::knob_write();
1382 pyramid_round_trip(
1383 Pyramid {
1384 mini_gop: 8,
1385 mid_q_offset: Some(-8),
1386 ..Pyramid::default()
1387 },
1388 2,
1389 );
1390 }
1391
1392 /// The same round trip over a FOUR-level group
1393 /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four
1394 /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two
1395 /// quarters at 2 and 6 -- each re-output by its own
1396 /// `show_existing_frame`. Every leaf reads a different pair of DPB slots
1397 /// than it did at three levels, so a slot map that lets one level
1398 /// overwrite a picture another is still reading shows up here as a
1399 /// display-order mismatch against ffmpeg.
1400 #[test]
1401 fn a_four_level_pyramid_stream_decodes_in_display_order() {
1402 let _knobs = crate::speed::knob_write();
1403 pyramid_round_trip(
1404 Pyramid {
1405 mini_gop: 8,
1406 mid_q_offset: Some(-8),
1407 quarter_q_offset: Some(4),
1408 ..Pyramid::default()
1409 },
1410 4,
1411 );
1412 }
1413
1414 /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads
1415 /// the key, so an offset that never arrived would be invisible in the BD
1416 /// table except as "no change" (class symbol-consumption-gap). A finer
1417 /// key must cost strictly more bytes than the same picture at base q.
1418 #[test]
1419 fn the_key_q_offset_reaches_the_key_frame() {
1420 let _knobs = crate::speed::knob_read();
1421 crate::encode::force_screen(Some(false));
1422 let key_bytes = |offset: i16| {
1423 let config = EncoderConfig {
1424 width: 128,
1425 height: 128,
1426 base_q_idx: 120,
1427 gop: 32,
1428 colour: Colour::Bt709Limited,
1429 tile_cols_log2: 0,
1430 tile_rows_log2: 0,
1431 };
1432 let pyramid = Pyramid {
1433 key_q_offset: offset,
1434 ..Pyramid::default()
1435 };
1436 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1437 let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
1438 let key = packets
1439 .iter()
1440 .find(|p| p.level == Level::Key)
1441 .expect("key frame");
1442 key.data.len()
1443 };
1444 let (base, finer) = (key_bytes(0), key_bytes(-48));
1445 eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
1446 assert!(
1447 finer > base,
1448 "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
1449 );
1450 }
1451
1452 /// lane-last2's witness: a clip whose pictures ALTERNATE between two
1453 /// textures, so for every leaf the picture two back is an exact match and
1454 /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf
1455 /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older
1456 /// slot `LAST2_FRAME`; blocks must actually be CODED off it
1457 /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen
1458 /// proves only that the bookkeeping compiles), the stream must decode
1459 /// sample-exact through OUR decoder and through ffmpeg, and the hidden
1460 /// frames must still come out in display order. With the lever OFF the
1461 /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a
1462 /// measurement of this lane and not of the reference set we already had.
1463 #[test]
1464 fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() {
1465 let _knobs = crate::speed::knob_write();
1466 crate::encode::force_screen(Some(false));
1467 let (width, height) = (128usize, 128usize);
1468 let sources: Vec<Picture> = (0..9)
1469 .map(|t| test_card(width, height, (t % 2) * 24))
1470 .collect();
1471 let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) {
1472 set_last2(Some(on));
1473 let config = EncoderConfig {
1474 width,
1475 height,
1476 base_q_idx: 120,
1477 gop: 32,
1478 colour: Colour::Bt709Limited,
1479 tile_cols_log2: 0,
1480 tile_rows_log2: 0,
1481 };
1482 let pyramid = Pyramid {
1483 mini_gop: 4,
1484 mid_q_offset: None,
1485 ..Pyramid::default()
1486 };
1487 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1488 let _ = crate::encode::take_ref_frame_hits();
1489 let mut packets = Vec::new();
1490 for picture in &sources {
1491 packets.extend(enc.encode_frames(picture).unwrap());
1492 }
1493 packets.extend(enc.flush().unwrap());
1494 let hits = crate::encode::take_ref_frame_hits();
1495 (hits, concat(&packets), packets)
1496 };
1497 let (off_hits, off_stream, _) = run(false);
1498 let (on_hits, stream, packets) = run(true);
1499 set_last2(None);
1500 eprintln!(
1501 "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
1502 on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
1503 off_hits[1],
1504 off_hits[2],
1505 off_hits[4],
1506 off_hits[7],
1507 off_stream.len(),
1508 on_hits[1],
1509 on_hits[2],
1510 on_hits[4],
1511 on_hits[7],
1512 stream.len(),
1513 );
1514 assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
1515 assert!(
1516 on_hits[2] >= 8,
1517 "the picture two back matches exactly and only {} blocks were coded off LAST2",
1518 on_hits[2],
1519 );
1520
1521 // Display order and sample-exactness, both decoders (the same shape
1522 // `pyramid_round_trip` gates the hidden frames with).
1523 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1524 assert_eq!(
1525 ours.len(),
1526 sources.len(),
1527 "our decoder's display-order count"
1528 );
1529 if !have_ffmpeg() {
1530 eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg");
1531 return;
1532 }
1533 let theirs = ffmpeg_decode_luma(&stream, width, height);
1534 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
1535 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1536 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1537 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
1538 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1539 panic!(
1540 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1541 at % width,
1542 at / width,
1543 got[at],
1544 b[at],
1545 );
1546 }
1547 }
1548 // The reordering itself is unchanged by the second leaf slot.
1549 let shown = packets
1550 .iter()
1551 .filter(|p| p.level == Level::ShowExisting)
1552 .count();
1553 let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
1554 assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
1555 }
1556
1557 /// A picture whose content is a static gradient plus a per-picture
1558 /// pseudo-random +-2 of noise: motion search matches the neighbours
1559 /// almost exactly, so the ARF temporal filter's weights are near 1 and
1560 /// the filter actually changes the source (a moving test card gives every
1561 /// neighbour a large MSE, weight ~0, and the filter is a no-op that would
1562 /// make the future-window witness below pass blind).
1563 fn noisy_card(width: usize, height: usize, t: usize) -> Picture {
1564 let mut picture = Picture::grey(width, height);
1565 let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
1566 for y in 0..height {
1567 for x in 0..width {
1568 seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
1569 let noise = ((seed >> 33) % 5) as i32 - 2;
1570 let base = 40 + (x + y) as i32 / 2;
1571 picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16;
1572 }
1573 }
1574 for i in 0..(width / 2) * (height / 2) {
1575 picture.u[i] = 110;
1576 picture.v[i] = 140;
1577 }
1578 picture
1579 }
1580
1581 /// lane-lookahead's correctness witness. One group of lookahead
1582 /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and
1583 /// codes the group before it) must not change WHAT is coded:
1584 ///
1585 /// * with the future half of the filter window empty AND the top ARF's
1586 /// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream
1587 /// is byte for byte the one the encoder coded without a lookahead, at
1588 /// every run length -- 1 picture (no hidden frame at all), 7 (a short
1589 /// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 --
1590 /// and at a GOP short enough (8) that key frames drain the buffer
1591 /// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so
1592 /// the identity arm pins the lambda window off or this witness tests
1593 /// a different lever;
1594 /// * every run decodes to exactly its picture count through OUR decoder
1595 /// and through ffmpeg, sample-exact between the two, so the flush and
1596 /// the `show_existing_frame` order survive the delay;
1597 /// * and with ONE future neighbour the top ARF's source filter actually
1598 /// reads it -- the stream MOVES (class gate-blind-to-feature: a
1599 /// buffered picture nothing consumes would pass every check above).
1600 #[test]
1601 fn the_lookahead_holds_one_group_and_still_codes_every_picture() {
1602 let _knobs = crate::speed::knob_write();
1603 // The preset is PROCESS-GLOBAL and another test may have left it
1604 // anywhere: at a high one every block of this fixture codes as skip
1605 // (17 pictures in 493 bytes) and the source filter cannot change a
1606 // byte, which failed the future-half assertion below in the suite and
1607 // passed it standalone (class process-global-knob-races-tests).
1608 let was = crate::speed::speed();
1609 crate::speed::set_speed(0);
1610 crate::encode::force_screen(Some(false));
1611 let (width, height) = (128usize, 128usize);
1612 let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) {
1613 set_lookahead(Some(on));
1614 set_arf_tf_future(Some(fut));
1615 set_tpl_fut(Some(0));
1616 let config = EncoderConfig {
1617 // FINE (not the 120 the other facade tests use): at a coarse
1618 // quantizer this fixture's ARF codes almost pure skip (17
1619 // pictures in 493 bytes) and a filtered source quantizes back
1620 // to the same bytes, which made the future-half assertion
1621 // below depend on where the suite's other tests had left the
1622 // process-global preset. At q=60 the anchor carries real
1623 // coefficients and the filter must move them.
1624 base_q_idx: 60,
1625 width,
1626 height,
1627 gop,
1628 colour: Colour::Bt709Limited,
1629 tile_cols_log2: 0,
1630 tile_rows_log2: 0,
1631 };
1632 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
1633 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
1634 let packets = encode_all(&mut enc, &sources);
1635 // The content gate is process-global and so is the preset: if
1636 // either has been flipped under this test the pyramid is gone and
1637 // there is no ARF to filter, which is a different failure from
1638 // "the future neighbour changed nothing" (the suite reported the
1639 // second when it meant the first).
1640 assert!(
1641 enc.pyramid().is_some(),
1642 "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})",
1643 crate::speed::speed(),
1644 );
1645 (concat(&packets), packets)
1646 };
1647 for gop in [32usize, 8] {
1648 for n in [1usize, 7, 8, 9, 17] {
1649 let (flat, flat_packets) = run(n, gop, false, 0);
1650 let (held, packets) = run(n, gop, true, 0);
1651 assert_eq!(
1652 flat.len(),
1653 held.len(),
1654 "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH"
1655 );
1656 assert!(
1657 flat == held,
1658 "{n} pictures at gop {gop}: the stream is not byte-identical"
1659 );
1660 assert_eq!(
1661 packets
1662 .iter()
1663 .map(|p| (p.order, p.key, p.level))
1664 .collect::<Vec<_>>(),
1665 flat_packets
1666 .iter()
1667 .map(|p| (p.order, p.key, p.level))
1668 .collect::<Vec<_>>(),
1669 "{n} pictures at gop {gop}: coding order/levels moved"
1670 );
1671 let ours = crate::stream::decode_stream(&held).expect("our decoder");
1672 assert_eq!(
1673 ours.len(),
1674 n,
1675 "{n} pictures at gop {gop}: our decoder's count"
1676 );
1677 if !have_ffmpeg() {
1678 continue;
1679 }
1680 let theirs = ffmpeg_decode_luma(&held, width, height);
1681 assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count");
1682 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1683 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1684 assert!(
1685 got == *b,
1686 "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg"
1687 );
1688 }
1689 }
1690 }
1691 // The future half REACHES the filter, and what it produces still
1692 // decodes exactly.
1693 let (base, _) = run(17, 32, true, 0);
1694 let (symmetric, _) = run(17, 32, true, 1);
1695 set_lookahead(None);
1696 set_arf_tf_future(None);
1697 set_tpl_fut(None);
1698 assert!(
1699 base != symmetric,
1700 "one display-future neighbour left the top ARF's filter unchanged \
1701 ({} B vs {} B, preset {})",
1702 base.len(),
1703 symmetric.len(),
1704 crate::speed::speed()
1705 );
1706 let ours = crate::stream::decode_stream(&symmetric).expect("our decoder");
1707 assert_eq!(ours.len(), 17, "the symmetric arm's display-order count");
1708 if have_ffmpeg() {
1709 let theirs = ffmpeg_decode_luma(&symmetric, width, height);
1710 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");
1711 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1712 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1713 assert!(
1714 got == *b,
1715 "symmetric arm, display frame {i}: ours differs from ffmpeg"
1716 );
1717 }
1718 }
1719 crate::speed::set_speed(was);
1720 }
1721
1722 /// lane-tplfut's correctness witness, the sibling of
1723 /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with
1724 /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next
1725 /// group (`speed::TPL_FUT`), every picture is still coded, the streams
1726 /// decode exactly through our decoder and ffmpeg, and the stream MOVES
1727 /// against the knob off wherever a next group exists (class
1728 /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse
1729 /// quantizer this fixture's ARF is almost pure skip and a different
1730 /// lambda map re-quantises to identical bytes.
1731 #[test]
1732 fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() {
1733 let _knobs = crate::speed::knob_write();
1734 let was = crate::speed::speed();
1735 crate::speed::set_speed(0);
1736 crate::encode::force_screen(Some(false));
1737 let (width, height) = (128usize, 128usize);
1738 let run = |n: usize, gop: usize, fut: usize| -> (Vec<u8>, Vec<Packet>) {
1739 set_lookahead(Some(true));
1740 set_arf_tf_future(Some(0));
1741 set_tpl_fut(Some(fut));
1742 let config = EncoderConfig {
1743 base_q_idx: 60,
1744 width,
1745 height,
1746 gop,
1747 colour: Colour::Bt709Limited,
1748 tile_cols_log2: 0,
1749 tile_rows_log2: 0,
1750 };
1751 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
1752 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
1753 let packets = encode_all(&mut enc, &sources);
1754 assert!(
1755 enc.pyramid().is_some(),
1756 "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})",
1757 crate::speed::speed(),
1758 );
1759 (concat(&packets), packets)
1760 };
1761 for gop in [32usize, 8] {
1762 for n in [1usize, 7, 8, 9, 17] {
1763 let (off, off_packets) = run(n, gop, 0);
1764 for mode in [1usize, 2, 3] {
1765 let (on, packets) = run(n, gop, mode);
1766 assert_eq!(
1767 packets
1768 .iter()
1769 .map(|p| (p.order, p.key, p.level))
1770 .collect::<Vec<_>>(),
1771 off_packets
1772 .iter()
1773 .map(|p| (p.order, p.key, p.level))
1774 .collect::<Vec<_>>(),
1775 "{n} pictures at gop {gop} mode {mode}: coding order/levels moved"
1776 );
1777 let ours = crate::stream::decode_stream(&on).expect("our decoder");
1778 assert_eq!(
1779 ours.len(),
1780 n,
1781 "{n} pictures at gop {gop} mode {mode}: our count"
1782 );
1783 if !have_ffmpeg() {
1784 continue;
1785 }
1786 let theirs = ffmpeg_decode_luma(&on, width, height);
1787 assert_eq!(
1788 theirs.len(),
1789 n,
1790 "{n} pictures at gop {gop} mode {mode}: ffmpeg count"
1791 );
1792 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1793 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1794 assert!(
1795 got == *b,
1796 "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg"
1797 );
1798 }
1799 }
1800 let _ = &off;
1801 }
1802 }
1803 // The future window REACHES the lambda map: 17 pictures at gop 32 is
1804 // three groups, so the first two top ARFs each have a next group
1805 // buffered and their windows really are display-future.
1806 let (off, _) = run(17, 32, 0);
1807 // Mode 2 is NOT in this list: at its default split it keeps the three
1808 // NEAREST past neighbours, and those dominate the propagation -- on
1809 // this 128x128 fixture the map moves too little to flip an RD
1810 // decision and the stream comes back byte-identical to mode 0. Not a
1811 // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past
1812 // neighbour, six future) does move the stream, and the gate below
1813 // measures mode 2 on real content.
1814 for mode in [1usize, 3] {
1815 let (on, _) = run(17, 32, mode);
1816 assert!(
1817 off != on,
1818 "mode {mode} left the top ARF's temporal lambda map unchanged \
1819 ({} B vs {} B, preset {})",
1820 off.len(),
1821 on.len(),
1822 crate::speed::speed()
1823 );
1824 }
1825 set_lookahead(None);
1826 set_arf_tf_future(None);
1827 set_tpl_fut(None);
1828 crate::speed::set_speed(was);
1829 }
1830
1831 /// lane-arfmode: the top ARF's leaf offer set. Three guards in one
1832 /// witness, over 17 pictures at gop 32 (three groups, so several top
1833 /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the
1834 /// anchor carries real coefficients, so a cut that moves only the
1835 /// hidden frame's internal decisions cannot hide behind "everything
1836 /// quantized to the same bytes":
1837 ///
1838 /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the
1839 /// shipped table is 0 and the lever is bit-exact when off;
1840 /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really
1841 /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter
1842 /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM;
1843 /// 3. the coding order and levels never change, and every armed stream
1844 /// decodes sample-exact through `decode_stream` AND ffmpeg.
1845 #[test]
1846 fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() {
1847 let _knobs = crate::speed::knob_write();
1848 let was = crate::speed::speed();
1849 crate::speed::set_speed(0);
1850 crate::encode::force_screen(Some(false));
1851 let (width, height) = (128usize, 128usize);
1852 let run = |mode: Option<u8>| -> (Vec<u8>, Vec<Packet>) {
1853 crate::encode::set_arfmode(mode);
1854 let _ = crate::encode::take_arfmode_hits();
1855 let config = EncoderConfig {
1856 base_q_idx: 60,
1857 width,
1858 height,
1859 gop: 32,
1860 colour: Colour::Bt709Limited,
1861 tile_cols_log2: 0,
1862 tile_rows_log2: 0,
1863 };
1864 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
1865 // Groups at three luma LEVELS (the base ramp 40/110/180): the
1866 // middle group's top ARF sits halfway between the two dark/light
1867 // anchors its slots hold, which is exactly where neither
1868 // single-reference prediction nor intra wins by default -- the
1869 // AVERAGE of two references (compound) and the DC of the new
1870 // level (intra) do. Without this the synthetic cards' noise
1871 // quantizes to skip and no arm can move anything (measured:
1872 // 516 intra trials skipped, zero won, stream identical).
1873 let sources: Vec<Picture> = (0..17)
1874 .map(|t| {
1875 let mut p = noisy_card(width, height, t);
1876 let shift = 70i32 * (t / 8) as i32;
1877 for v in p.y.iter_mut() {
1878 *v = (i32::from(*v) + shift).clamp(0, 255) as u16;
1879 }
1880 p
1881 })
1882 .collect();
1883 let packets = encode_all(&mut enc, &sources);
1884 (concat(&packets), packets)
1885 };
1886 let (off, off_packets) = run(None);
1887 let (explicit_off, _) = run(Some(0));
1888 assert_eq!(
1889 off, explicit_off,
1890 "mode 0 is not bit-exact with the default"
1891 );
1892 for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] {
1893 let (on, packets) = run(Some(mode));
1894 let hits = crate::encode::take_arfmode_hits();
1895 assert_eq!(
1896 packets
1897 .iter()
1898 .map(|p| (p.order, p.key, p.level))
1899 .collect::<Vec<_>>(),
1900 off_packets
1901 .iter()
1902 .map(|p| (p.order, p.key, p.level))
1903 .collect::<Vec<_>>(),
1904 "mode {mode}: coding order/levels moved"
1905 );
1906 assert!(
1907 hits[arm] > 0,
1908 "mode {mode}: its counter never fired ({hits:?}) -- the lever is \
1909 gate-blind on this fixture",
1910 );
1911 assert_ne!(
1912 off, on,
1913 "mode {mode} left the stream byte-identical despite {} firing hits",
1914 hits[arm],
1915 );
1916 eprintln!(
1917 "mode {mode}: {} -> {} B, hits {hits:?}",
1918 off.len(),
1919 on.len()
1920 );
1921 let ours = crate::stream::decode_stream(&on).expect("our decoder");
1922 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");
1923 if !have_ffmpeg() {
1924 continue;
1925 }
1926 let theirs = ffmpeg_decode_luma(&on, width, height);
1927 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");
1928 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1929 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1930 assert!(
1931 got == *b,
1932 "mode {mode}, frame {i}: ours differs from ffmpeg"
1933 );
1934 }
1935 }
1936 crate::encode::set_arfmode(None);
1937 crate::speed::set_speed(was);
1938 }
1939
1940 fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
1941 let (width, height) = (128usize, 128usize);
1942 let config = EncoderConfig {
1943 width,
1944 height,
1945 base_q_idx: 120,
1946 gop: 32,
1947 colour: Colour::Bt709Limited,
1948 tile_cols_log2: 0,
1949 tile_rows_log2: 0,
1950 };
1951 // The content gate ([`Av1Encoder::encode_frames`]) would drop a
1952 // screen-content stream to the flat path, and a synthetic test card
1953 // is exactly the few-colour picture the detector fires on: this gate
1954 // is about the reordering, so it asks for camera content explicitly.
1955 crate::encode::force_screen(Some(false));
1956 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1957 let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
1958 let _ = crate::encode::take_ref_frame_hits();
1959 let mut packets = Vec::new();
1960 for picture in &sources {
1961 packets.extend(enc.encode_frames(picture).unwrap());
1962 }
1963 packets.extend(enc.flush().unwrap());
1964
1965 // Shape: every source picture is coded exactly once, and each closed
1966 // group adds one `show_existing_frame` packet.
1967 let coded: Vec<u64> = packets
1968 .iter()
1969 .filter(|p| p.level != Level::ShowExisting)
1970 .map(|p| p.order)
1971 .collect();
1972 let mut sorted = coded.clone();
1973 sorted.sort_unstable();
1974 assert_eq!(
1975 sorted,
1976 (0..9).collect::<Vec<u64>>(),
1977 "one packet per picture"
1978 );
1979 assert_ne!(coded, sorted, "the pyramid never reordered anything");
1980 let shown = packets
1981 .iter()
1982 .filter(|p| p.level == Level::ShowExisting)
1983 .count();
1984 assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
1985 for (i, p) in packets.iter().enumerate() {
1986 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
1987 }
1988 let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
1989 eprintln!(
1990 "pyramid levels: key {} arf {} leaf {} show_existing {}",
1991 hist(Level::Key),
1992 hist(Level::Arf),
1993 hist(Level::Leaf),
1994 hist(Level::ShowExisting),
1995 );
1996 assert_eq!(hist(Level::Arf), hidden, "hidden frames");
1997 let refs = crate::encode::take_ref_frame_hits();
1998 eprintln!(
1999 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
2000 refs[crate::mvstack::LAST_FRAME as usize],
2001 refs[crate::mvstack::GOLDEN_FRAME as usize],
2002 refs[crate::mvstack::ALTREF_FRAME as usize],
2003 );
2004 // [[gate-blind-to-feature]]: the whole point of the hidden frame is
2005 // that the leaves predict BACKWARD off it, which is also the only
2006 // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
2007 // round trip in which `ALTREF_FRAME` never won a block would prove
2008 // only that a hidden frame can be written and re-output.
2009 assert!(
2010 refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
2011 "no block predicted off the hidden ALTREF"
2012 );
2013
2014 let stream = concat(&packets);
2015 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2016 assert_eq!(
2017 ours.len(),
2018 sources.len(),
2019 "our decoder's display-order count"
2020 );
2021 if !have_ffmpeg() {
2022 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
2023 return;
2024 }
2025 let theirs = ffmpeg_decode_luma(&stream, width, height);
2026 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
2027 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2028 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2029 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
2030 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2031 panic!(
2032 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2033 at % width,
2034 at / width,
2035 got[at],
2036 b[at],
2037 );
2038 }
2039 }
2040 }
2041
2042 // Every tile layout this encoder can write decodes SAMPLE-EXACT
2043 // through both decoders -- ours and ffmpeg's -- and the frames really
2044 // carry the tiles the header claims (the OBU parser locates one payload
2045 // per tile, so a stream that quietly stayed single-tile fails here
2046 // rather than passing on a green round trip).
2047 //
2048 // The bytes are what the gate is on: an encoder that clipped its
2049 // neighbour availability wrong writes a stream whose two decoders agree
2050 // with each other and disagree with nothing -- so the ffmpeg half is
2051 // the one that catches a tile boundary the writer respected and the
2052 // spec does not, and the parser half catches the reverse.
2053
2054 /// A STATIC clip: every inter frame predicts perfectly from the last, so
2055 /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead
2056 /// of coding four 32x32 quadrants, and the stream both decoders
2057 /// reconstruct is still sample-exact against the encoder's own
2058 /// reconstruction. The counter is the point (class
2059 /// `gate-blind-to-feature`): without it a green three-way compare says
2060 /// nothing about whether a single 64x64 block was ever written.
2061 /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK.
2062 /// Every partition decision below the root is the one the 64-superblock
2063 /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the
2064 /// four 64x64 superblocks -- so the only thing this proves is the
2065 /// structural syntax: the root's own partition symbol, its loop
2066 /// restoration read once over the 128 span at the 128 unit size, and
2067 /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks
2068 /// per frame over three frames, so the root fires 6 times.
2069 ///
2070 /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global
2071 /// (the superblock size is a sequence field), so this gate runs alone:
2072 ///
2073 /// Runs only inside `superblock_size_global_suite`.
2074 pub(crate) fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() {
2075 let _knobs = crate::speed::knob_write();
2076 let _gate_lock = crate::stream::tests::lock_gate_counters();
2077 crate::encode::force_sb128(true);
2078 let (width, height) = (256usize, 128usize);
2079 let still = test_card(width, height, 0);
2080 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
2081 let config = EncoderConfig {
2082 width,
2083 height,
2084 base_q_idx: 120,
2085 gop: 8,
2086 colour: Colour::Bt709Limited,
2087 tile_cols_log2: 0,
2088 tile_rows_log2: 0,
2089 };
2090 let mut enc = Av1Encoder::new(config).unwrap();
2091 let mut stream = Vec::new();
2092 let _ = crate::tile::take_sb128_root_hits();
2093 for packet in encode_all(&mut enc, &sources) {
2094 stream.extend_from_slice(&packet.data);
2095 }
2096 let roots = crate::tile::take_sb128_root_hits();
2097 assert!(
2098 roots >= 4,
2099 "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4"
2100 );
2101 eprintln!("128x128 superblock roots: {roots}");
2102
2103 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2104 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2105 assert!(
2106 crate::decode::part128_split_hits() >= 4,
2107 "our decoder read no 128x128 superblock root"
2108 );
2109 if !have_ffmpeg() {
2110 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2111 return;
2112 }
2113 let theirs = ffmpeg_decode_luma(&stream, width, height);
2114 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2115 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2116 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2117 assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree");
2118 }
2119 }
2120
2121 #[test]
2122 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {
2123 let _knobs = crate::speed::knob_write();
2124 let _gate_lock = crate::stream::tests::lock_gate_counters();
2125 let (width, height) = (256usize, 128usize);
2126 let still = test_card(width, height, 0);
2127 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
2128 let config = EncoderConfig {
2129 width,
2130 height,
2131 base_q_idx: 120,
2132 gop: 8,
2133 colour: Colour::Bt709Limited,
2134 tile_cols_log2: 0,
2135 tile_rows_log2: 0,
2136 };
2137 let mut enc = Av1Encoder::new(config).unwrap();
2138 let mut stream = Vec::new();
2139 let _ = crate::encode::take_b64_root_hits();
2140 for packet in encode_all(&mut enc, &sources) {
2141 stream.extend_from_slice(&packet.data);
2142 }
2143 let roots = crate::encode::take_b64_root_hits();
2144 // 8 superblocks per frame, two inter frames.
2145 assert!(
2146 roots > 0,
2147 "a static clip coded no 64x64 root at all (of 16 inter superblocks)"
2148 );
2149 eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks");
2150
2151 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2152 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2153 if !have_ffmpeg() {
2154 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2155 return;
2156 }
2157 let theirs = ffmpeg_decode_luma(&stream, width, height);
2158 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2159 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2160 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2161 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2162 panic!(
2163 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2164 at % width,
2165 at / width,
2166 got[at],
2167 b[at],
2168 );
2169 }
2170 assert_eq!(
2171 got.len(),
2172 b.len(),
2173 "frame {i}: luma is {} samples, ffmpeg's is {}",
2174 got.len(),
2175 b.len()
2176 );
2177 }
2178 }
2179
2180 /// The same clip with a DC step between frames (lane-tx64): the 64x64
2181 /// root still predicts the whole superblock from the last frame, but the
2182 /// prediction is uniformly off, so the root's NON-skip arm -- one
2183 /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below
2184 /// its skip arm and a 64x64 residual is really written. The counter is
2185 /// the gate (class `gate-blind-to-feature`; the static clip above cannot
2186 /// reach this arm at all because its prediction is exact), and both
2187 /// decoders have to reconstruct those coefficients sample-exact -- a
2188 /// writer that names the wrong coefficient set or the wrong `txfm_split`
2189 /// desyncs the whole tile here.
2190 #[test]
2191 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
2192 let _knobs = crate::speed::knob_write();
2193 let _gate_lock = crate::stream::tests::lock_gate_counters();
2194 let (width, height) = (256usize, 128usize);
2195 let still = test_card(width, height, 0);
2196 let sources: Vec<Picture> = (0..3)
2197 .map(|t| {
2198 let mut p = still.clone();
2199 let step = (t * 6) as u16;
2200 for v in &mut p.y {
2201 *v = (*v + step).min(255);
2202 }
2203 p
2204 })
2205 .collect();
2206 let config = EncoderConfig {
2207 width,
2208 height,
2209 base_q_idx: 120,
2210 gop: 8,
2211 colour: Colour::Bt709Limited,
2212 tile_cols_log2: 0,
2213 tile_rows_log2: 0,
2214 };
2215 let mut enc = Av1Encoder::new(config).unwrap();
2216 let mut stream = Vec::new();
2217 let _ = crate::encode::take_b64_residual_hits();
2218 for packet in encode_all(&mut enc, &sources) {
2219 stream.extend_from_slice(&packet.data);
2220 }
2221 let residuals = crate::encode::take_b64_residual_hits();
2222 assert!(
2223 residuals > 0,
2224 "a DC-stepped clip coded no 64x64 root with a residual at all"
2225 );
2226 eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks");
2227
2228 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2229 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2230 if !have_ffmpeg() {
2231 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2232 return;
2233 }
2234 let theirs = ffmpeg_decode_luma(&stream, width, height);
2235 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2236 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2237 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2238 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2239 panic!(
2240 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2241 at % width,
2242 at / width,
2243 got[at],
2244 b[at],
2245 );
2246 }
2247 assert_eq!(
2248 got.len(),
2249 b.len(),
2250 "frame {i}: luma is {} samples, ffmpeg's is {}",
2251 got.len(),
2252 b.len()
2253 );
2254 }
2255 }
2256
2257 /// A frame whose size is NOT a multiple of a superblock (lane-b64b):
2258 /// 232x168 leaves the last superblock column and row cut by the true
2259 /// frame edge, with more than half of each inside -- which is exactly
2260 /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films
2261 /// are superblock-aligned, so nothing but a synthetic size reaches this
2262 /// path at all (class `gate-blind-to-feature`), and the user's own
2263 /// exports are arbitrary sizes.
2264 #[test]
2265 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {
2266 let _knobs = crate::speed::knob_write();
2267 let _gate_lock = crate::stream::tests::lock_gate_counters();
2268 let (width, height) = (232usize, 168usize);
2269 let still = test_card(width, height, 0);
2270 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
2271 let config = EncoderConfig {
2272 width,
2273 height,
2274 base_q_idx: 120,
2275 gop: 8,
2276 colour: Colour::Bt709Limited,
2277 tile_cols_log2: 0,
2278 tile_rows_log2: 0,
2279 };
2280 let mut enc = Av1Encoder::new(config).unwrap();
2281 let mut stream = Vec::new();
2282 let _ = crate::encode::take_b64_edge_hits();
2283 for packet in encode_all(&mut enc, &sources) {
2284 stream.extend_from_slice(&packet.data);
2285 }
2286 let edges = crate::encode::take_b64_edge_hits();
2287 assert!(
2288 edges > 0,
2289 "no 64x64 root was taken at a superblock the frame edge cuts"
2290 );
2291 eprintln!("edge 64x64 roots: {edges}");
2292
2293 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2294 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2295 if !have_ffmpeg() {
2296 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2297 return;
2298 }
2299 let theirs = ffmpeg_decode_luma(&stream, width, height);
2300 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2301 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
2302 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
2303 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
2304 panic!(
2305 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2306 at % width,
2307 at / width,
2308 got[at],
2309 theirs_i[at],
2310 );
2311 }
2312 assert_eq!(
2313 got.len(),
2314 theirs_i.len(),
2315 "frame {i}: luma is {} samples, ffmpeg's is {}",
2316 got.len(),
2317 theirs_i.len()
2318 );
2319 }
2320 }
2321
2322 /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three
2323 /// whole superblock columns and 1.6875 superblock rows, so the bottom
2324 /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b
2325 /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8)
2326 /// leaves it did not. Every one of them is now scored over its inside
2327 /// part alone, and a distortion change that moved a partition or a
2328 /// transform decision the writer did not follow would desync the tile, so
2329 /// both decoders reconstruct it sample-exact.
2330 #[test]
2331 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {
2332 let _knobs = crate::speed::knob_write();
2333 let _gate_lock = crate::stream::tests::lock_gate_counters();
2334 let (width, height) = (384usize, 216usize);
2335 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();
2336 let config = EncoderConfig {
2337 width,
2338 height,
2339 base_q_idx: 120,
2340 gop: 8,
2341 colour: Colour::Bt709Limited,
2342 tile_cols_log2: 0,
2343 tile_rows_log2: 0,
2344 };
2345 let mut enc = Av1Encoder::new(config).unwrap();
2346 let mut stream = Vec::new();
2347 for packet in encode_all(&mut enc, &sources) {
2348 stream.extend_from_slice(&packet.data);
2349 }
2350 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2351 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2352 if !have_ffmpeg() {
2353 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2354 return;
2355 }
2356 let theirs = ffmpeg_decode_luma(&stream, width, height);
2357 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2358 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
2359 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
2360 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
2361 panic!(
2362 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2363 at % width,
2364 at / width,
2365 got[at],
2366 theirs_i[at],
2367 );
2368 }
2369 assert_eq!(
2370 got.len(),
2371 theirs_i.len(),
2372 "frame {i}: luma is {} samples, ffmpeg's is {}",
2373 got.len(),
2374 theirs_i.len()
2375 );
2376 }
2377 }
2378
2379 /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every
2380 /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is
2381 /// off by exactly the detail a TX_64X64 throws away (it codes only the
2382 /// top-left 32x32 corner of its coefficient space) and the root's var-tx
2383 /// arm splits its luma into four TX_32X32 units instead. The counter is
2384 /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the
2385 /// reader does not expect desyncs the whole tile, so both decoders have
2386 /// to reconstruct it sample-exact.
2387 #[test]
2388 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {
2389 let _knobs = crate::speed::knob_write();
2390 let _gate_lock = crate::stream::tests::lock_gate_counters();
2391 let (width, height) = (256usize, 128usize);
2392 let still = test_card(width, height, 0);
2393 let sources: Vec<Picture> = (0..4)
2394 .map(|t| {
2395 let mut p = still.clone();
2396 for (i, v) in p.y.iter_mut().enumerate() {
2397 let checker = ((i % width) / 4 + (i / width) / 4) % 2;
2398 let bump = (t * 5 * (checker + 1)) as u16;
2399 *v = (*v + bump).min(255);
2400 }
2401 p
2402 })
2403 .collect();
2404 let config = EncoderConfig {
2405 width,
2406 height,
2407 base_q_idx: 90,
2408 gop: 8,
2409 colour: Colour::Bt709Limited,
2410 tile_cols_log2: 0,
2411 tile_rows_log2: 0,
2412 };
2413 let mut enc = Av1Encoder::new(config).unwrap();
2414 let mut stream = Vec::new();
2415 let _ = crate::encode::take_b64_var_tx_hits();
2416 for packet in encode_all(&mut enc, &sources) {
2417 stream.extend_from_slice(&packet.data);
2418 }
2419 let split = crate::encode::take_b64_var_tx_hits();
2420 assert!(split > 0, "no 64x64 root split its luma transform at all");
2421 eprintln!("64x64 roots with a SPLIT luma transform: {split}");
2422
2423 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2424 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2425 if !have_ffmpeg() {
2426 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2427 return;
2428 }
2429 let theirs = ffmpeg_decode_luma(&stream, width, height);
2430 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2431 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
2432 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
2433 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
2434 panic!(
2435 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2436 at % width,
2437 at / width,
2438 got[at],
2439 theirs_i[at],
2440 );
2441 }
2442 assert_eq!(
2443 got.len(),
2444 theirs_i.len(),
2445 "frame {i}: luma is {} samples, ffmpeg's is {}",
2446 got.len(),
2447 theirs_i.len()
2448 );
2449 }
2450 }
2451
2452 /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two
2453 /// stills, so on a leaf frame the average of its past (`LAST`) and future
2454 /// (`ALTREF`) references IS the source and neither reference alone is --
2455 /// exactly the content a COMPOUND 64x64 root pays on. The counter is the
2456 /// gate (class `gate-blind-to-feature`): without it a green three-way
2457 /// compare says nothing about whether one compound root was written, and
2458 /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no
2459 /// `motion_mode` symbol) desyncs the whole tile if it is wrong.
2460 #[test]
2461 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {
2462 let _knobs = crate::speed::knob_write();
2463 let _gate_lock = crate::stream::tests::lock_gate_counters();
2464 let (width, height) = (256usize, 128usize);
2465 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));
2466 let sources: Vec<Picture> = (0..9)
2467 .map(|t| {
2468 let mut p = a.clone();
2469 let w = t as u32;
2470 for (v, &other) in p.y.iter_mut().zip(&b.y) {
2471 *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16;
2472 }
2473 p
2474 })
2475 .collect();
2476 let config = EncoderConfig {
2477 width,
2478 height,
2479 base_q_idx: 120,
2480 gop: 9,
2481 colour: Colour::Bt709Limited,
2482 tile_cols_log2: 0,
2483 tile_rows_log2: 0,
2484 };
2485 let mut enc = Av1Encoder::new(config).unwrap();
2486 let mut stream = Vec::new();
2487 let _ = crate::encode::take_b64_compound_hits();
2488 for packet in encode_all(&mut enc, &sources) {
2489 stream.extend_from_slice(&packet.data);
2490 }
2491 let compound = crate::encode::take_b64_compound_hits();
2492 assert!(
2493 compound > 0,
2494 "a crossfade clip coded no COMPOUND 64x64 root at all"
2495 );
2496 eprintln!("compound 64x64 roots on a crossfade clip: {compound}");
2497
2498 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2499 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2500 if !have_ffmpeg() {
2501 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2502 return;
2503 }
2504 let theirs = ffmpeg_decode_luma(&stream, width, height);
2505 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2506 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
2507 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
2508 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
2509 panic!(
2510 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2511 at % width,
2512 at / width,
2513 got[at],
2514 theirs_i[at],
2515 );
2516 }
2517 assert_eq!(
2518 got.len(),
2519 theirs_i.len(),
2520 "frame {i}: luma is {} samples, ffmpeg's is {}",
2521 got.len(),
2522 theirs_i.len()
2523 );
2524 }
2525 }
2526
2527 #[test]
2528 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
2529 let _knobs = crate::speed::knob_read();
2530 let (width, height) = (640usize, 384usize);
2531 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
2532 let mut sizes = Vec::new();
2533 for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
2534 let config = EncoderConfig {
2535 width,
2536 height,
2537 base_q_idx: 120,
2538 gop: 4,
2539 colour: Colour::Bt709Limited,
2540 tile_cols_log2: cols_log2,
2541 tile_rows_log2: rows_log2,
2542 };
2543 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
2544 // lane-b128m: the SPEC's uniform spacing derives the tile count
2545 // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`),
2546 // so a frame with fewer superblock columns than the requested
2547 // count codes fewer tiles -- which is what a 128-superblock
2548 // sequence does here. The grid the encoder itself computes is the
2549 // expectation; at 64 superblocks it is `1 << log2` exactly.
2550 let grid = crate::tile::TileLayout::new(
2551 (width as u32).div_ceil(4),
2552 (height as u32).div_ceil(4),
2553 cols_log2,
2554 rows_log2,
2555 );
2556 let (want_cols, want_rows) = (grid.cols(), grid.rows());
2557 let mut enc = Av1Encoder::new(config).unwrap();
2558 let mut stream = Vec::new();
2559 for packet in encode_all(&mut enc, &sources) {
2560 stream.extend_from_slice(&packet.data);
2561 }
2562 sizes.push((layout.clone(), stream.len()));
2563
2564 // The frames carry the tiles their headers claim.
2565 let mut parser = ec_av1_syntax::Av1Parser::new();
2566 let mut frames = 0usize;
2567 let mut offset = 0usize;
2568 while offset < stream.len() {
2569 let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
2570 let unit: usize = obus.iter().map(|o| o.total_size).sum();
2571 for obu in &obus {
2572 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
2573 assert_eq!(
2574 (parsed.tile_info.cols, parsed.tile_info.rows),
2575 (want_cols, want_rows),
2576 "{layout}: the header's own tile grid"
2577 );
2578 assert_eq!(
2579 tiles.len(),
2580 (want_cols * want_rows) as usize,
2581 "{layout}: tile payloads located in the tile group"
2582 );
2583 frames += 1;
2584 }
2585 }
2586 offset += unit;
2587 }
2588 assert_eq!(frames, sources.len(), "{layout}: coded frames");
2589
2590 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2591 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
2592 if !have_ffmpeg() {
2593 eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
2594 continue;
2595 }
2596 let theirs = ffmpeg_decode_luma(&stream, width, height);
2597 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
2598 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2599 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2600 assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
2601 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2602 panic!(
2603 "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2604 at % width,
2605 at / width,
2606 got[at],
2607 b[at],
2608 );
2609 }
2610 }
2611 }
2612 let base = sizes[0].1 as f64;
2613 for (layout, bytes) in &sizes {
2614 eprintln!(
2615 "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
2616 (*bytes as f64 / base - 1.0) * 100.0
2617 );
2618 }
2619 }
2620
2621 /// lane-deltaq's three-way witness: a clip with a real gradient of tpl
2622 /// factors -- a moving detail region over a flat background, so the
2623 /// superblocks the NEXT picture predicts from are worth more than the
2624 /// ones it does not -- codes at least two distinct per-superblock
2625 /// quantizer levels (the fire count, class `gate-blind-to-feature`), and
2626 /// both decoders reconstruct every frame sample-exact from the
2627 /// `delta_qindex` syntax that carries them.
2628 #[test]
2629 fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() {
2630 // `knob_write`, not `knob_read`: the override below is
2631 // process-global and every other test's bytes move under it.
2632 let _knobs = crate::speed::knob_write();
2633 let _gate_lock = crate::stream::tests::lock_gate_counters();
2634 crate::encode::set_deltaq_res(Some(2));
2635 let (width, height) = (640usize, 384usize);
2636 // The gate's own moving test card, with a 128x128 patch of fine
2637 // detail travelling right by 32 samples a frame laid over it: the
2638 // patch is what the tpl pass finds worth propagating and the card
2639 // around it is not, so the map -- and with it the quantizer grid --
2640 // is a gradient and not one flat number.
2641 let sources: Vec<Picture> = (0..4)
2642 .map(|t| {
2643 let mut p = test_card(width, height, t * 3);
2644 let x0 = 32 + t * 32;
2645 for y in 128..256 {
2646 for x in x0..x0 + 128 {
2647 p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
2648 }
2649 }
2650 p
2651 })
2652 .collect();
2653 let config = EncoderConfig {
2654 width,
2655 height,
2656 base_q_idx: 120,
2657 gop: 4,
2658 colour: Colour::Bt709Limited,
2659 tile_cols_log2: 0,
2660 tile_rows_log2: 0,
2661 };
2662 let mut enc = Av1Encoder::new(config).unwrap();
2663 let _ = crate::encode::take_deltaq_levels();
2664 let mut stream = Vec::new();
2665 for packet in encode_all(&mut enc, &sources) {
2666 stream.extend_from_slice(&packet.data);
2667 }
2668 let levels = crate::encode::take_deltaq_levels();
2669 // The quantizer grid rides the tpl map, and `speed::TPL_DEPTH` cuts
2670 // the lookahead window to one picture at the top presets, so there IS
2671 // no map -- and no delta_q syntax -- there. The exactness half below
2672 // still runs; only the fire count needs a window (lane-tplwin: the
2673 // predicate is the window, not preset 0, since presets 1..6 have one).
2674 if crate::speed::at(&crate::speed::TPL_DEPTH) > 1 {
2675 assert!(
2676 levels >= 2,
2677 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
2678 );
2679 } else {
2680 eprintln!(
2681 "SKIP the fire count at preset {}: no tpl map",
2682 crate::speed::speed()
2683 );
2684 }
2685 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2686 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2687 if have_ffmpeg() {
2688 let theirs = ffmpeg_decode_luma(&stream, width, height);
2689 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2690 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2691 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2692 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2693 panic!(
2694 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2695 at % width,
2696 at / width,
2697 got[at],
2698 b[at],
2699 );
2700 }
2701 assert_eq!(
2702 got.len(),
2703 b.len(),
2704 "frame {i}: luma is {} samples, ffmpeg's is {}",
2705 got.len(),
2706 b.len()
2707 );
2708 }
2709 } else {
2710 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2711 }
2712 crate::encode::set_deltaq_res(None);
2713 eprintln!(
2714 "delta_q witness: {levels} quantizer levels, {} bytes",
2715 stream.len()
2716 );
2717 }
2718
2719 /// lane-txset's witness: a clip of hard directional edges makes the intra
2720 /// luma search take EVERY type of the five-type reduced set
2721 /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`,
2722 /// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature`
2723 /// -- and both decoders reconstruct every frame sample-exact from the
2724 /// `tx_type` symbols that name them. Before the lane the writer coded
2725 /// `DCT_DCT` for every luma transform unit ever written, so this is also
2726 /// the statement that the other four are REACHABLE at all.
2727 #[test]
2728 fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() {
2729 // `knob_write`: the screen override below is process-global, and the
2730 // type search is SCREEN-ONLY (`encode::tx_type_candidates`).
2731 let _knobs = crate::speed::knob_write();
2732 crate::encode::force_screen(Some(true));
2733 let _gate_lock = crate::stream::tests::lock_gate_counters();
2734 let (width, height) = (320usize, 192usize);
2735 // Sharp horizontal and vertical steps: a vertical edge is what an
2736 // `ADST` column pass beats a `DCT` one on, a horizontal edge the
2737 // mirror, and the flat/ramp areas between them are where `IDTX` wins.
2738 let sources: Vec<Picture> = (0..2)
2739 .map(|t| {
2740 let mut p = test_card(width, height, t * 3);
2741 for y in 0..height {
2742 for x in 0..width {
2743 let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) {
2744 (0, 0) => 16u16,
2745 (1, 0) => 235,
2746 (0, 1) => (x % 64 * 3) as u16,
2747 _ => (y % 64 * 3) as u16,
2748 };
2749 p.y[y * width + x] = v;
2750 }
2751 }
2752 p
2753 })
2754 .collect();
2755 let config = EncoderConfig {
2756 width,
2757 height,
2758 base_q_idx: 90,
2759 gop: 2,
2760 colour: Colour::Bt709Limited,
2761 tile_cols_log2: 0,
2762 tile_rows_log2: 0,
2763 };
2764 let mut enc = Av1Encoder::new(config).unwrap();
2765 let _ = crate::encode::take_tx_type_hits();
2766 let mut stream = Vec::new();
2767 for packet in encode_all(&mut enc, &sources) {
2768 stream.extend_from_slice(&packet.data);
2769 }
2770 let hits = crate::encode::take_tx_type_hits();
2771 // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above
2772 // the presets that carry it only `DCT_DCT` is offered, and the
2773 // exactness half below is what still runs there. The FULL five-type
2774 // fire count is preset 0's to make: a faster preset prunes modes and
2775 // partitions before a type is ever priced on them, so `ADST_ADST` and
2776 // `IDTX` stop winning on this clip at preset 6 (measured: hits
2777 // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever
2778 // still has to reach SOME non-`DCT_DCT` type -- that is the
2779 // "reachable at all" statement, class `gate-blind-to-feature`.
2780 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) {
2781 let non_dct: usize =
2782 hits.iter().sum::<usize>() - hits[crate::transform::TxType::DctDct as usize];
2783 assert!(
2784 non_dct > 0,
2785 "every luma transform unit took DCT_DCT: {hits:?}"
2786 );
2787 }
2788 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
2789 for (name, ty) in [
2790 ("DCT_DCT", crate::transform::TxType::DctDct),
2791 ("ADST_ADST", crate::transform::TxType::AdstAdst),
2792 ("ADST_DCT", crate::transform::TxType::AdstDct),
2793 ("DCT_ADST", crate::transform::TxType::DctAdst),
2794 ("IDTX", crate::transform::TxType::Idtx),
2795 ] {
2796 assert!(
2797 hits[ty as usize] > 0,
2798 "no luma transform unit took {name}: {hits:?}"
2799 );
2800 }
2801 } else {
2802 eprintln!(
2803 "SKIP the five-type fire count at preset {}: {hits:?}",
2804 crate::speed::speed()
2805 );
2806 }
2807 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2808 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2809 if have_ffmpeg() {
2810 let theirs = ffmpeg_decode_luma(&stream, width, height);
2811 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2812 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2813 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2814 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2815 panic!(
2816 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2817 at % width,
2818 at / width,
2819 got[at],
2820 b[at],
2821 );
2822 }
2823 assert_eq!(
2824 got.len(),
2825 b.len(),
2826 "frame {i}: luma is {} samples, ffmpeg's is {}",
2827 got.len(),
2828 b.len()
2829 );
2830 }
2831 } else {
2832 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2833 }
2834 crate::encode::force_screen(None);
2835 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());
2836 }
2837
2838 /// lane-txset2's witness: an INTER frame's luma transform units take BOTH
2839 /// types of the two-type inter set the writer already codes a symbol for
2840 /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire
2841 /// count, class `gate-blind-to-feature` -- and both decoders reconstruct
2842 /// every frame sample-exact from the `tx_type` symbols that name them.
2843 /// Before this lane every inter luma unit was coded `DCT_DCT`.
2844 #[test]
2845 fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() {
2846 // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so
2847 // this turns it on process-globally under the same exclusive lock the
2848 // presets take.
2849 let _knobs = crate::speed::knob_write();
2850 let _gate_lock = crate::stream::tests::lock_gate_counters();
2851 crate::encode::set_inter_tx_search(Some(true));
2852 let (width, height) = (320usize, 192usize);
2853 // Sharp steps that MOVE: the motion-compensated residual along a
2854 // moving edge is exactly where the identity transform beats a DCT,
2855 // and the flat plateaus between them predict to nothing at all.
2856 let sources: Vec<Picture> = (0..4)
2857 .map(|t| {
2858 let mut p = test_card(width, height, t * 3);
2859 for y in 0..height {
2860 for x in 0..width {
2861 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
2862 (0, 0) => 16u16,
2863 (1, 0) => 235,
2864 (0, 1) => ((x + t) % 64 * 3) as u16,
2865 _ => ((y + t) % 64 * 3) as u16,
2866 };
2867 p.y[y * width + x] = v;
2868 }
2869 }
2870 p
2871 })
2872 .collect();
2873 let config = EncoderConfig {
2874 width,
2875 height,
2876 base_q_idx: 90,
2877 gop: 4,
2878 colour: Colour::Bt709Limited,
2879 tile_cols_log2: 0,
2880 tile_rows_log2: 0,
2881 };
2882 let mut enc = Av1Encoder::new(config).unwrap();
2883 let _ = crate::encode::take_inter_tx_type_hits();
2884 let mut stream = Vec::new();
2885 for packet in encode_all(&mut enc, &sources) {
2886 stream.extend_from_slice(&packet.data);
2887 }
2888 let hits = crate::encode::take_inter_tx_type_hits();
2889 crate::encode::set_inter_tx_search(None);
2890 for (name, ty) in [
2891 ("DCT_DCT", crate::transform::TxType::DctDct),
2892 ("IDTX", crate::transform::TxType::Idtx),
2893 ] {
2894 assert!(
2895 hits[ty as usize] > 0,
2896 "no inter luma transform unit was CODED {name}: {hits:?}"
2897 );
2898 }
2899 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2900 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
2901 if have_ffmpeg() {
2902 let theirs = ffmpeg_decode_luma(&stream, width, height);
2903 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
2904 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2905 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2906 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2907 panic!(
2908 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
2909 at % width,
2910 at / width,
2911 got[at],
2912 b[at],
2913 );
2914 }
2915 assert_eq!(
2916 got.len(),
2917 b.len(),
2918 "frame {i}: luma is {} samples, ffmpeg's is {}",
2919 got.len(),
2920 b.len()
2921 );
2922 }
2923 } else {
2924 eprintln!("SKIP the ffmpeg half: no ffmpeg");
2925 }
2926 eprintln!(
2927 "inter tx_type witness: hits {hits:?}, {} bytes",
2928 stream.len()
2929 );
2930 }
2931
2932 /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER
2933 /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra
2934 /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below --
2935 /// and both decoders reconstruct every frame sample-exact from them. The
2936 /// statement is that the types only those alphabets can NAME (`V_DCT`,
2937 /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are
2938 /// reachable at all, and that the header bit, the writer's set map and
2939 /// the search's pricer agree on which alphabet a symbol was coded into
2940 /// (class `wrong-alphabet-same-value`: a disagreement here changes no
2941 /// symbol VALUE and desyncs the arithmetic coder anyway).
2942 #[test]
2943 #[ignore = "sets process-global search levers: run it alone"]
2944 fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() {
2945 // Every lever below is process-global: the same exclusive lock the
2946 // presets take.
2947 let _knobs = crate::speed::knob_write();
2948 let _gate_lock = crate::stream::tests::lock_gate_counters();
2949 crate::encode::set_intra_tx_search(Some(true));
2950 crate::encode::set_inter_tx_search(Some(true));
2951 crate::encode::set_wide_tx_set(Some(true));
2952 let (width, height) = (320usize, 192usize);
2953 // The same moving hard-edge card the two narrow-set witnesses use:
2954 // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the
2955 // ramps are `ADST`'s and the moving plateaus `IDTX`'s.
2956 let sources: Vec<Picture> = (0..4)
2957 .map(|t| {
2958 let mut p = test_card(width, height, t * 3);
2959 for y in 0..height {
2960 for x in 0..width {
2961 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
2962 (0, 0) => 16u16,
2963 (1, 0) => 235,
2964 (0, 1) => ((x + t) % 64 * 3) as u16,
2965 _ => ((y + t) % 64 * 3) as u16,
2966 };
2967 p.y[y * width + x] = v;
2968 }
2969 }
2970 p
2971 })
2972 .collect();
2973 let config = EncoderConfig {
2974 width,
2975 height,
2976 base_q_idx: 90,
2977 gop: 4,
2978 colour: Colour::Bt709Limited,
2979 tile_cols_log2: 0,
2980 tile_rows_log2: 0,
2981 };
2982 let mut enc = Av1Encoder::new(config).unwrap();
2983 let _ = crate::encode::take_tx_type_hits();
2984 let _ = crate::encode::take_inter_tx_type_hits();
2985 let mut stream = Vec::new();
2986 for packet in encode_all(&mut enc, &sources) {
2987 stream.extend_from_slice(&packet.data);
2988 }
2989 let (intra, inter) = (
2990 crate::encode::take_tx_type_hits(),
2991 crate::encode::take_inter_tx_type_hits(),
2992 );
2993 crate::encode::set_wide_tx_set(None);
2994 crate::encode::set_inter_tx_search(None);
2995 crate::encode::set_intra_tx_search(None);
2996 eprintln!(
2997 "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes",
2998 stream.len()
2999 );
3000 // The fire count is preset 0's, for the reason the five-type witness
3001 // spells out: a faster preset prunes the modes and partitions a type
3002 // wins on before it is ever priced (class `gate-blind-to-feature`).
3003 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
3004 use crate::transform::TxType;
3005 let wide_only = |hits: &[usize; 16]| -> usize {
3006 hits[TxType::VDct as usize] + hits[TxType::HDct as usize]
3007 };
3008 assert!(
3009 wide_only(&intra) > 0,
3010 "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}"
3011 );
3012 // The INTER units of this same frame are coded into the
3013 // twelve/sixteen-symbol alphabets too (the header bit widens
3014 // every luma set at once), but their SEARCH still offers the
3015 // two-type list -- see `encode::inter_luma_set`'s note on the
3016 // reference-slot refusal the wider inter candidates trip. So the
3017 // statement here is that those units still decode sample-exact
3018 // out of the wider alphabet, which the two decoders below make.
3019 assert!(
3020 inter.iter().sum::<usize>() > 0,
3021 "the clip coded no inter luma transform unit at all: {inter:?}"
3022 );
3023 } else {
3024 eprintln!(
3025 "SKIP the wide-alphabet fire count at preset {}",
3026 crate::speed::speed()
3027 );
3028 }
3029 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3030 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3031 if have_ffmpeg() {
3032 let theirs = ffmpeg_decode_luma(&stream, width, height);
3033 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3034 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3035 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3036 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3037 panic!(
3038 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3039 at % width,
3040 at / width,
3041 got[at],
3042 b[at],
3043 );
3044 }
3045 assert_eq!(
3046 got.len(),
3047 b.len(),
3048 "frame {i}: luma is {} samples, ffmpeg's is {}",
3049 got.len(),
3050 b.len()
3051 );
3052 }
3053 } else {
3054 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3055 }
3056 }
3057 /// lane-intertx's witness: on a clip the screen detector calls
3058 /// NON-screen, the inter luma search offers the wider
3059 /// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit
3060 /// (a `coded > 0` guard on the committed-winners census, class
3061 /// `gate-blind-to-feature`), the block's chroma transforms inherit that
3062 /// type reduced to the chroma size's set against the frame's own honest
3063 /// header bit, and BOTH decoders reconstruct every frame sample-exact on
3064 /// ALL THREE planes -- chroma is the plane the inheritance desync
3065 /// corrupts, so luma-only comparisons cannot see it.
3066 #[test]
3067 #[ignore = "sets process-global search levers: run it alone"]
3068 fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() {
3069 let _knobs = crate::speed::knob_write();
3070 let _gate_lock = crate::stream::tests::lock_gate_counters();
3071 crate::encode::set_intra_tx_search(Some(true));
3072 crate::encode::set_inter_tx_search(Some(true));
3073 crate::encode::set_wide_tx_set(Some(true));
3074 crate::encode::force_screen(Some(false));
3075 let (width, height) = (320usize, 192usize);
3076 // The wide witness's moving card: vertical steps (where a 1-D
3077 // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated
3078 // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated
3079 // a few samples per frame so the inter search sees real motion.
3080 let sources: Vec<Picture> = (0..4)
3081 .map(|t| {
3082 let mut p = test_card(width, height, t * 3);
3083 for y in 0..height {
3084 for x in 0..width {
3085 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
3086 (0, 0) => 16u16,
3087 (1, 0) => 235,
3088 (0, 1) => ((x + t) % 64 * 3) as u16,
3089 _ => ((y + t) % 64 * 3) as u16,
3090 };
3091 p.y[y * width + x] = v;
3092 }
3093 }
3094 p
3095 })
3096 .collect();
3097 let config = EncoderConfig {
3098 width,
3099 height,
3100 base_q_idx: 90,
3101 gop: 4,
3102 colour: Colour::Bt709Limited,
3103 tile_cols_log2: 0,
3104 tile_rows_log2: 0,
3105 };
3106 let mut enc = Av1Encoder::new(config).unwrap();
3107 let _ = crate::encode::take_inter_tx_type_hits();
3108 let mut stream = Vec::new();
3109 for packet in encode_all(&mut enc, &sources) {
3110 stream.extend_from_slice(&packet.data);
3111 }
3112 let hits = crate::encode::take_inter_tx_type_hits();
3113 crate::encode::force_screen(None);
3114 crate::encode::set_wide_tx_set(None);
3115 crate::encode::set_inter_tx_search(None);
3116 crate::encode::set_intra_tx_search(None);
3117 use crate::transform::TxType;
3118 eprintln!(
3119 "inter wide-set witness: inter hits {hits:?}, {} bytes",
3120 stream.len()
3121 );
3122 assert!(
3123 hits[TxType::Idtx as usize] > 0,
3124 "no inter luma unit was CODED IDTX: {hits:?}"
3125 );
3126 assert!(
3127 hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0,
3128 "no inter luma unit was CODED a 1-D type -- the wider search \
3129 never fired on non-screen content (class gate-blind-to-feature): {hits:?}"
3130 );
3131 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3132 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3133 if have_ffmpeg() {
3134 let theirs = ffmpeg_decode_planes(&stream, width, height);
3135 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3136 let (cw, ch) = (width / 2, height / 2);
3137 for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() {
3138 for (name, got16, want, w) in [
3139 ("y", &a.y, y, width),
3140 ("u", &a.u, u, cw),
3141 ("v", &a.v, v, ch),
3142 ] {
3143 let got: Vec<u8> = got16.iter().map(|&s| s as u8).collect();
3144 assert_eq!(got.len(), want.len(), "frame {i} {name} plane size");
3145 if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) {
3146 panic!(
3147 "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}",
3148 at % w,
3149 at / w,
3150 got[at],
3151 want[at],
3152 );
3153 }
3154 }
3155 }
3156 } else {
3157 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3158 }
3159 }
3160
3161 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
3162 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
3163 /// its neighbour (a preset that changes no byte is a preset that buys no
3164 /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the
3165 /// full-search ones, which is the cheap in-suite statement of the byte
3166 /// pins' rule.
3167 ///
3168 /// Ignored by default because the preset is PROCESS-GLOBAL
3169 /// ([`crate::speed`]): flipping it while the suite's other tests encode
3170 /// in parallel would move their bytes under them. Run it on its own:
3171 /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`.
3172 #[test]
3173 #[ignore = "sets the process-global speed preset: run it alone"]
3174 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {
3175 let _knobs = crate::speed::knob_write();
3176 let _gate_lock = crate::stream::tests::lock_gate_counters();
3177 let (width, height) = (640usize, 384usize);
3178 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3179 let mut sizes: Vec<(u8, usize)> = Vec::new();
3180 for speed in [0u8, 3, 6, 10] {
3181 let config = EncoderConfig {
3182 width,
3183 height,
3184 base_q_idx: 120,
3185 gop: 4,
3186 colour: Colour::Bt709Limited,
3187 tile_cols_log2: 1,
3188 tile_rows_log2: 0,
3189 };
3190 let mut enc = Av1Encoder::with_speed(config, speed).unwrap();
3191 let mut stream = Vec::new();
3192 for packet in encode_all(&mut enc, &sources) {
3193 stream.extend_from_slice(&packet.data);
3194 }
3195 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3196 assert_eq!(
3197 ours.len(),
3198 sources.len(),
3199 "speed {speed}: our decoder's frames"
3200 );
3201 if have_ffmpeg() {
3202 let theirs = ffmpeg_decode_luma(&stream, width, height);
3203 assert_eq!(
3204 theirs.len(),
3205 sources.len(),
3206 "speed {speed}: ffmpeg's frames"
3207 );
3208 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3209 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3210 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3211 panic!(
3212 "speed {speed} frame {i}: luma differs first at ({}, {}): \
3213 ours {} vs ffmpeg {}",
3214 at % width,
3215 at / width,
3216 got[at],
3217 b[at],
3218 );
3219 }
3220 assert_eq!(
3221 got.len(),
3222 b.len(),
3223 "speed {speed} frame {i}: luma is {} samples, ffmpeg's is {}",
3224 got.len(),
3225 b.len()
3226 );
3227 }
3228 } else {
3229 eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
3230 }
3231 eprintln!(
3232 "speed {speed}: {} bytes [{}]",
3233 stream.len(),
3234 crate::speed::levers(speed).join(", ")
3235 );
3236 sizes.push((speed, stream.len()));
3237 }
3238 crate::speed::set_speed(0);
3239 for w in sizes.windows(2) {
3240 assert_ne!(
3241 w[0].1, w[1].1,
3242 "speed {} and {} coded the same bytes: the preset changed no decision",
3243 w[0].0, w[1].0
3244 );
3245 }
3246 }
3247
3248 /// What tiles and tile threads are worth at the size the editor exports
3249 /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
3250 /// per cell. Ignored by default (minutes).
3251 #[test]
3252 #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"]
3253 fn tile_wall_table_at_1080p() {
3254 let _knobs = crate::speed::knob_write();
3255 let _gate_lock = crate::stream::tests::lock_gate_counters();
3256 let (width, height) = (1920usize, 1080usize);
3257 let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else {
3258 return;
3259 };
3260 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
3261 let threadings = [1usize, 2, 4, 8];
3262 let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
3263 for pass in 0..2 {
3264 for &(cols_log2, rows_log2) in &layouts {
3265 for &threads in &threadings {
3266 crate::par::set_tile_threads(threads);
3267 let config = EncoderConfig {
3268 width,
3269 height,
3270 base_q_idx: 120,
3271 gop: 8,
3272 colour: Colour::Bt709Limited,
3273 tile_cols_log2: cols_log2,
3274 tile_rows_log2: rows_log2,
3275 };
3276 let mut enc = Av1Encoder::new(config).unwrap();
3277 let start = std::time::Instant::now();
3278 let mut bytes = 0usize;
3279 for packet in encode_all(&mut enc, &sources) {
3280 bytes += packet.data.len();
3281 }
3282 let wall = start.elapsed().as_secs_f64();
3283 let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
3284 match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
3285 Some(row) => row.2 = row.2.min(wall),
3286 None => table.push((name, threads, wall, bytes)),
3287 }
3288 let _ = pass;
3289 }
3290 }
3291 }
3292 crate::par::set_tile_threads(1);
3293 eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
3294 for (name, threads, wall, bytes) in &table {
3295 eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
3296 }
3297 }
3298
3299 /// The tiles of a frame are entropy-independent, so the bytes must not
3300 /// depend on how many workers wrote them: the same stream at one tile
3301 /// thread and at four, per layout.
3302 #[test]
3303 fn tile_bytes_do_not_depend_on_the_thread_count() {
3304 let _knobs = crate::speed::knob_write();
3305 let _gate_lock = crate::stream::tests::lock_gate_counters();
3306 let (width, height) = (320usize, 192usize);
3307 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
3308 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
3309 crate::par::set_tile_threads(threads);
3310 let config = EncoderConfig {
3311 width,
3312 height,
3313 base_q_idx: 120,
3314 gop: 3,
3315 colour: Colour::Bt709Limited,
3316 tile_cols_log2: cols_log2,
3317 tile_rows_log2: rows_log2,
3318 };
3319 let mut enc = Av1Encoder::new(config).unwrap();
3320 let mut stream = Vec::new();
3321 for packet in encode_all(&mut enc, &sources) {
3322 stream.extend_from_slice(&packet.data);
3323 }
3324 stream
3325 };
3326 for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
3327 let one = coded(1, cols_log2, rows_log2);
3328 let four = coded(4, cols_log2, rows_log2);
3329 assert_eq!(
3330 one,
3331 four,
3332 "{}x{} tiles: {} bytes at one thread, {} at four",
3333 1 << cols_log2,
3334 1 << rows_log2,
3335 one.len(),
3336 four.len()
3337 );
3338 }
3339 crate::par::set_tile_threads(1);
3340 }
3341
3342 /// What the per-tile search (lane-av1tsearch) is worth in wall and in
3343 /// frames per second at the editor's own export sizes: every tile layout
3344 /// crossed with every tile-thread count, plus librav1e at the matching
3345 /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
3346 /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
3347 /// the two kept, so a thermal drift cannot order the rows.
3348 ///
3349 /// Measurement, not a pass/fail gate: it asserts only that every cell
3350 /// produced a stream.
3351 #[test]
3352 // MEASURED 1243 s in release on a 12-core workstation. A 4-core server
3353 // cannot finish it at all: the same run TIMED OUT at 2400 s there
3354 // (12 frames x 2 passes x 12 cells), so the 8- and 12-thread rows are
3355 // only meaningful on a host with the cores to run them. Do not schedule
3356 // it on a 4-core fleet box.
3357 #[ignore = "wall measurement: 20 min at 1080p and it TIMES OUT on a 4-core host -- run it on >=8 cores"]
3358 fn tile_search_wall_1080p() {
3359 let _knobs = crate::speed::knob_write();
3360 tile_search_wall(
3361 1920,
3362 1080,
3363 12,
3364 &[(0, 0), (1, 0), (1, 1), (2, 1)],
3365 &[1, 2, 4, 8],
3366 );
3367 }
3368
3369 /// The same table at the 4K frame size the editor exports (3840x1608),
3370 /// at the two layouts with enough tiles to fill this box.
3371 #[test]
3372 #[ignore = "wall measurement: 12 min at 4K (732 s measured); run it with --ignored --nocapture"]
3373 fn tile_search_wall_4k() {
3374 let _knobs = crate::speed::knob_write();
3375 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
3376 }
3377
3378 /// lane-av1fpar: the frame-level FILTER stage is banded across the same
3379 /// workers the tile search uses (`par::override_filter_threads`), so the
3380 /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
3381 /// pieces. Every piece is a disjoint band of the same integers, so the
3382 /// stream must not move -- at a size that crops and is several superblock
3383 /// rows tall, which is what makes the bands non-trivial.
3384 #[test]
3385 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
3386 let _knobs = crate::speed::knob_write();
3387 let _gate_lock = crate::stream::tests::lock_gate_counters();
3388 let (width, height) = (384usize, 288usize);
3389 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3390 let coded = |threads: usize| {
3391 crate::par::set_tile_threads(threads);
3392 let config = EncoderConfig {
3393 width,
3394 height,
3395 base_q_idx: 120,
3396 gop: 2,
3397 colour: Colour::Bt709Limited,
3398 tile_cols_log2: 0,
3399 tile_rows_log2: 0,
3400 };
3401 let mut enc = Av1Encoder::new(config).unwrap();
3402 let mut stream = Vec::new();
3403 for packet in encode_all(&mut enc, &sources) {
3404 stream.extend_from_slice(&packet.data);
3405 }
3406 stream
3407 };
3408 // One tile, so only the filter stage can differ between these.
3409 let one = coded(1);
3410 for threads in [2usize, 4, 8] {
3411 assert_eq!(
3412 one,
3413 coded(threads),
3414 "the filter stage moved at {threads} threads"
3415 );
3416 }
3417 crate::par::set_tile_threads(1);
3418 }
3419
3420 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
3421 /// the loop filters on one captured reconstruction instead of decoding
3422 /// the coded tile again per candidate. The replay must be that decode,
3423 /// byte for byte -- including at a size that CROPS (1080 and 1608 both
3424 /// pad to a superblock row, i.e. every export size the editor uses),
3425 /// which is the arm this lane opened.
3426 #[test]
3427 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
3428 let _knobs = crate::speed::knob_read();
3429 let _gate_lock = crate::stream::tests::lock_gate_counters();
3430 let run = |width: usize, height: usize, off: bool| {
3431 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3432 crate::decode::set_filter_replay_disabled(off);
3433 let config = EncoderConfig {
3434 width,
3435 height,
3436 base_q_idx: 120,
3437 gop: 2,
3438 colour: Colour::Bt709Limited,
3439 tile_cols_log2: 0,
3440 tile_rows_log2: 0,
3441 };
3442 let mut enc = Av1Encoder::new(config).unwrap();
3443 let mut stream = Vec::new();
3444 for packet in encode_all(&mut enc, &sources) {
3445 stream.extend_from_slice(&packet.data);
3446 }
3447 crate::decode::set_filter_replay_disabled(false);
3448 stream
3449 };
3450 // 320x160 crops (the coding surface is 320x192, one superblock row
3451 // taller); 320x192 is a whole number of superblocks, the shape the
3452 // replay already covered.
3453 for (width, height) in [(320usize, 160usize), (320, 192)] {
3454 let replayed = run(width, height, false);
3455 let decoded = run(width, height, true);
3456 assert_eq!(
3457 replayed,
3458 decoded,
3459 "{width}x{height}: the filter replay is not the decode it stands in for \
3460 ({} bytes replayed, {} decoded)",
3461 replayed.len(),
3462 decoded.len(),
3463 );
3464 }
3465 }
3466
3467 /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced
3468 /// the capture decode -- against that decode. `set_verify_final_replay`
3469 /// makes `encode::pick_and_apply_filters` run both on every frame and
3470 /// assert, per frame, that the spliced picture and the two filter stages
3471 /// the loop-restoration search reads are bit-identical.
3472 #[test]
3473 fn filter_replay_final_matches_the_capture_decode() {
3474 let _knobs = crate::speed::knob_read();
3475 let _gate_lock = crate::stream::tests::lock_gate_counters();
3476 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {
3477 let config = EncoderConfig {
3478 width,
3479 height,
3480 base_q_idx: 120,
3481 gop: 2,
3482 colour: Colour::Bt709Limited,
3483 tile_cols_log2: tiles.0,
3484 tile_rows_log2: tiles.1,
3485 };
3486 let mut enc = Av1Encoder::new(config).unwrap();
3487 for packet in encode_all(&mut enc, sources) {
3488 assert!(!packet.data.is_empty());
3489 }
3490 };
3491 crate::decode::set_verify_final_replay(true);
3492 // 320x160 crops (its coding surface is one superblock row taller);
3493 // 320x192 is a whole number of superblocks.
3494 for (width, height) in [(320usize, 160usize), (320, 192)] {
3495 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3496 run(&sources, width, height, (0, 0));
3497 }
3498 // Real gate content, where the CDEF preset search actually chooses
3499 // `bits > 0` and the tile is re-coded, one tile and four.
3500 if let Some(sources) = h264_clip_frames("the gate-clip arm", 640, 384, 3) {
3501 run(&sources, 640, 384, (0, 0));
3502 run(&sources, 640, 384, (1, 1));
3503 }
3504 crate::decode::set_verify_final_replay(false);
3505 }
3506
3507 /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
3508 /// the per-tile search, the tile write, the frame-level filter search
3509 /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
3510 /// decode the loop-restoration search rides on, and that search itself.
3511 /// Measurement, not a pass/fail gate.
3512 #[test]
3513 #[ignore = "wall measurement: 36 s at 1080p; run it with --ignored --nocapture"]
3514 fn filter_stage_wall_1080p() {
3515 let _knobs = crate::speed::knob_write();
3516 filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
3517 }
3518
3519 #[test]
3520 #[ignore = "wall measurement: 62 s at 4K; run it with --ignored --nocapture"]
3521 fn filter_stage_wall_4k() {
3522 let _knobs = crate::speed::knob_write();
3523 filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
3524 }
3525
3526 /// The same breakdown at the real films' own crop size. With
3527 /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with
3528 /// it unset it is the colour-bar fixture at the same size, which is what
3529 /// makes the pair a comparison rather than a number.
3530 #[test]
3531 // MEASURED 16 s WITHOUT `EC_AV1_WALL_CLIP`, and what it measures then is
3532 // the COLOUR-BAR fixture, not a film: `h264_clip_frames` falls back to
3533 // `fixtures/video/h264-1080p-23.976-8bit.mp4` when the var is unset. A
3534 // reader who takes the name for the content reads a bars number as a
3535 // film number, so the precondition belongs in the reason.
3536 #[ignore = "wall measurement: 16 s; MEASURES THE BARS FIXTURE unless EC_AV1_WALL_CLIP names a real film window"]
3537 fn filter_stage_wall_film() {
3538 let _knobs = crate::speed::knob_write();
3539 filter_stage_wall(1920, 768, 4, (2, 1), &[8]);
3540 }
3541
3542 fn filter_stage_wall(
3543 width: usize,
3544 height: usize,
3545 frames: usize,
3546 (cols_log2, rows_log2): (u32, u32),
3547 threads: &[usize],
3548 ) {
3549 let _gate_lock = crate::stream::tests::lock_gate_counters();
3550 let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames)
3551 else {
3552 return;
3553 };
3554 crate::par::set_stage_times(true);
3555 for &t in threads {
3556 crate::par::set_tile_threads(t);
3557 let config = EncoderConfig {
3558 width,
3559 height,
3560 base_q_idx: 120,
3561 gop: frames,
3562 colour: Colour::Bt709Limited,
3563 tile_cols_log2: cols_log2,
3564 tile_rows_log2: rows_log2,
3565 };
3566 let mut enc = Av1Encoder::new(config).unwrap();
3567 let _ = crate::par::take_stage_ns();
3568 let start = std::time::Instant::now();
3569 for packet in encode_all(&mut enc, &sources) {
3570 assert!(!packet.data.is_empty());
3571 }
3572 let wall = start.elapsed().as_secs_f64();
3573 let ns = crate::par::take_stage_ns();
3574 let ms = |i: usize| ns[i] as f64 / 1e6;
3575 eprintln!(
3576 "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
3577 {wall:.2}s wall, {:.2} fps",
3578 1 << cols_log2,
3579 1 << rows_log2,
3580 frames as f64 / wall,
3581 );
3582 eprintln!("| stage | ms | ms/frame | % of wall |");
3583 for (i, name) in crate::par::STAGES.iter().enumerate() {
3584 eprintln!(
3585 "| {name} | {:.0} | {:.1} | {:.1}% |",
3586 ms(i),
3587 ms(i) / frames as f64,
3588 100.0 * ms(i) / (wall * 1e3),
3589 );
3590 }
3591 // Top-level stages only (the deblock/CDEF/SSE rows are inside
3592 // the filter-search total); the rest is per-frame setup, the
3593 // source conversion and the splice.
3594 let top: f64 = [
3595 crate::par::S_TILE_SEARCH,
3596 crate::par::S_TILE_WRITE,
3597 crate::par::S_FILTER,
3598 crate::par::S_CAPTURE,
3599 crate::par::S_LR,
3600 ]
3601 .iter()
3602 .map(|&i| ms(i))
3603 .sum();
3604 eprintln!(
3605 "accounted {:.1}% of wall; outside the tile search {:.1}%",
3606 100.0 * top / (wall * 1e3),
3607 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
3608 );
3609 }
3610 crate::par::set_stage_times(false);
3611 crate::par::set_tile_threads(1);
3612 }
3613
3614 fn tile_search_wall(
3615 width: usize,
3616 height: usize,
3617 frames: usize,
3618 layouts: &[(u32, u32)],
3619 threads: &[usize],
3620 ) {
3621 let _gate_lock = crate::stream::tests::lock_gate_counters();
3622 let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames)
3623 else {
3624 return;
3625 };
3626 let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
3627 crate::par::set_tile_threads(t);
3628 let config = EncoderConfig {
3629 width,
3630 height,
3631 base_q_idx: 120,
3632 gop: frames,
3633 colour: Colour::Bt709Limited,
3634 tile_cols_log2: cols_log2,
3635 tile_rows_log2: rows_log2,
3636 };
3637 let mut enc = Av1Encoder::new(config).unwrap();
3638 let start = std::time::Instant::now();
3639 let mut bytes = 0usize;
3640 for packet in encode_all(&mut enc, &sources) {
3641 bytes += packet.data.len();
3642 }
3643 (start.elapsed(), bytes)
3644 };
3645 let cells: Vec<((u32, u32), usize)> = layouts
3646 .iter()
3647 .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
3648 .collect();
3649 let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
3650 for _pass in 0..2 {
3651 for (i, &((c, r), t)) in cells.iter().enumerate() {
3652 let got = run(c, r, t);
3653 assert!(
3654 got.1 > 0,
3655 "{}x{} tiles at {t} threads: empty stream",
3656 1 << c,
3657 1 << r
3658 );
3659 if best[i].is_none_or(|(w, _)| got.0 < w) {
3660 best[i] = Some(got);
3661 }
3662 }
3663 }
3664 crate::par::set_tile_threads(1);
3665 eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
3666 eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
3667 let base = best[0].expect("the first cell ran").0.as_secs_f64();
3668 for (i, &((c, r), t)) in cells.iter().enumerate() {
3669 let (wall, bytes) = best[i].expect("every cell ran");
3670 let secs = wall.as_secs_f64();
3671 eprintln!(
3672 "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
3673 1 << c,
3674 1 << r,
3675 1 << (c + r),
3676 frames as f64 / secs,
3677 base / secs,
3678 );
3679 }
3680 // Parallel efficiency per layout: what the extra threads actually
3681 // took off that layout's own single-threaded wall, and so what share
3682 // of the added cores sat idle.
3683 for &(c, r) in layouts {
3684 let one = cells
3685 .iter()
3686 .position(|&(l, t)| l == (c, r) && t == threads[0])
3687 .map(|i| best[i].expect("cell").0.as_secs_f64());
3688 let Some(one) = one else { continue };
3689 for &t in &threads[1..] {
3690 let i = cells
3691 .iter()
3692 .position(|&(l, tt)| l == (c, r) && tt == t)
3693 .expect("cell");
3694 let secs = best[i].expect("cell").0.as_secs_f64();
3695 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
3696 let speedup = one / secs;
3697 eprintln!(
3698 "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
3699 idle share {:.0}%",
3700 1 << c,
3701 1 << r,
3702 threads[0],
3703 100.0 * (1.0 - speedup / workers).max(0.0),
3704 );
3705 }
3706 }
3707 rav1e_wall_reference(width, height, frames, layouts, threads);
3708 }
3709
3710 /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
3711 /// -- the reference the wall table is read against.
3712 fn rav1e_wall_reference(
3713 width: usize,
3714 height: usize,
3715 frames: usize,
3716 layouts: &[(u32, u32)],
3717 threads: &[usize],
3718 ) {
3719 let listed = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3720 .args(["-hide_banner", "-encoders"]), None, |c| c.output());
3721 let has_rav1e = listed
3722 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
3723 .unwrap_or(false);
3724 // lane-av1clipprobe: this was `!has_rav1e || !clip.exists()` behind ONE
3725 // line, which is how the clip's absence hid inside a tool-absence
3726 // message and could not fail under any require env. The two causes are
3727 // now separate, and only the clip goes through the fixture probe, so
3728 // either way this helper prints exactly ONE line.
3729 if !has_rav1e {
3730 eprintln!("SKIP the rav1e reference: ffmpeg has no librav1e encoder");
3731 return;
3732 }
3733 let Some(clip) = crate::library_fixture::require(
3734 "video/h264-1080p-23.976-8bit.mp4",
3735 "the rav1e reference",
3736 ) else {
3737 return;
3738 };
3739 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
3740 for &(c, r) in layouts {
3741 for &t in threads {
3742 let out =
3743 std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
3744 let params = format!(
3745 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
3746 1 << c,
3747 1 << r
3748 );
3749 let start = std::time::Instant::now();
3750 let status = crate::tool_cache::cached_output_io(Command::new("ffmpeg")
3751 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
3752 .args(["-frames:v", &frames.to_string()])
3753 .args(["-vf", &format!("scale={width}:{height}")])
3754 .args(["-c:v", "librav1e", "-rav1e-params", &params])
3755 .arg(out.to_str().unwrap()), None, |c| c.output())
3756 .expect("ffmpeg failed to run");
3757 let secs = start.elapsed().as_secs_f64();
3758 if !status.status.success() {
3759 eprintln!(
3760 "| {}x{} | {t} | FAILED: {} |",
3761 1 << c,
3762 1 << r,
3763 String::from_utf8_lossy(&status.stderr)
3764 .lines()
3765 .last()
3766 .unwrap_or("")
3767 );
3768 continue;
3769 }
3770 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
3771 let _ = std::fs::remove_file(&out);
3772 eprintln!(
3773 "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
3774 1 << c,
3775 1 << r,
3776 frames as f64 / secs
3777 );
3778 }
3779 }
3780 }
3781
3782 /// The same round trip at a real 1920x1080 crop of the gate's own clip
3783 /// -- the size the editor's export actually runs at, where a tile grid
3784 /// is worth having.
3785 ///
3786 /// UN-IGNORED by lane-av1probes: it was `#[ignore]`d only for its wall
3787 /// ("1080p encode: minutes"), and it is the only 1080p arm in the ignored
3788 /// set that actually ASSERTS. Measured 30.6 s in release on the
3789 /// workstation (12 cores) and 64 s on a 4-core server, so it is affordable
3790 /// in the suite. Evidence for the un-ignore: the three tile grids 2x1,
3791 /// 2x2 and 4x2 each decode sample-exact through BOTH our decoder and
3792 /// ffmpeg (84488 / 84208 / 84685 bytes), and the check is a per-frame
3793 /// first-differing-luma-sample comparison, not a length or non-empty
3794 /// smoke.
3795 ///
3796 /// The two skippable halves both route through the crate's EXISTING
3797 /// presence probes, not a new shape: `h264_clip_frames` (which itself asks
3798 /// `have_ffmpeg()` and `library_fixture::require_at`) and `have_ffmpeg()`
3799 /// for the ffmpeg arm. No bare presence check was added.
3800 ///
3801 /// lane-av1clipprobe: with the root `fixtures/` absent this gate printed
3802 /// `SKIP the 1080p tile round trip: no fixture` and libtest reported `ok`
3803 /// — a 1080p gate that asserts nothing on every linked worktree, and no
3804 /// env that made it RED. `library_fixture::require_at` now fails under
3805 /// `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC`
3806 /// and otherwise prints exactly ONE line naming the resolved path, and the
3807 /// path it resolves honours `EC_FIXTURES` — the root
3808 /// `scripts/verify-fixture-library.sh` validates — so the preflight's
3809 /// verdict and these bytes cannot be different trees again.
3810 #[test]
3811 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
3812 let _knobs = crate::speed::knob_read();
3813 let (width, height) = (1920usize, 1080usize);
3814 let Some(sources) = h264_clip_frames(
3815 "a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders",
3816 width,
3817 height,
3818 3,
3819 ) else {
3820 return;
3821 };
3822 for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
3823 let config = EncoderConfig {
3824 width,
3825 height,
3826 base_q_idx: 120,
3827 gop: 3,
3828 colour: Colour::Bt709Limited,
3829 tile_cols_log2: cols_log2,
3830 tile_rows_log2: rows_log2,
3831 };
3832 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
3833 let mut enc = Av1Encoder::new(config).unwrap();
3834 let mut stream = Vec::new();
3835 for packet in encode_all(&mut enc, &sources) {
3836 stream.extend_from_slice(&packet.data);
3837 }
3838 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3839 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
3840 if !have_ffmpeg() {
3841 eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
3842 continue;
3843 }
3844 let theirs = ffmpeg_decode_luma(&stream, width, height);
3845 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
3846 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3847 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3848 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3849 panic!(
3850 "1080p {layout} frame {i}: luma differs first at ({}, {})",
3851 at % width,
3852 at / width
3853 );
3854 }
3855 assert_eq!(
3856 got.len(),
3857 b.len(),
3858 "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}",
3859 got.len(),
3860 b.len()
3861 );
3862 }
3863 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
3864 }
3865 }
3866
3867 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
3868 /// produces a smaller stream or a worse mean PSNR than a lower one, on
3869 /// the same real clip.
3870 #[test]
3871 fn quality_target_is_monotone_in_bytes_and_psnr() {
3872 let _knobs = crate::speed::knob_read();
3873 if !have_ffmpeg() {
3874 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
3875 return;
3876 }
3877 let (width, height) = (640, 384);
3878 let Some(pictures) = h264_clip_frames(
3879 "quality_target_is_monotone_in_bytes_and_psnr",
3880 width,
3881 height,
3882 8,
3883 ) else {
3884 return;
3885 };
3886 let mut prev_bytes = 0usize;
3887 let mut prev_psnr = 0.0f64;
3888 for quality in [20u8, 50, 80] {
3889 let config = EncoderConfig {
3890 width,
3891 height,
3892 base_q_idx: 100,
3893 gop: 8,
3894 colour: Colour::Bt709Limited,
3895 tile_cols_log2: 0,
3896 tile_rows_log2: 0,
3897 };
3898 let mut enc =
3899 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
3900 let mut stream = Vec::new();
3901 let mut total_bytes = 0usize;
3902 for packet in encode_all(&mut enc, &pictures) {
3903 total_bytes += packet.data.len();
3904 stream.extend_from_slice(&packet.data);
3905 }
3906 let decoded = ffmpeg_decode_luma(&stream, width, height);
3907 assert_eq!(
3908 decoded.len(),
3909 pictures.len(),
3910 "quality {quality}: dav1d frame count"
3911 );
3912 let mean_psnr: f64 = decoded
3913 .iter()
3914 .zip(&pictures)
3915 .map(|(d, p)| {
3916 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
3917 psnr(&d16, &p.y)
3918 })
3919 .sum::<f64>()
3920 / decoded.len() as f64;
3921 assert!(
3922 total_bytes >= prev_bytes,
3923 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
3924 );
3925 assert!(
3926 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
3927 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
3928 );
3929 prev_bytes = total_bytes;
3930 prev_psnr = mean_psnr;
3931 }
3932 }