forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.2 MiBfbd8fe4Tahinli5 hours ago4107 commits

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