forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

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