forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.1 MiBa69dfabTahinli4 hours ago4073 commits

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