forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

conformance.rs2286 lines, 82.6 KiBHistoryRawDownload
1//! JVT conformance: first IDR picture, bit-exact.
2//!
3//! Fixture-gated like tools/oracle: fixtures/ is gitignored, so a checkout
4//! without `scripts/fetch-vectors.sh` skips loudly instead of failing.
5//!
6//! Oracles, in order of authority:
7//! 1. The reference decoder YUV that ships with each JVT vector (first
8//! frame) — ffmpeg-independent.
9//! 2. `ffmpeg -i <stream> -frames:v 1` raw output, cross-checked when the
10//! binary is present.
11//!
12//! The same binary hosts the zero-allocation proof and the ns/MB
13//! measurement so the crate keeps a single integration-test link unit.
14
15use std::alloc::System;
16use std::sync::Once;
17
18use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator};
19use std::cell::Cell;
20use std::path::{Path, PathBuf};
21use std::process::Command;
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
25use ec_core::{Buf, Frame, Packet, TimeBase};
26use ec_h264::{Decoder, Error, H264Decoder, NalOutcome};
27
28// ---------------------------------------------------------------------------
29// Counting allocator: proves the steady-state decode loop allocates nothing.
30// Lives in the test binary only — the shipped crates have no allocator games.
31// ---------------------------------------------------------------------------
32
33struct CountingAlloc;
34
35static ALLOCS: AtomicU64 = AtomicU64::new(0);
36
37std::thread_local! {
38 /// Only the test thread that armed the counter is counted — other test
39 /// threads (and their ffmpeg child plumbing) allocate freely.
40 static COUNTING_HERE: Cell<bool> = const { Cell::new(false) };
41}
42
43fn counting_here() -> bool {
44 COUNTING_HERE.try_with(Cell::get).unwrap_or(false)
45}
46
47impl AllocationTracker for CountingAlloc {
48 fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) {
49 if counting_here() {
50 ALLOCS.fetch_add(1, Ordering::Relaxed);
51 }
52 }
53 fn deallocated(
54 &self,
55 _addr: usize,
56 _object_size: usize,
57 _wrapped: usize,
58 _source: AllocationGroupId,
59 _current: AllocationGroupId,
60 ) {
61 }
62}
63
64#[global_allocator]
65static A: Allocator<System> = Allocator::system();
66
67/// Installs the tracker once; every test that arms the counter calls this first.
68fn install_counter() {
69 static ONCE: Once = Once::new();
70 ONCE.call_once(|| {
71 let _ = AllocationRegistry::set_global_tracker(CountingAlloc);
72 AllocationRegistry::enable_tracking();
73 });
74}
75
76// ---------------------------------------------------------------------------
77
78fn vectors_dir() -> PathBuf {
79 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt")
80}
81
82/// A gate that skips when its fixtures are absent reports GREEN having checked
83/// nothing — the "gate skips on its own failure" class. The root `fixtures/`
84/// directory is gitignored, so `git worktree add` hands every lane worktree a
85/// tree without it and the whole conformance suite silently stops testing.
86///
87/// `EC_REQUIRE_FIXTURES=1` turns the skip into a hard failure naming the exact
88/// missing path and the command that produces it; unset (the default), the skip
89/// is kept and now says what it skipped. Set it in every batch run.
90fn require_fixtures(path: &Path, what: &str, generator: &str) -> bool {
91 if path.exists() {
92 return true;
93 }
94 assert!(
95 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
96 "{what} missing at {} — this gate would prove nothing. A worktree has no \
97 gitignored root `fixtures/`: run scripts/link-fixtures.sh, or generate \
98 them with {generator}.",
99 path.display()
100 );
101 eprintln!(
102 "SKIP {what} missing at {} — this gate proved nothing; run \
103 scripts/link-fixtures.sh, or generate them with {generator} \
104 (or set EC_REQUIRE_FIXTURES=1 to make this a failure).",
105 path.display()
106 );
107 false
108}
109
110/// Every vector directory `scripts/fetch-vectors.sh` has populated, in name
111/// order.
112///
113/// A hand-written list would only ever record what passed on the day it was
114/// written: a vector added later would be silently untested, and one that
115/// regressed from bit-exact to refused would be invisible. Walking the
116/// directory makes every fixture on disk a claim this test has to account for.
117fn all_vectors(base: &Path) -> Vec<String> {
118 let mut names: Vec<String> = std::fs::read_dir(base)
119 .into_iter()
120 .flatten()
121 .flatten()
122 .filter(|e| e.path().is_dir())
123 .map(|e| e.file_name().to_string_lossy().into_owned())
124 .collect();
125 names.sort();
126 names
127}
128
129fn find_stream(dir: &Path) -> Option<PathBuf> {
130 let mut fallback = None;
131 for entry in std::fs::read_dir(dir).ok()? {
132 let p = entry.ok()?.path();
133 let ext = p.extension()?.to_str()?.to_ascii_lowercase();
134 if matches!(ext.as_str(), "jsv" | "264" | "avc" | "26l" | "h264" | "jvt") {
135 return Some(p);
136 }
137 if ext == "bit" {
138 fallback = Some(p);
139 }
140 }
141 fallback
142}
143
144fn find_ref_yuv(dir: &Path) -> Option<PathBuf> {
145 for entry in std::fs::read_dir(dir).ok()? {
146 let p = entry.ok()?.path();
147 let ext = p.extension()?.to_str()?.to_ascii_lowercase();
148 if ext == "yuv" || ext == "qcif" {
149 return Some(p);
150 }
151 }
152 None
153}
154
155fn ffmpeg_first_frame(stream: &Path) -> Option<Vec<u8>> {
156 let out = Command::new("ffmpeg")
157 .args(["-v", "error", "-i"])
158 .arg(stream)
159 .args([
160 "-frames:v",
161 "1",
162 "-f",
163 "rawvideo",
164 "-pix_fmt",
165 "yuv420p",
166 "-",
167 ])
168 .output()
169 .ok()?;
170 if !out.status.success() || out.stdout.is_empty() {
171 return None;
172 }
173 Some(out.stdout)
174}
175
176/// Decode the first IDR and return (frame bytes as I420, width, height).
177fn decode_first(stream_bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), Error> {
178 let mut dec = Decoder::new();
179 let frame = dec.decode_first_idr(stream_bytes)?;
180 let (w, h) = (frame.width as usize, frame.height as usize);
181 let mut out = Vec::with_capacity(w * h * 3 / 2);
182 let dims = [
183 (w, h),
184 (w.div_ceil(2), h.div_ceil(2)),
185 (w.div_ceil(2), h.div_ceil(2)),
186 ];
187 for (plane, (pw, ph)) in frame.planes.iter().zip(dims) {
188 for y in 0..ph {
189 out.extend_from_slice(plane.row(y, pw).expect("plane row"));
190 }
191 }
192 Ok((out, w, h))
193}
194
195fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> {
196 a.iter().zip(b).position(|(x, y)| x != y)
197}
198
199/// Pack a decoded frame as contiguous I420 bytes.
200fn frame_bytes(frame: &ec_core::frame::VideoFrame) -> Vec<u8> {
201 let (w, h) = (frame.width as usize, frame.height as usize);
202 let mut out = Vec::with_capacity(w * h * 3 / 2);
203 let dims = [
204 (w, h),
205 (w.div_ceil(2), h.div_ceil(2)),
206 (w.div_ceil(2), h.div_ceil(2)),
207 ];
208 for (plane, (pw, ph)) in frame.planes.iter().zip(dims) {
209 for y in 0..ph {
210 out.extend_from_slice(plane.row(y, pw).expect("plane row"));
211 }
212 }
213 out
214}
215
216/// Decode a whole Annex B stream, returning every frame in display order.
217fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> {
218 let mut dec = Decoder::new();
219 let mut frames = Vec::new();
220 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
221 if dec.push_nal(nal)? == NalOutcome::PictureBoundary {
222 dec.end_picture()?;
223 dec.push_nal(nal)?;
224 }
225 while let Some(f) = dec.next_frame() {
226 frames.push(frame_bytes(&f));
227 }
228 }
229 dec.flush()?;
230 while let Some(f) = dec.next_frame() {
231 frames.push(frame_bytes(&f));
232 }
233 Ok(frames)
234}
235
236/// Every frame ffmpeg decodes from `stream`, as raw I420.
237fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> {
238 let out = Command::new("ffmpeg")
239 .args(["-v", "error", "-i"])
240 .arg(stream)
241 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
242 .output()
243 .ok()?;
244 if !out.status.success() || out.stdout.is_empty() {
245 return None;
246 }
247 Some(
248 out.stdout
249 .chunks_exact(frame_len)
250 .map(<[u8]>::to_vec)
251 .collect(),
252 )
253}
254
255/// Encode a multi-frame clip with x264 and return the Annex B file.
256fn x264_encode_gop(
257 dir: &Path,
258 tag: &str,
259 size: &str,
260 frames: u32,
261 extra: &[&str],
262) -> Option<PathBuf> {
263 let stream = dir.join(format!("{tag}.264"));
264 let source = format!("testsrc=size={size}:rate=25:duration=4");
265 let mut args: Vec<String> = [
266 "-hide_banner",
267 "-loglevel",
268 "error",
269 "-y",
270 "-f",
271 "lavfi",
272 "-i",
273 ]
274 .iter()
275 .map(|s| s.to_string())
276 .collect();
277 args.push(source);
278 if !extra.contains(&"-pix_fmt") {
279 args.extend(["-pix_fmt".into(), "yuv420p".into()]);
280 }
281 args.extend([
282 "-c:v".into(),
283 "libx264".into(),
284 "-frames:v".into(),
285 frames.to_string(),
286 ]);
287 args.extend(extra.iter().map(|s| s.to_string()));
288 args.extend([
289 "-f".into(),
290 "h264".into(),
291 stream.to_string_lossy().into_owned(),
292 ]);
293 let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
294 run("ffmpeg", &refs).then_some(stream)
295}
296
297/// Decode `stream` both ways and report the first frame that differs.
298fn compare_sequence(stream: &Path) -> Result<usize, String> {
299 let bytes = std::fs::read(stream).map_err(|e| e.to_string())?;
300 let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?;
301 let first = ours.first().ok_or("no frames decoded")?;
302 let theirs = ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?;
303 if ours.len() != theirs.len() {
304 return Err(format!(
305 "{} frames decoded, ffmpeg gave {}",
306 ours.len(),
307 theirs.len()
308 ));
309 }
310 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
311 if let Some(pos) = first_diff(a, b) {
312 return Err(format!(
313 "frame {i} differs at byte {pos}: ours {} ffmpeg {}",
314 a[pos], b[pos]
315 ));
316 }
317 assert_eq!(
318 a.len(),
319 b.len(),
320 "frame {i} is {} samples, ffmpeg gave {}",
321 a.len(),
322 b.len()
323 );
324 }
325 Ok(ours.len())
326}
327
328#[test]
329fn jvt_cavlc_first_idr_bit_exact() {
330 let base = vectors_dir();
331 if !require_fixtures(
332 &base,
333 "the JVT conformance vectors",
334 "scripts/fetch-vectors.sh",
335 ) {
336 return;
337 }
338 let mut passed = Vec::new();
339 let mut failed = Vec::new();
340 let mut refused = Vec::new();
341 for name in all_vectors(&base) {
342 let name = name.as_str();
343 let dir = base.join(name);
344 let Some(stream) = find_stream(&dir) else {
345 eprintln!("SKIP {name}: no bitstream file");
346 continue;
347 };
348 let bytes = std::fs::read(&stream).unwrap();
349 match decode_first(&bytes) {
350 Ok((ours, w, h)) => {
351 let frame_len = w * h * 3 / 2;
352 // Oracle 1: reference decoder YUV, first frame.
353 let mut ok = true;
354 if let Some(ref_path) = find_ref_yuv(&dir) {
355 let reference = std::fs::read(&ref_path).unwrap();
356 assert!(
357 reference.len() >= frame_len,
358 "{name}: reference YUV shorter than one frame"
359 );
360 if let Some(pos) = first_diff(&ours, &reference[..frame_len]) {
361 eprintln!(
362 "FAIL {name}: differs from reference YUV at byte {pos} \
363 (plane offset, {w}x{h}): ours {} ref {}",
364 ours[pos], reference[pos]
365 );
366 ok = false;
367 }
368 assert_eq!(
369 ours.len(),
370 frame_len,
371 "{name}: frame is {} samples ({w}x{h}), the reference frame is {frame_len}",
372 ours.len()
373 );
374 } else {
375 eprintln!("WARN {name}: no reference YUV, ffmpeg only");
376 }
377 // Oracle 2: ffmpeg.
378 if let Some(ff) = ffmpeg_first_frame(&stream) {
379 assert!(ff.len() >= frame_len, "{name}: ffmpeg output short");
380 if let Some(pos) = first_diff(&ours, &ff[..frame_len]) {
381 eprintln!(
382 "FAIL {name}: differs from ffmpeg at byte {pos}: ours {} ff {}",
383 ours[pos], ff[pos]
384 );
385 ok = false;
386 }
387 assert_eq!(
388 ours.len(),
389 frame_len,
390 "{name}: frame is {} samples ({w}x{h}), the ffmpeg frame is {frame_len}",
391 ours.len()
392 );
393 }
394 if ok {
395 passed.push(name.to_string());
396 } else {
397 failed.push(name.to_string());
398 }
399 }
400 // Outside this release's scope is allowed, but only when the
401 // decoder says so by name. Corrupt or NeedMore on a conformant
402 // stream is a bug here, not a capability statement.
403 Err(e @ Error::Unsupported { .. }) => {
404 eprintln!("REFUSED {name}: {e}");
405 refused.push(name.to_string());
406 }
407 Err(e) => {
408 eprintln!("FAIL {name}: decode error: {e}");
409 failed.push(name.to_string());
410 }
411 }
412 }
413 eprintln!(
414 "PASS table ({} bit-exact, {} refused by name): {passed:?}",
415 passed.len(),
416 refused.len()
417 );
418 assert!(
419 failed.is_empty(),
420 "streams neither bit-exact nor refused by name: {failed:?}"
421 );
422 assert!(
423 passed.len() >= 5,
424 "fewer than 5 CAVLC conformance streams verified: {passed:?}"
425 );
426}
427
428/// Steady-state slice decoding performs zero heap allocations.
429///
430/// After a warm-up pass the picture pool, every per-picture array and the
431/// parameter-set store are all sized, so decoding the same stream again must
432/// not allocate at all: not per macroblock, not per slice, not per picture.
433/// Emitting a frame is measured separately and *does* allocate — it hands the
434/// caller owned planes — which also proves the counter is alive.
435#[test]
436fn steady_state_decode_loop_zero_alloc() {
437 install_counter();
438 let base = vectors_dir();
439 if !require_fixtures(
440 &base,
441 "the JVT conformance vectors",
442 "scripts/fetch-vectors.sh",
443 ) {
444 return;
445 }
446 // One stream per entropy coder, and one with B slices and multiple
447 // reference frames so the decoded picture buffer really recycles pictures.
448 for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] {
449 let Some(stream) = find_stream(&base.join(name)) else {
450 continue;
451 };
452 let bytes = std::fs::read(stream).unwrap();
453 let mut dec = Decoder::new();
454 let drive = |dec: &mut Decoder, count: bool| -> usize {
455 let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
456 let mut frames = 0usize;
457 for nal in &nals {
458 if count {
459 COUNTING_HERE.with(|c| c.set(true));
460 }
461 let outcome = dec.push_nal(nal);
462 if count {
463 COUNTING_HERE.with(|c| c.set(false));
464 }
465 match outcome {
466 Ok(ec_h264::NalOutcome::PictureBoundary) => {
467 dec.end_picture().expect("end_picture");
468 dec.push_nal(nal).expect("re-push");
469 }
470 Ok(_) => {}
471 Err(e) => panic!("{name}: {e}"),
472 }
473 while dec.next_frame().is_some() {
474 frames += 1;
475 }
476 }
477 dec.flush().expect("flush");
478 while dec.next_frame().is_some() {
479 frames += 1;
480 }
481 frames
482 };
483 // Warm-up: every reusable buffer reaches its final size.
484 let warm = drive(&mut dec, false);
485 assert!(warm > 1, "{name}: only {warm} frames decoded");
486 dec.reset_pictures();
487
488 ALLOCS.store(0, Ordering::SeqCst);
489 let again = drive(&mut dec, true);
490 let n = ALLOCS.load(Ordering::SeqCst);
491 assert_eq!(
492 again, warm,
493 "{name}: frame count changed on the second pass"
494 );
495 assert_eq!(
496 n, 0,
497 "{name}: steady-state slice decode allocated {n} times"
498 );
499 }
500
501 // Sanity: the counter is alive — emitting a frame does allocate.
502 let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap();
503 let mut dec = Decoder::new();
504 let _ = dec.decode_first_idr(&bytes).expect("decode");
505 ALLOCS.store(0, Ordering::SeqCst);
506 COUNTING_HERE.with(|c| c.set(true));
507 let frame = dec.frame().expect("frame");
508 COUNTING_HERE.with(|c| c.set(false));
509 assert!(frame.width > 0);
510 assert!(
511 ALLOCS.load(Ordering::SeqCst) > 0,
512 "allocation counter appears dead"
513 );
514}
515
516/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf
517/// report. Run with `--nocapture` to see it. Uses the steady-state path
518/// (buffers warm) like a playback loop would.
519///
520/// Both halves matter: the intra measurement is what the previous release
521/// reported, and the whole-sequence one is what playback actually costs, since
522/// a real stream is almost all inter pictures.
523#[test]
524fn ns_per_macroblock_measurement() {
525 let base = vectors_dir();
526 if !require_fixtures(
527 &base,
528 "the JVT conformance vectors",
529 "scripts/fetch-vectors.sh",
530 ) {
531 return;
532 }
533 for name in [
534 "BA1_Sony_D",
535 "CI_MW_D",
536 "NL1_Sony_D",
537 "CABA1_SVA_B",
538 "CABA3_SVA_B",
539 ] {
540 let Some(stream) = find_stream(&base.join(name)) else {
541 continue;
542 };
543 let bytes = std::fs::read(stream).unwrap();
544 let mut dec = Decoder::new();
545 let frame = dec.decode_first_idr(&bytes).expect("warm-up");
546 let (w, h) = (frame.width as u64, frame.height as u64);
547 let mbs = (w.div_ceil(16)) * (h.div_ceil(16));
548 let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
549
550 let iters = 200u32;
551 let start = std::time::Instant::now();
552 for _ in 0..iters {
553 for nal in &nals {
554 match dec.push_nal(nal) {
555 Ok(ec_h264::NalOutcome::PictureBoundary) => break,
556 Ok(_) => {}
557 Err(e) => panic!("{e}"),
558 }
559 }
560 dec.end_picture().expect("end_picture");
561 }
562 let elapsed = start.elapsed();
563 let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64;
564 let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6;
565 eprintln!(
566 "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \
567 (intra IDR, single thread, deblock included, output copy excluded)"
568 );
569 }
570 perf_whole_sequence();
571}
572
573/// The same measurement over whole sequences, where inter prediction, the
574/// decoded picture buffer and output all count.
575fn perf_whole_sequence() {
576 let base = vectors_dir();
577 for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] {
578 let Some(stream) = find_stream(&base.join(name)) else {
579 continue;
580 };
581 let bytes = std::fs::read(stream).unwrap();
582 let Ok(warm) = decode_all(&bytes) else {
583 continue;
584 };
585 if warm.is_empty() {
586 continue;
587 }
588 let frames = warm.len() as f64;
589 let start = std::time::Instant::now();
590 let iters = 5u32;
591 for _ in 0..iters {
592 let _ = decode_all(&bytes).expect("decode");
593 }
594 let elapsed = start.elapsed().as_secs_f64() / f64::from(iters);
595 // Every vector here is QCIF: 11 x 9 macroblocks.
596 let mbs = 99.0 * frames;
597 eprintln!(
598 "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \
599 (full sequence, single thread, deblock and output copy included)",
600 elapsed * 1e9 / mbs,
601 176.0 * 144.0 * frames / elapsed / 1e6
602 );
603 }
604}
605
606/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte
607/// mutations and truncations of a real stream must produce `Err` or a frame,
608/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane
609/// done-criterion); this keeps the invariant enforced in every test run.
610#[test]
611fn corrupt_streams_never_panic() {
612 let base = vectors_dir();
613 if !require_fixtures(
614 &base,
615 "the JVT conformance vectors",
616 "scripts/fetch-vectors.sh",
617 ) {
618 return;
619 }
620 // One stream per entropy coder, plus one with B slices and multiple
621 // references: CABAC's arithmetic decoder indexes context and coefficient
622 // arrays from stream-derived values, and inter prediction indexes the
623 // decoded picture buffer, the reference lists and the motion arrays from
624 // them too. All of it needs the same no-panic floor as the CAVLC tables.
625 for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] {
626 let Some(stream) = find_stream(&base.join(name)) else {
627 continue;
628 };
629 corrupt_sweep(&std::fs::read(stream).unwrap());
630 }
631}
632
633/// Truncate and bit-flip `bytes` many ways; every decode must return, error or
634/// succeed, and never panic.
635fn corrupt_sweep(bytes: &[u8]) {
636 let bytes = bytes.to_vec();
637
638 // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data.
639 for len in (0..bytes.len().min(4096))
640 .step_by(37)
641 .chain([bytes.len() / 2])
642 {
643 let mut dec = Decoder::new();
644 let _ = dec.decode_first_idr(&bytes[..len]);
645 // Truncation must also be survivable on the full-sequence path, where
646 // a half-decoded picture meets the decoded picture buffer.
647 let _ = decode_all(&bytes[..len]);
648 }
649 // Single-byte corruptions: xor a walking pattern through the first 6KB
650 // (covers parameter sets and the first slices), plus scattered hits.
651 let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep
652 // Debug builds carry overflow checks but decode ~10x slower; a smaller
653 // sweep keeps the suite fast while release runs the full one.
654 let count = if cfg!(debug_assertions) { 400 } else { 2000 };
655 let dense = count * 3 / 4;
656 for i in 0..count {
657 let mut m = bytes.clone();
658 let pos = if i < dense {
659 i * 4 % m.len().min(6144)
660 } else {
661 xorshift ^= xorshift << 13;
662 xorshift ^= xorshift >> 17;
663 xorshift ^= xorshift << 5;
664 (xorshift as usize) % m.len()
665 };
666 m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1);
667 let mut dec = Decoder::new();
668 let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine
669 if i % 8 == 0 {
670 // The whole-sequence path costs more, so it gets a thinner sweep;
671 // it is the one that exercises reference lists and marking with
672 // stream-derived indices.
673 let _ = decode_all(&m);
674 }
675 }
676}
677
678// ---------------------------------------------------------------------------
679// ffmpeg-driven coverage: the JVT vectors are all QCIF, single-slice and coded
680// at a handful of quantisers, which leaves most of the deblocking tables, every
681// non-QCIF geometry and every refusal unexercised. x264 fills those gaps, with
682// ffmpeg's own decoder as the oracle.
683// ---------------------------------------------------------------------------
684
685/// Run a command, false when it fails or is not installed.
686fn run(command: &str, args: &[&str]) -> bool {
687 Command::new(command)
688 .args(args)
689 .stdout(std::process::Stdio::null())
690 .stderr(std::process::Stdio::null())
691 .status()
692 .map(|s| s.success())
693 .unwrap_or(false)
694}
695
696fn have_ffmpeg() -> bool {
697 run(
698 "ffmpeg",
699 &["-hide_banner", "-loglevel", "error", "-version"],
700 )
701}
702
703/// A private scratch directory for one test.
704fn scratch(tag: &str) -> PathBuf {
705 let dir = std::env::temp_dir().join(format!("ec-h264-{tag}-{}", std::process::id()));
706 let _ = std::fs::create_dir_all(&dir);
707 dir
708}
709
710/// Encode one all-intra picture with x264 and return the Annex B file.
711fn x264_encode(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Option<PathBuf> {
712 let stream = dir.join(format!("{tag}.264"));
713 let source = format!("testsrc=size={size}:rate=1:duration=1");
714 let mut args: Vec<String> = [
715 "-hide_banner",
716 "-loglevel",
717 "error",
718 "-y",
719 "-f",
720 "lavfi",
721 "-i",
722 ]
723 .iter()
724 .map(|s| s.to_string())
725 .collect();
726 args.push(source);
727 // The pixel format has to precede the encoder arguments that name a
728 // profile depending on it.
729 if !extra.contains(&"-pix_fmt") {
730 args.extend(["-pix_fmt".into(), "yuv420p".into()]);
731 }
732 args.extend([
733 "-c:v".into(),
734 "libx264".into(),
735 "-frames:v".into(),
736 "1".into(),
737 ]);
738 args.extend(extra.iter().map(|s| s.to_string()));
739 args.extend([
740 "-f".into(),
741 "h264".into(),
742 stream.to_string_lossy().into_owned(),
743 ]);
744 let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
745 run("ffmpeg", &refs).then_some(stream)
746}
747
748/// Encode, decode both ways, return the number of differing bytes.
749fn round_trip(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Result<usize, String> {
750 let stream =
751 x264_encode(dir, tag, size, extra).ok_or(format!("{tag}: ffmpeg cannot encode"))?;
752 let expected =
753 ffmpeg_first_frame(&stream).ok_or(format!("{tag}: ffmpeg cannot decode its own output"))?;
754 let (ours, w, h) =
755 decode_first(&std::fs::read(&stream).unwrap()).map_err(|e| format!("{tag}: {e}"))?;
756 if ours.len() > expected.len() {
757 return Err(format!(
758 "{tag}: {w}x{h} is {} bytes, ffmpeg gave {}",
759 ours.len(),
760 expected.len()
761 ));
762 }
763 if ours.len() < expected.len() {
764 return Err(format!(
765 "{tag}: {w}x{h} decoded to {} bytes, ffmpeg gave {}",
766 ours.len(),
767 expected.len()
768 ));
769 }
770 Ok(ours
771 .iter()
772 .zip(&expected[..ours.len()])
773 .filter(|(a, b)| a != b)
774 .count())
775}
776
777/// The two entropy coders, as ffmpeg encoder arguments. Baseline forces CAVLC;
778/// Main with `-coder ac` selects CABAC. Neither profile admits the 8x8
779/// transform, so both stay inside this release's scope.
780const ENTROPY_MODES: [(&str, &[&str]); 2] = [
781 ("cavlc", &["-profile:v", "baseline"]),
782 ("cabac", &["-profile:v", "main", "-coder", "ac"]),
783];
784
785/// Geometry and slice structure: cropping, odd sizes, multiple slices, the
786/// loop filter off and a chroma QP offset — what a real camera or encoder
787/// produces, none of which the QCIF single-slice vectors cover.
788#[test]
789fn geometry_and_slice_structure_match_ffmpeg() {
790 if !have_ffmpeg() {
791 eprintln!("SKIP: ffmpeg not on PATH");
792 return;
793 }
794 let dir = scratch("geometry");
795 let cases: &[(&str, &str, &[&str])] = &[
796 // 1080 lines are coded as 68 macroblock rows and cropped back to 1080.
797 ("hd", "1920x1080", &["-qp", "26"]),
798 // A width that is not a multiple of 16 crops horizontally as well.
799 ("odd", "1916x1080", &["-qp", "26"]),
800 // Four slices: neighbour availability stops at every slice boundary,
801 // and under CABAC every slice re-initialises its own contexts.
802 (
803 "slices",
804 "352x288",
805 &["-qp", "24", "-x264-params", "slices=4"],
806 ),
807 // No loop filter at all.
808 (
809 "nodeblock",
810 "352x288",
811 &["-qp", "30", "-x264-params", "no-deblock=1"],
812 ),
813 // A non-zero chroma QP offset moves the chroma deblock thresholds.
814 (
815 "chromaqp",
816 "352x288",
817 &["-qp", "30", "-x264-params", "chroma_qp_offset=6"],
818 ),
819 // One macroblock wide: every neighbour is unavailable.
820 ("tiny", "16x16", &["-qp", "20"]),
821 ];
822 let mut table = String::new();
823 let mut failures = Vec::new();
824 for (mode, profile) in ENTROPY_MODES {
825 for (tag, size, case) in cases {
826 let mut extra = profile.to_vec();
827 extra.extend_from_slice(case);
828 let tag = format!("{mode}-{tag}");
829 match round_trip(&dir, &tag, size, &extra) {
830 Ok(0) => table.push_str(&format!("{tag:<16} {size:<10} bit-exact\n")),
831 Ok(n) => {
832 table.push_str(&format!("{tag:<16} {size:<10} MISMATCH {n} bytes\n"));
833 failures.push(format!("{tag}: {n} bytes differ"));
834 }
835 Err(e) => {
836 table.push_str(&format!("{tag:<16} {size:<10} {e}\n"));
837 failures.push(e);
838 }
839 }
840 }
841 }
842 let _ = std::fs::remove_dir_all(&dir);
843 eprintln!("{table}");
844 assert!(failures.is_empty(), "{failures:#?}");
845}
846
847/// Scaling matrices are decoded, not refused: a High-profile stream carrying
848/// the JVT default matrices (`cqm=jvt`) must come out bit-exact.
849///
850/// Pinned because it is the one High-profile tool this release implements, and
851/// nothing else in the suite would notice it regressing into a refusal.
852#[test]
853fn jvt_scaling_matrices_decode_bit_exact() {
854 if !have_ffmpeg() {
855 eprintln!("SKIP: ffmpeg not on PATH");
856 return;
857 }
858 let dir = scratch("scaling");
859 let extra = [
860 "-profile:v",
861 "high",
862 "-qp",
863 "26",
864 "-x264-params",
865 "cabac=0:8x8dct=0:cqm=jvt",
866 ];
867 let result = round_trip(&dir, "cqm-jvt", "176x144", &extra);
868 let _ = std::fs::remove_dir_all(&dir);
869 match result {
870 Ok(0) => eprintln!("cqm=jvt scaling matrices bit-exact"),
871 Ok(n) => panic!("cqm=jvt: {n} bytes differ from ffmpeg"),
872 Err(e) => panic!("{e}"),
873 }
874}
875
876/// The `avcC` entry path: parameter sets out of band and NAL units length
877/// prefixed — how an MP4 or Matroska demuxer hands H.264 over.
878#[test]
879fn avcc_extradata_and_length_prefixed_packets() {
880 if !have_ffmpeg() {
881 eprintln!("SKIP: ffmpeg not on PATH");
882 return;
883 }
884 let dir = scratch("avcc");
885 let Some(annex_b) = x264_encode(
886 &dir,
887 "stream",
888 "176x144",
889 &["-profile:v", "baseline", "-qp", "26"],
890 ) else {
891 panic!("ffmpeg cannot encode a baseline picture");
892 };
893 let data = std::fs::read(&annex_b).unwrap();
894 let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
895 .map(<[u8]>::to_vec)
896 .collect();
897 let sps = units.iter().find(|u| u[0] & 0x1F == 7).expect("an SPS");
898 let pps = units.iter().find(|u| u[0] & 0x1F == 8).expect("a PPS");
899
900 // avcC (ISO/IEC 14496-15 clause 5.3.3.1): version, profile, compatibility,
901 // level, the NAL length size, then the parameter sets.
902 let mut avcc = vec![1, sps[1], sps[2], sps[3], 0xFF, 0xE1];
903 avcc.extend_from_slice(&(sps.len() as u16).to_be_bytes());
904 avcc.extend_from_slice(sps);
905 avcc.push(1);
906 avcc.extend_from_slice(&(pps.len() as u16).to_be_bytes());
907 avcc.extend_from_slice(pps);
908
909 let mut params = CodecParameters::new(CodecId::H264);
910 params.extradata = Some(Buf::from_vec(avcc));
911 let mut decoder = H264Decoder::new(params).expect("avcC parses");
912 assert_eq!(
913 (
914 decoder.codec_parameters().video().unwrap().width,
915 decoder.codec_parameters().video().unwrap().height
916 ),
917 (176, 144),
918 "the SPS inside the avcC sets the picture size, before any packet"
919 );
920
921 // The slice NAL units, each behind a four byte length prefix.
922 let mut sample = Vec::new();
923 for unit in units.iter().filter(|u| matches!(u[0] & 0x1F, 1 | 5)) {
924 sample.extend_from_slice(&(unit.len() as u32).to_be_bytes());
925 sample.extend_from_slice(unit);
926 }
927 decoder
928 .send_packet(&Packet::new(0, TimeBase::new(1, 25), sample).with_pts(7))
929 .expect("length prefixed packet decodes");
930 let Frame::Video(frame) = decoder.receive_frame().expect("a frame") else {
931 panic!("video frame expected");
932 };
933 assert_eq!((frame.width, frame.height), (176, 144));
934 assert_eq!(
935 frame.pts.map(|t| t.ticks),
936 Some(7),
937 "packet pts reaches the frame"
938 );
939
940 // Same picture through the Annex B path: the two entry paths agree.
941 let (annex_b_frame, _, _) = decode_first(&data).unwrap();
942 let mut avcc_frame = Vec::with_capacity(annex_b_frame.len());
943 for (index, plane) in frame.planes.iter().enumerate() {
944 let (w, h) = if index == 0 { (176, 144) } else { (88, 72) };
945 for row in 0..h {
946 avcc_frame.extend_from_slice(plane.row(row, w).expect("plane row"));
947 }
948 }
949 assert_eq!(avcc_frame, annex_b_frame);
950 let _ = std::fs::remove_dir_all(&dir);
951}
952
953// ---------------------------------------------------------------------------
954// Inter prediction, the decoded picture buffer and display order.
955// ---------------------------------------------------------------------------
956
957/// A P-only GOP, every frame bit-exact against ffmpeg, under both entropy
958/// coders. This is the narrowest thing that exercises motion compensation, the
959/// reference list, sliding-window marking and the inter boundary strengths at
960/// once, so it is the first test to look at when any of them regress.
961#[test]
962fn p_only_gop_matches_ffmpeg_every_frame() {
963 if !have_ffmpeg() {
964 eprintln!("SKIP: ffmpeg not on PATH");
965 return;
966 }
967 let dir = scratch("p-gop");
968 let mut failures = Vec::new();
969 for (mode, profile) in ENTROPY_MODES {
970 let mut extra = profile.to_vec();
971 extra.extend(["-qp", "26", "-x264-params", "bframes=0:weightp=0:ref=1"]);
972 let tag = format!("{mode}-p");
973 match x264_encode_gop(&dir, &tag, "176x144", 12, &extra) {
974 Some(stream) => match compare_sequence(&stream) {
975 Ok(n) => eprintln!("{tag}: {n} frames bit-exact"),
976 Err(e) => failures.push(format!("{tag}: {e}")),
977 },
978 None => failures.push(format!("{tag}: ffmpeg cannot encode")),
979 }
980 }
981 let _ = std::fs::remove_dir_all(&dir);
982 assert!(failures.is_empty(), "{failures:#?}");
983}
984
985/// JVT conformance, every frame of every vector: our display-order output
986/// against the reference decoder YUV that ships with the vector.
987///
988/// The first-IDR test above proves intra reconstruction; this one is what
989/// proves inter prediction, the decoded picture buffer and output order,
990/// because a single wrong motion vector or a reference marked at the wrong
991/// moment shows up as a mismatch in some later frame, not the first.
992#[test]
993fn jvt_full_sequence_bit_exact() {
994 let base = vectors_dir();
995 if !require_fixtures(
996 &base,
997 "the JVT conformance vectors",
998 "scripts/fetch-vectors.sh",
999 ) {
1000 return;
1001 }
1002 let mut table = String::new();
1003 let mut passed = 0usize;
1004 let mut refused = Vec::new();
1005 let mut failed = Vec::new();
1006 for name in all_vectors(&base) {
1007 let dir = base.join(&name);
1008 let Some(stream) = find_stream(&dir) else {
1009 continue;
1010 };
1011 let bytes = std::fs::read(&stream).unwrap();
1012 match decode_all(&bytes) {
1013 Ok(frames) if frames.is_empty() => {
1014 failed.push(format!("{name}: decoded no frames"));
1015 }
1016 Ok(frames) => {
1017 let len = frames[0].len();
1018 let Some(ref_path) = find_ref_yuv(&dir) else {
1019 table.push_str(&format!(
1020 "{name:<16} {:>3} frames, no reference YUV\n",
1021 frames.len()
1022 ));
1023 continue;
1024 };
1025 let reference = std::fs::read(&ref_path).unwrap();
1026 let want = reference.len() / len;
1027 let mut bad = None;
1028 for (i, f) in frames.iter().enumerate() {
1029 let Some(chunk) = reference.get(i * len..(i + 1) * len) else {
1030 break;
1031 };
1032 if let Some(pos) = first_diff(f, chunk) {
1033 bad = Some((i, pos));
1034 break;
1035 }
1036 assert_eq!(
1037 f.len(),
1038 len,
1039 "{name}: frame {i} is {} samples, {len} expected",
1040 f.len()
1041 );
1042 }
1043 match bad {
1044 None if frames.len() == want => {
1045 passed += 1;
1046 table.push_str(&format!(
1047 "{name:<16} {:>3}/{want:<3} frames bit-exact\n",
1048 frames.len()
1049 ));
1050 }
1051 None => {
1052 failed.push(format!(
1053 "{name}: {} frames decoded, reference has {want}",
1054 frames.len()
1055 ));
1056 table.push_str(&format!(
1057 "{name:<16} {:>3}/{want:<3} FRAME COUNT\n",
1058 frames.len()
1059 ));
1060 }
1061 Some((i, pos)) => {
1062 failed.push(format!("{name}: frame {i} differs at byte {pos}"));
1063 table.push_str(&format!(
1064 "{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n",
1065 frames.len()
1066 ));
1067 }
1068 }
1069 }
1070 Err(e @ Error::Unsupported { .. }) => {
1071 refused.push(name.clone());
1072 table.push_str(&format!("{name:<16} refused: {e}\n"));
1073 }
1074 Err(e) => {
1075 failed.push(format!("{name}: {e}"));
1076 table.push_str(&format!("{name:<16} ERROR {e}\n"));
1077 }
1078 }
1079 }
1080 eprintln!("{table}");
1081 eprintln!(
1082 "full-sequence: {passed} bit-exact, {} refused by name, {} failed",
1083 refused.len(),
1084 failed.len()
1085 );
1086 assert!(failed.is_empty(), "{failed:#?}");
1087}
1088
1089/// Decode a whole stream in decode order rather than display order.
1090fn decode_all_in_decode_order(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> {
1091 let mut dec = Decoder::new();
1092 dec.set_output_order(ec_h264::OutputOrder::Decode);
1093 let mut frames = Vec::new();
1094 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
1095 if dec.push_nal(nal)? == NalOutcome::PictureBoundary {
1096 dec.end_picture()?;
1097 dec.push_nal(nal)?;
1098 }
1099 while let Some(f) = dec.next_frame() {
1100 frames.push(frame_bytes(&f));
1101 }
1102 }
1103 dec.flush()?;
1104 while let Some(f) = dec.next_frame() {
1105 frames.push(frame_bytes(&f));
1106 }
1107 Ok(frames)
1108}
1109
1110/// Count I, P and B slices in an Annex B stream, straight from the slice
1111/// headers. A test that claims to exercise B pictures has to prove the encoder
1112/// actually produced some — x264's adaptive decision drops them on flat
1113/// synthetic sources, and the test would then pass while measuring nothing.
1114fn slice_type_counts(bytes: &[u8]) -> [usize; 3] {
1115 let mut counts = [0usize; 3];
1116 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
1117 let Some((&header, payload)) = nal.split_first() else {
1118 continue;
1119 };
1120 if !matches!(header & 0x1F, 1 | 5) {
1121 continue;
1122 }
1123 let mut r = ec_core::BitReader::new(payload);
1124 if r.read_ue().is_err() {
1125 continue;
1126 }
1127 let Ok(code) = r.read_ue() else { continue };
1128 match code % 5 {
1129 0 => counts[1] += 1,
1130 1 => counts[2] += 1,
1131 2 => counts[0] += 1,
1132 _ => {}
1133 }
1134 }
1135 counts
1136}
1137
1138/// A GOP with B pictures, every frame bit-exact against ffmpeg, under both
1139/// entropy coders and both direct modes.
1140///
1141/// B pictures are where the decoded picture buffer earns its keep: two
1142/// reference lists, direct prediction from a co-located picture, implicit
1143/// weighting, and pictures that leave the buffer in a different order than
1144/// they arrived.
1145#[test]
1146fn b_pictures_match_ffmpeg_every_frame() {
1147 if !have_ffmpeg() {
1148 eprintln!("SKIP: ffmpeg not on PATH");
1149 return;
1150 }
1151 let dir = scratch("b-gop");
1152 let cases: &[(&str, &[&str])] = &[
1153 (
1154 "spatial",
1155 &[
1156 "-x264-params",
1157 "bframes=3:b-adapt=0:direct=spatial:weightp=0",
1158 ],
1159 ),
1160 (
1161 "temporal",
1162 &[
1163 "-x264-params",
1164 "bframes=3:b-adapt=0:direct=temporal:weightp=0",
1165 ],
1166 ),
1167 // B pictures used as references, which makes the buffer hold pictures
1168 // that are neither the newest nor the oldest.
1169 (
1170 "pyramid",
1171 &[
1172 "-x264-params",
1173 "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial",
1174 ],
1175 ),
1176 // Weighted prediction on: explicit for P, implicit for B.
1177 (
1178 "weighted",
1179 &[
1180 "-x264-params",
1181 "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial",
1182 ],
1183 ),
1184 ];
1185 let mut failures = Vec::new();
1186 let mut table = String::new();
1187 for (mode, profile) in ENTROPY_MODES {
1188 if mode == "cavlc" {
1189 continue; // baseline forbids B pictures; main covers CAVLC below
1190 }
1191 for (tag, case) in cases {
1192 for coder in ["ac", "0"] {
1193 let mut extra = vec!["-profile:v", "main", "-coder", coder, "-qp", "26"];
1194 extra.extend_from_slice(case);
1195 let name = format!("{tag}-{}", if coder == "ac" { "cabac" } else { "cavlc" });
1196 match x264_encode_gop(&dir, &name, "176x144", 20, &extra) {
1197 Some(stream) => {
1198 let counts = slice_type_counts(&std::fs::read(&stream).unwrap());
1199 if counts[2] == 0 {
1200 failures.push(format!("{name}: encoder produced no B slices"));
1201 continue;
1202 }
1203 match compare_sequence(&stream) {
1204 Ok(n) => table.push_str(&format!(
1205 "{name:<18} {n:>3} frames bit-exact ({} B slices)\n",
1206 counts[2]
1207 )),
1208 Err(e) => failures.push(format!("{name}: {e}")),
1209 }
1210 }
1211 None => failures.push(format!("{name}: ffmpeg cannot encode")),
1212 }
1213 }
1214 }
1215 let _ = profile;
1216 }
1217 let _ = std::fs::remove_dir_all(&dir);
1218 eprintln!("{table}");
1219 assert!(failures.is_empty(), "{failures:#?}");
1220}
1221
1222/// Frames come out in display order, and that is a real reordering.
1223///
1224/// Matching ffmpeg frame for frame already implies display order, but only if
1225/// the stream actually reorders — so this also decodes the same stream in
1226/// decode order and requires the two to differ. Without that second half the
1227/// test would pass on a decoder that never reorders anything.
1228#[test]
1229fn output_is_display_order_and_the_reorder_is_real() {
1230 if !have_ffmpeg() {
1231 eprintln!("SKIP: ffmpeg not on PATH");
1232 return;
1233 }
1234 let dir = scratch("order");
1235 let extra = [
1236 "-profile:v",
1237 "main",
1238 "-coder",
1239 "ac",
1240 "-qp",
1241 "26",
1242 "-x264-params",
1243 "bframes=3:b-adapt=0:b-pyramid=normal",
1244 ];
1245 let stream = x264_encode_gop(&dir, "reorder", "176x144", 20, &extra).expect("encode");
1246 let bytes = std::fs::read(&stream).unwrap();
1247 let counts = slice_type_counts(&bytes);
1248 assert!(counts[2] > 0, "the encoder produced no B slices to reorder");
1249 let display = decode_all(&bytes).expect("display order decode");
1250 let decode = decode_all_in_decode_order(&bytes).expect("decode order decode");
1251 let ffmpeg = ffmpeg_all_frames(&stream, display[0].len()).expect("ffmpeg");
1252 let _ = std::fs::remove_dir_all(&dir);
1253
1254 assert_eq!(display.len(), ffmpeg.len());
1255 assert_eq!(decode.len(), display.len());
1256 for (i, (a, b)) in display.iter().zip(&ffmpeg).enumerate() {
1257 assert!(
1258 first_diff(a, b).is_none(),
1259 "display-order frame {i} differs from ffmpeg"
1260 );
1261 assert_eq!(
1262 a.len(),
1263 b.len(),
1264 "display-order frame {i} is {} samples, ffmpeg gave {}",
1265 a.len(),
1266 b.len()
1267 );
1268 }
1269 // Every decode-order frame is somewhere in the display-order set: the two
1270 // are permutations of one another, not different pictures.
1271 for (i, f) in decode.iter().enumerate() {
1272 assert!(
1273 display.iter().any(|d| d == f),
1274 "decode-order frame {i} is not in the display-order output"
1275 );
1276 }
1277 let moved = decode.iter().zip(&display).filter(|(a, b)| a != b).count();
1278 assert!(
1279 moved > 0,
1280 "decode order and display order are identical: the stream does not \
1281 reorder, so this test proves nothing"
1282 );
1283 eprintln!(
1284 "{} of {} frames move under reordering",
1285 moved,
1286 display.len()
1287 );
1288}
1289
1290/// A gap in frame_num decodes instead of stalling (clause 8.2.5.2).
1291///
1292/// This is what a seek into the middle of a GOP looks like, and what a lossy
1293/// transport delivers: the pictures a later frame_num implies never arrived.
1294/// The spec infers them; a decoder that treats the gap as corruption drops
1295/// every following picture, which is the failure an editor sees as a frozen
1296/// preview after a seek.
1297#[test]
1298fn a_frame_num_gap_keeps_decoding() {
1299 if !have_ffmpeg() {
1300 eprintln!("SKIP: ffmpeg not on PATH");
1301 return;
1302 }
1303 let dir = scratch("gap");
1304 let extra = [
1305 "-profile:v",
1306 "baseline",
1307 "-qp",
1308 "26",
1309 "-x264-params",
1310 "bframes=0:ref=1:keyint=100",
1311 ];
1312 let stream = x264_encode_gop(&dir, "gap", "176x144", 12, &extra).expect("encode");
1313 let bytes = std::fs::read(&stream).unwrap();
1314 let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&bytes)
1315 .map(<[u8]>::to_vec)
1316 .collect();
1317 let _ = std::fs::remove_dir_all(&dir);
1318
1319 // Drop the fourth picture entirely, leaving frame_num 3 missing.
1320 let mut vcl_seen = 0;
1321 let mut dec = Decoder::new();
1322 let mut frames = 0usize;
1323 let mut errors = Vec::new();
1324 for unit in &units {
1325 if matches!(unit[0] & 0x1F, 1 | 5) {
1326 vcl_seen += 1;
1327 if vcl_seen == 4 {
1328 continue; // the lost picture
1329 }
1330 }
1331 match dec.push_nal(unit) {
1332 Ok(NalOutcome::PictureBoundary) => {
1333 dec.end_picture().expect("end_picture");
1334 dec.push_nal(unit).expect("re-push");
1335 }
1336 Ok(_) => {}
1337 Err(e) => errors.push(format!("{e}")),
1338 }
1339 while dec.next_frame().is_some() {
1340 frames += 1;
1341 }
1342 }
1343 dec.flush().expect("flush");
1344 while dec.next_frame().is_some() {
1345 frames += 1;
1346 }
1347 assert!(errors.is_empty(), "decoding stopped at the gap: {errors:?}");
1348 // 12 pictures coded, one dropped; the gap is filled by an inferred frame,
1349 // so every remaining picture still decodes and is output.
1350 assert!(
1351 frames >= 11,
1352 "only {frames} frames survived a single dropped picture"
1353 );
1354 eprintln!("frame_num gap: {frames} frames decoded after dropping one picture");
1355}
1356
1357/// Geometry and slice structure, over a GOP rather than one picture: cropping,
1358/// odd sizes, multiple slices per picture and the loop filter off, all with
1359/// inter prediction and reordering active.
1360#[test]
1361fn geometry_with_motion_matches_ffmpeg() {
1362 if !have_ffmpeg() {
1363 eprintln!("SKIP: ffmpeg not on PATH");
1364 return;
1365 }
1366 let dir = scratch("geometry-motion");
1367 let cases: &[(&str, &str, &[&str])] = &[
1368 ("hd", "1920x1080", &["bframes=2:b-adapt=0"]),
1369 ("odd", "1916x1078", &["bframes=2:b-adapt=0"]),
1370 // Neighbour availability stops at every slice boundary, and a motion
1371 // vector predictor at one sees no partition across it.
1372 ("slices", "352x288", &["bframes=2:b-adapt=0:slices=4"]),
1373 (
1374 "nodeblock",
1375 "352x288",
1376 &["bframes=2:b-adapt=0:no-deblock=1"],
1377 ),
1378 // One macroblock wide: every spatial neighbour is unavailable, which
1379 // is where the reference index of a missing partition matters most.
1380 ("tiny", "16x16", &["bframes=2:b-adapt=0"]),
1381 // Many references, so the list is long and reordering is real work.
1382 (
1383 "manyref",
1384 "352x288",
1385 &["bframes=3:b-adapt=0:ref=5:b-pyramid=normal"],
1386 ),
1387 ];
1388 let mut table = String::new();
1389 let mut failures = Vec::new();
1390 for coder in ["ac", "0"] {
1391 for (tag, size, params) in cases {
1392 let extra = vec![
1393 "-profile:v",
1394 "main",
1395 "-coder",
1396 coder,
1397 "-qp",
1398 "26",
1399 "-x264-params",
1400 params[0],
1401 ];
1402 let name = format!("{coder}-{tag}");
1403 match x264_encode_gop(&dir, &name, size, 10, &extra) {
1404 Some(stream) => match compare_sequence(&stream) {
1405 Ok(n) => {
1406 table.push_str(&format!("{name:<14} {size:<10} {n:>2} frames bit-exact\n"))
1407 }
1408 Err(e) => {
1409 table.push_str(&format!("{name:<14} {size:<10} {e}\n"));
1410 failures.push(format!("{name}: {e}"));
1411 }
1412 },
1413 None => failures.push(format!("{name}: ffmpeg cannot encode")),
1414 }
1415 }
1416 }
1417 let _ = std::fs::remove_dir_all(&dir);
1418 eprintln!("{table}");
1419 assert!(failures.is_empty(), "{failures:#?}");
1420}
1421
1422/// SP and SI slices are refused by name, proved against a stream that really
1423/// carries one.
1424///
1425/// No encoder here emits switching slices, so the stream is hand built: an SPS
1426/// and PPS this decoder accepts, then a slice header whose slice_type says SP.
1427/// Without it the refusal would be an untested string, which is how a refusal
1428/// becomes a hidden bug.
1429#[test]
1430fn switching_slices_are_refused_by_name() {
1431 use ec_core::BitWriter;
1432
1433 let mut annexb: Vec<u8> = Vec::new();
1434 let mut nal = |kind: u8, ref_idc: u8, payload: &[u8]| {
1435 annexb.extend_from_slice(&[0, 0, 0, 1]);
1436 annexb.push((ref_idc << 5) | kind);
1437 annexb.extend_from_slice(payload);
1438 };
1439
1440 let mut w = BitWriter::new();
1441 w.write_bits(66, 8); // profile_idc baseline
1442 w.write_bits(0, 8);
1443 w.write_bits(30, 8); // level_idc
1444 w.write_ue(0); // sps id
1445 w.write_ue(0); // log2_max_frame_num_minus4
1446 w.write_ue(2); // pic_order_cnt_type 2
1447 w.write_ue(1); // max_num_ref_frames
1448 w.write_bit(false); // gaps_in_frame_num_value_allowed
1449 w.write_ue(10); // pic_width_in_mbs_minus1 -> 176
1450 w.write_ue(8); // pic_height_in_map_units_minus1 -> 144
1451 w.write_bit(true); // frame_mbs_only
1452 w.write_bit(true); // direct_8x8_inference
1453 w.write_bit(false); // no cropping
1454 w.write_bit(false); // no vui
1455 w.write_bit(true); // rbsp stop bit
1456 w.align_to_byte();
1457 nal(7, 3, w.as_bytes());
1458
1459 let mut w = BitWriter::new();
1460 w.write_ue(0); // pps id
1461 w.write_ue(0); // sps id
1462 w.write_bit(false); // entropy_coding_mode
1463 w.write_bit(false); // bottom_field_pic_order_in_frame_present
1464 w.write_ue(0); // num_slice_groups_minus1
1465 w.write_ue(0); // num_ref_idx_l0_default_active_minus1
1466 w.write_ue(0); // num_ref_idx_l1_default_active_minus1
1467 w.write_bit(false); // weighted_pred
1468 w.write_bits(0, 2); // weighted_bipred_idc
1469 w.write_se(0); // pic_init_qp_minus26
1470 w.write_se(0); // pic_init_qs_minus26
1471 w.write_se(0); // chroma_qp_index_offset
1472 w.write_bit(false); // deblocking_filter_control_present
1473 w.write_bit(false); // constrained_intra_pred
1474 w.write_bit(false); // redundant_pic_cnt_present
1475 w.write_bit(true); // rbsp stop bit
1476 w.align_to_byte();
1477 nal(8, 3, w.as_bytes());
1478
1479 // A slice whose slice_type is SP (3), which is what has to be refused.
1480 let mut w = BitWriter::new();
1481 w.write_ue(0); // first_mb_in_slice
1482 w.write_ue(3); // slice_type: SP
1483 w.write_ue(0); // pps id
1484 w.write_bits(0, 4); // frame_num
1485 w.write_bit(false); // num_ref_idx_active_override_flag
1486 w.write_bit(false); // ref_pic_list_modification_flag_l0
1487 w.write_bit(false); // adaptive_ref_pic_marking_mode_flag
1488 w.write_bit(false); // sp_for_switch_flag
1489 w.write_se(0); // slice_qs_delta
1490 w.write_se(0); // slice_qp_delta
1491 w.write_bit(true);
1492 w.align_to_byte();
1493 nal(1, 2, w.as_bytes());
1494
1495 let mut dec = Decoder::new();
1496 let mut refusal = None;
1497 for unit in ec_h264_syntax::AnnexBIter::new(&annexb) {
1498 if let Err(e) = dec.push_nal(unit) {
1499 refusal = Some(e);
1500 break;
1501 }
1502 }
1503 match refusal {
1504 Some(Error::Unsupported { what, why }) => {
1505 assert!(
1506 what.contains("SP and SI"),
1507 "refused as {what} ({why}), expected the switching-slice refusal"
1508 );
1509 }
1510 other => panic!("expected an SP-slice refusal, got {other:?}"),
1511 }
1512}
1513
1514// ---------------------------------------------------------------------------
1515// Real library: the files actually on this machine, not fixtures.
1516// ---------------------------------------------------------------------------
1517
1518/// Compare a long stream against ffmpeg without holding it in memory: ffmpeg's
1519/// raw output is consumed from a pipe one frame at a time, in step with our
1520/// own decoding, so a 500-frame 1080p sweep costs two frames of memory rather
1521/// than three gigabytes.
1522fn compare_sequence_streamed(
1523 stream: &Path,
1524 frames_wanted: usize,
1525) -> Result<StreamedResult, String> {
1526 use std::io::Read;
1527
1528 let bytes = std::fs::read(stream).map_err(|e| e.to_string())?;
1529 let mut child = Command::new("ffmpeg")
1530 .args(["-v", "error", "-i"])
1531 .arg(stream)
1532 .args([
1533 "-frames:v",
1534 &frames_wanted.to_string(),
1535 "-f",
1536 "rawvideo",
1537 "-pix_fmt",
1538 "yuv420p",
1539 "-",
1540 ])
1541 .stdout(std::process::Stdio::piped())
1542 .stderr(std::process::Stdio::null())
1543 .spawn()
1544 .map_err(|e| e.to_string())?;
1545 let mut out = child.stdout.take().expect("piped stdout");
1546
1547 let mut dec = Decoder::new();
1548 let mut reference = Vec::new();
1549 let mut result = StreamedResult::default();
1550 let mut oracle_open = true;
1551 let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1552 result.produced += 1;
1553 if !oracle_open || result.compared >= frames_wanted {
1554 return;
1555 }
1556 reference.resize(frame.len(), 0);
1557 if out.read_exact(reference).is_err() {
1558 oracle_open = false;
1559 return;
1560 }
1561 if let Some(pos) = first_diff(&frame, reference) {
1562 result.diffs.push((result.compared, pos));
1563 }
1564 result.compared += 1;
1565 };
1566
1567 for nal in ec_h264_syntax::AnnexBIter::new(&bytes) {
1568 match dec.push_nal(nal) {
1569 Ok(NalOutcome::PictureBoundary) => {
1570 dec.end_picture().map_err(|e| format!("{e}"))?;
1571 dec.push_nal(nal).map_err(|e| format!("{e}"))?;
1572 }
1573 Ok(_) => {}
1574 Err(e) => return Err(format!("{e}")),
1575 }
1576 while let Some(f) = dec.next_frame() {
1577 take(frame_bytes(&f), &mut result, &mut reference);
1578 }
1579 }
1580 dec.flush().map_err(|e| format!("{e}"))?;
1581 while let Some(f) = dec.next_frame() {
1582 take(frame_bytes(&f), &mut result, &mut reference);
1583 }
1584 let _ = child.kill();
1585 let _ = child.wait();
1586 Ok(result)
1587}
1588
1589/// Outcome of a streamed comparison.
1590#[derive(Default)]
1591struct StreamedResult {
1592 /// Frames this decoder produced.
1593 produced: usize,
1594 /// Frames the oracle also produced, and which were therefore compared.
1595 compared: usize,
1596 /// `(frame index, byte offset)` of each mismatch.
1597 diffs: Vec<(usize, usize)>,
1598}
1599
1600/// Extract the video elementary stream of a real file as Annex B.
1601fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool {
1602 run(
1603 "ffmpeg",
1604 &[
1605 "-v",
1606 "error",
1607 "-y",
1608 "-i",
1609 &src.to_string_lossy(),
1610 "-map",
1611 "0:v:0",
1612 "-c",
1613 "copy",
1614 "-bsf:v",
1615 "h264_mp4toannexb",
1616 "-frames:v",
1617 &frames.to_string(),
1618 "-f",
1619 "h264",
1620 &dst.to_string_lossy(),
1621 ],
1622 )
1623}
1624
1625/// The same comparison, but demuxed from the container by [`ec_mp4`] instead
1626/// of extracted to Annex B by ffmpeg's bitstream filter.
1627///
1628/// Some real MP4s produce an elementary stream that ffmpeg itself then decodes
1629/// only three frames of, silently. That is a property of the extraction, not of
1630/// the file: reading the sample table directly and handing the `avcC` and the
1631/// length-prefixed samples to the packet entry surface leaves the oracle able to
1632/// decode the original file, so the comparison is real again.
1633fn compare_container_streamed(
1634 source: &Path,
1635 frames_wanted: usize,
1636) -> Result<StreamedResult, String> {
1637 use ec_core::registry::{Decoder as _, Demuxer as _};
1638 use std::io::Read;
1639
1640 let file = std::fs::File::open(source).map_err(|e| e.to_string())?;
1641 let mut demux = ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file))
1642 .map_err(|e| format!("ec-mp4 open: {e}"))?;
1643 let (stream_index, params) = demux
1644 .streams()
1645 .iter()
1646 .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
1647 .map(|s| (s.index, s.params.clone()))
1648 .ok_or("no H.264 track")?;
1649 let mut dec = ec_h264::H264Decoder::new(params).map_err(|e| format!("{e}"))?;
1650
1651 let mut child = Command::new("ffmpeg")
1652 .args(["-v", "error", "-i"])
1653 .arg(source)
1654 .args([
1655 "-map",
1656 "0:v:0",
1657 "-frames:v",
1658 &frames_wanted.to_string(),
1659 "-f",
1660 "rawvideo",
1661 "-pix_fmt",
1662 "yuv420p",
1663 "-",
1664 ])
1665 .stdout(std::process::Stdio::piped())
1666 .stderr(std::process::Stdio::null())
1667 .spawn()
1668 .map_err(|e| e.to_string())?;
1669 let mut out = child.stdout.take().expect("piped stdout");
1670
1671 let mut reference = Vec::new();
1672 let mut result = StreamedResult::default();
1673 let mut oracle_open = true;
1674 let mut take = |frame: Vec<u8>, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1675 result.produced += 1;
1676 if !oracle_open || result.compared >= frames_wanted {
1677 return;
1678 }
1679 reference.resize(frame.len(), 0);
1680 if out.read_exact(reference).is_err() {
1681 oracle_open = false;
1682 return;
1683 }
1684 if let Some(pos) = first_diff(&frame, reference) {
1685 result.diffs.push((result.compared, pos));
1686 }
1687 result.compared += 1;
1688 };
1689 let mut drain =
1690 |dec: &mut ec_h264::H264Decoder, result: &mut StreamedResult, reference: &mut Vec<u8>| {
1691 while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
1692 take(frame_bytes(&f), result, reference);
1693 }
1694 };
1695 while result.produced < frames_wanted {
1696 let packet = match demux.next_packet() {
1697 Ok(p) => p,
1698 Err(_) => break,
1699 };
1700 if packet.stream != stream_index {
1701 continue;
1702 }
1703 dec.send_packet(&packet).map_err(|e| format!("{e}"))?;
1704 drain(&mut dec, &mut result, &mut reference);
1705 }
1706 dec.flush().map_err(|e| format!("{e}"))?;
1707 drain(&mut dec, &mut result, &mut reference);
1708 let _ = child.kill();
1709 let _ = child.wait();
1710 Ok(result)
1711}
1712
1713/// Decode real H.264 files from this machine's library, several hundred frames
1714/// each, frame for frame against ffmpeg.
1715///
1716/// Synthetic clips and conformance vectors are both written by people trying to
1717/// exercise a decoder. Real files are written by encoders tuned for size, at
1718/// resolutions and GOP structures the fixtures never use, and they are the ones
1719/// a user actually opens. Every file either decodes bit-exactly or is refused
1720/// by name; a file that decodes to different pixels is a failure.
1721// lane-h264reallib: LOCAL-ONLY, and the reason lives in the attribute so it
1722// shows in `cargo test -- --list` instead of hiding in a skip print.
1723//
1724// The precondition is a PERSONAL MEDIA LIBRARY: the manifest is generated by
1725// `scripts/scan-real-library.sh`, which scans `~/Videos ~/Downloads ~/Music`
1726// by default and is gitignored precisely because it is machine-local. A
1727// runner host has none of those directories, so both of this test's possible
1728// behaviours there are wrong:
1729//
1730// - manifest absent -> the `SKIP: ... missing` early return, which prints
1731// green. That is the silent-skip class this batch is removing: a green
1732// that means "nothing was checked".
1733// - manifest present but its absolute paths unresolvable (a host that ran
1734// the scan script against an empty library) -> zero files swept and
1735// `decoded >= 3` fails. That is the red every fleet run currently eats,
1736// and it is red for a reason that has nothing to do with the decoder.
1737//
1738// Hence `#[ignore]` rather than an env gate: an env gate whose variable is
1739// absent on the runner prints the same green the missing manifest already
1740// prints, which is the defect rather than the fix. An ignore is visible in
1741// `--list`, cannot go green silently, and leaves the assertion itself intact
1742// -- "the sweep is the point" still holds on the machine that can run it.
1743//
1744// Run it on the workstation, where the library is:
1745// cargo test -p ec-h264 --test conformance real_library_streams_match_ffmpeg -- --ignored
1746#[ignore = "sweeps the PERSONAL media library (~/Videos, ~/Downloads, ~/Music) through the gitignored fixtures/real-library-manifest.tsv; MINUTES of wall time (measured past 840 s on the workstation), so workstation only -- budget an hour, it is not wedged. A runner host has no such library, so the test is either a silent green or a red for the wrong reason. Run it on the workstation with --ignored."]
1747#[test]
1748fn real_library_streams_match_ffmpeg() {
1749 if !have_ffmpeg() {
1750 eprintln!("SKIP: ffmpeg not on PATH");
1751 return;
1752 }
1753 let manifest =
1754 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
1755 let Ok(text) = std::fs::read_to_string(&manifest) else {
1756 eprintln!("SKIP: {} missing", manifest.display());
1757 return;
1758 };
1759 let dir = scratch("real-library");
1760 const FRAMES: usize = 500;
1761 /// A file counts as swept only when the oracle stayed with us this long.
1762 const MIN_FRAMES: usize = 100;
1763 let mut table = String::new();
1764 let mut decoded = 0usize;
1765 let mut refused = 0usize;
1766 let mut failures = Vec::new();
1767 let mut seen_containers = std::collections::BTreeSet::new();
1768
1769 for line in text.lines().skip(1) {
1770 let mut f = line.split('\t');
1771 let (Some(path), Some(container), Some(vcodec)) = (f.next(), f.next(), f.next()) else {
1772 continue;
1773 };
1774 if vcodec != "h264" || !Path::new(path).is_file() {
1775 continue;
1776 }
1777 // One file per container family per resolution class keeps the sweep
1778 // to a few minutes while still covering both demuxers.
1779 let width = f.next().unwrap_or("0");
1780 let key = (container.to_string(), width.to_string());
1781 if !seen_containers.insert(key) {
1782 continue;
1783 }
1784 let name: String = Path::new(path)
1785 .file_name()
1786 .map(|n| n.to_string_lossy().chars().take(38).collect())
1787 .unwrap_or_default();
1788 let annexb = dir.join("stream.264");
1789 if !extract_annexb(Path::new(path), &annexb, FRAMES) {
1790 table.push_str(&format!("{name:<40} {container:<12} not extractable\n"));
1791 continue;
1792 }
1793 match compare_sequence_streamed(&annexb, FRAMES) {
1794 Ok(r) if !r.diffs.is_empty() => {
1795 failures.push(format!(
1796 "{name}: {} of {} frames differ",
1797 r.diffs.len(),
1798 r.compared
1799 ));
1800 table.push_str(&format!(
1801 "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {}\n",
1802 r.diffs.len(),
1803 r.compared
1804 ));
1805 }
1806 // The oracle stopped before we did: ffmpeg gave up on the elementary
1807 // stream its own bitstream filter produced. That is a property of
1808 // the extraction, so the file is re-run straight out of the
1809 // container, where the oracle can read the original samples.
1810 Ok(r) if r.compared < r.produced.min(MIN_FRAMES) => {
1811 match compare_container_streamed(Path::new(path), FRAMES) {
1812 Ok(c) if !c.diffs.is_empty() => {
1813 failures.push(format!(
1814 "{name} (container demux): {} of {} frames differ",
1815 c.diffs.len(),
1816 c.compared
1817 ));
1818 table.push_str(&format!(
1819 "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {} \
1820 (container demux)\n",
1821 c.diffs.len(),
1822 c.compared
1823 ));
1824 }
1825 Ok(c) if c.compared >= MIN_FRAMES => {
1826 decoded += 1;
1827 table.push_str(&format!(
1828 "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact \
1829 (container demux)\n",
1830 c.compared
1831 ));
1832 }
1833 Ok(c) => {
1834 table.push_str(&format!(
1835 "{name:<40} {container:<12} {width:>5}px oracle short both ways: \
1836 ffmpeg gave {} frames, we decoded {}\n",
1837 c.compared, c.produced
1838 ));
1839 }
1840 Err(e) => {
1841 table.push_str(&format!(
1842 "{name:<40} {container:<12} {width:>5}px oracle short, container \
1843 demux failed: {e}\n"
1844 ));
1845 }
1846 }
1847 }
1848 Ok(r) => {
1849 decoded += 1;
1850 table.push_str(&format!(
1851 "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact\n",
1852 r.compared
1853 ));
1854 }
1855 Err(e) if e.contains("unsupported") => {
1856 refused += 1;
1857 table.push_str(&format!(
1858 "{name:<40} {container:<12} {width:>5}px refused: {e}\n"
1859 ));
1860 }
1861 Err(e) => {
1862 failures.push(format!("{name}: {e}"));
1863 table.push_str(&format!(
1864 "{name:<40} {container:<12} {width:>5}px ERROR {e}\n"
1865 ));
1866 }
1867 }
1868 }
1869 let _ = std::fs::remove_dir_all(&dir);
1870 eprintln!("{table}");
1871 eprintln!("real library: {decoded} decoded bit-exact, {refused} refused by name");
1872 assert!(failures.is_empty(), "{failures:#?}");
1873 assert!(
1874 decoded >= 3,
1875 "only {decoded} real files swept end to end; the sweep is the point"
1876 );
1877}
1878
1879/// The registry entry surface, driven the way a demuxer drives it: one access
1880/// unit per packet, frames pulled with `receive_frame`.
1881///
1882/// This is where display order has to actually arrive. Everything above tests
1883/// the NAL-level API; a player never touches that one, so a reordering decoder
1884/// whose packet API still hands back decode order would look correct in every
1885/// other test here and wrong on screen.
1886#[test]
1887fn packet_entry_surface_reorders_and_carries_timestamps() {
1888 if !have_ffmpeg() {
1889 eprintln!("SKIP: ffmpeg not on PATH");
1890 return;
1891 }
1892 let dir = scratch("entry");
1893 let extra = [
1894 "-profile:v",
1895 "main",
1896 "-coder",
1897 "ac",
1898 "-qp",
1899 "26",
1900 "-x264-params",
1901 "bframes=3:b-adapt=0:b-pyramid=normal",
1902 ];
1903 let stream = x264_encode_gop(&dir, "entry", "176x144", 16, &extra).expect("encode");
1904 let data = std::fs::read(&stream).unwrap();
1905 assert!(
1906 slice_type_counts(&data)[2] > 0,
1907 "the encoder produced no B slices"
1908 );
1909
1910 // Split the stream into access units the way a demuxer would: a new one
1911 // starts at each parameter set or first slice of a picture.
1912 let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
1913 .map(<[u8]>::to_vec)
1914 .collect();
1915 let mut access_units: Vec<Vec<u8>> = Vec::new();
1916 let mut current: Vec<u8> = Vec::new();
1917 let mut current_has_slice = false;
1918 for unit in &units {
1919 let is_slice = matches!(unit[0] & 0x1F, 1 | 5);
1920 if is_slice && current_has_slice {
1921 access_units.push(std::mem::take(&mut current));
1922 current_has_slice = false;
1923 }
1924 current_has_slice |= is_slice;
1925 current.extend_from_slice(&[0, 0, 0, 1]);
1926 current.extend_from_slice(unit);
1927 }
1928 if current_has_slice {
1929 access_units.push(current);
1930 }
1931
1932 let time_base = TimeBase::new(1, 25);
1933 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder");
1934 let mut out: Vec<(i64, Vec<u8>)> = Vec::new();
1935 for (i, au) in access_units.iter().enumerate() {
1936 let packet = Packet::new(0, time_base, au.clone()).with_pts(i as i64);
1937 decoder.send_packet(&packet).expect("send_packet");
1938 while let Ok(Frame::Video(f)) = decoder.receive_frame() {
1939 out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f)));
1940 }
1941 }
1942 decoder.flush().expect("flush");
1943 while let Ok(Frame::Video(f)) = decoder.receive_frame() {
1944 out.push((f.pts.map(|t| t.ticks).unwrap_or(-1), frame_bytes(&f)));
1945 }
1946
1947 let expected = ffmpeg_all_frames(&stream, out[0].1.len()).expect("ffmpeg");
1948 let _ = std::fs::remove_dir_all(&dir);
1949 assert_eq!(out.len(), expected.len(), "frame count");
1950 for (i, ((_, ours), theirs)) in out.iter().zip(&expected).enumerate() {
1951 assert!(
1952 first_diff(ours, theirs).is_none(),
1953 "packet-path frame {i} differs from ffmpeg"
1954 );
1955 assert_eq!(
1956 ours.len(),
1957 theirs.len(),
1958 "packet-path frame {i} is {} samples, ffmpeg gave {}",
1959 ours.len(),
1960 theirs.len()
1961 );
1962 }
1963 // Each packet was tagged with its own index in *decode* order, so the tag
1964 // that comes back on a picture says which packet produced it. Decoding the
1965 // same stream in decode order gives the pixels for each of those indices,
1966 // and the two have to line up: that is the timestamp staying with its
1967 // picture across the reordering, not merely arriving in some order.
1968 let by_decode_order = decode_all_in_decode_order(&data).expect("decode order");
1969 assert_eq!(by_decode_order.len(), out.len());
1970 for (position, (tag, pixels)) in out.iter().enumerate() {
1971 let tag = usize::try_from(*tag).expect("a tag was lost");
1972 assert!(
1973 first_diff(pixels, &by_decode_order[tag]).is_none(),
1974 "output position {position} carries the timestamp of packet {tag}, \
1975 but its pixels are a different picture"
1976 );
1977 assert_eq!(
1978 pixels.len(),
1979 by_decode_order[tag].len(),
1980 "output position {position} is {} samples, decode-order frame {tag} is {}",
1981 pixels.len(),
1982 by_decode_order[tag].len()
1983 );
1984 }
1985 let order: Vec<i64> = out.iter().map(|(pts, _)| *pts).collect();
1986 assert_ne!(
1987 order,
1988 (0..order.len() as i64).collect::<Vec<_>>(),
1989 "output order equals packet order, so no reordering happened"
1990 );
1991 eprintln!(
1992 "packet entry surface: {} frames, packets emitted in order {order:?}",
1993 out.len()
1994 );
1995}
1996
1997/// Spatial direct prediction whose co-located picture is itself a B picture.
1998///
1999/// With a B pyramid the picture at RefPicList1[0] of the first B in a run is a
2000/// coded B picture, so its blocks are bi-predicted and carry two reference
2001/// indices. colZeroFlag (8.4.1.2.2) reads refIdxCol — the index of the list
2002/// 8.4.1.2.1 selected — and a decoder that instead accepts "either index is 0"
2003/// zeroes motion vectors that must keep their prediction. Several references
2004/// are what makes the two readings differ at all, so this needs `-refs`.
2005#[test]
2006fn spatial_direct_over_a_b_reference_matches_ffmpeg() {
2007 if !have_ffmpeg() {
2008 eprintln!("SKIP: ffmpeg not on PATH");
2009 return;
2010 }
2011 let dir = scratch("direct-bref");
2012 let mut failures = Vec::new();
2013 for (tag, coder) in [("cabac", "ac"), ("cavlc", "0")] {
2014 let extra = [
2015 "-profile:v",
2016 "high",
2017 "-coder",
2018 coder,
2019 "-qp",
2020 "24",
2021 "-bf",
2022 "3",
2023 "-refs",
2024 "4",
2025 "-x264-params",
2026 "b-adapt=0:b-pyramid=normal:direct=spatial:8x8dct=1",
2027 ];
2028 match x264_encode_gop(&dir, tag, "352x288", 40, &extra) {
2029 None => failures.push(format!("{tag}: ffmpeg cannot encode")),
2030 Some(stream) => match compare_sequence(&stream) {
2031 Ok(n) => eprintln!("b-pyramid direct {tag}: {n} frames bit-exact"),
2032 Err(e) => failures.push(format!("{tag}: {e}")),
2033 },
2034 }
2035 }
2036 let _ = std::fs::remove_dir_all(&dir);
2037 assert!(failures.is_empty(), "{failures:#?}");
2038}
2039
2040/// True when the stream's picture parameter set enables the 8x8 transform.
2041///
2042/// Without this the sweep below would silently prove nothing: an encoder that
2043/// quietly dropped back to 4x4 would pass every comparison while never coding
2044/// a single transform_size_8x8_flag.
2045fn pps_enables_8x8(stream: &Path) -> bool {
2046 let bytes = std::fs::read(stream).unwrap_or_default();
2047 let mut rbsp = Vec::new();
2048 let mut sps = None;
2049 for nal in ec_h264_syntax::AnnexBIter::new(&bytes) {
2050 let Some((&header, payload)) = nal.split_first() else {
2051 continue;
2052 };
2053 let Ok(h) = ec_h264_syntax::NalHeader::parse(header) else {
2054 continue;
2055 };
2056 ec_h264_syntax::unescape_rbsp(payload, &mut rbsp);
2057 match h.unit_type {
2058 ec_h264_syntax::NalUnitType::Sps => sps = ec_h264_syntax::Sps::parse(&rbsp).ok(),
2059 ec_h264_syntax::NalUnitType::Pps => {
2060 if let Ok(p) = ec_h264_syntax::Pps::parse(&rbsp, |_| sps.as_ref()) {
2061 return p.transform_8x8_mode;
2062 }
2063 }
2064 _ => {}
2065 }
2066 }
2067 false
2068}
2069
2070/// The same transform in inter macroblocks: P and B partitions carry the flag
2071/// only when no 8x8 is split further (7.3.5), the residual rides the inter
2072/// scaling list, and the deblocker must leave the internal 4-sample edges of an
2073/// 8x8 macroblock alone (8.7).
2074#[test]
2075fn high_profile_8x8_inter_sequences_match_ffmpeg() {
2076 if !have_ffmpeg() {
2077 eprintln!("SKIP: ffmpeg not on PATH");
2078 return;
2079 }
2080 let dir = scratch("high8x8-seq");
2081 let mut failures = Vec::new();
2082 let cases: &[(&str, &[&str])] = &[
2083 (
2084 "p-cabac",
2085 &["-profile:v", "high", "-coder", "ac", "-bf", "0"],
2086 ),
2087 (
2088 "p-cavlc",
2089 &["-profile:v", "high", "-coder", "0", "-bf", "0"],
2090 ),
2091 (
2092 "b-cabac",
2093 &[
2094 "-profile:v",
2095 "high",
2096 "-coder",
2097 "ac",
2098 "-bf",
2099 "2",
2100 "-x264-params",
2101 "b-adapt=0",
2102 ],
2103 ),
2104 (
2105 "b-cavlc",
2106 &[
2107 "-profile:v",
2108 "high",
2109 "-coder",
2110 "0",
2111 "-bf",
2112 "2",
2113 "-x264-params",
2114 "b-adapt=0",
2115 ],
2116 ),
2117 // Sub-8x8 partitions: every macroblock that splits below 8x8 must not
2118 // carry the flag, and the neighbouring context has to agree.
2119 (
2120 "subpart",
2121 &[
2122 "-profile:v",
2123 "high",
2124 "-coder",
2125 "ac",
2126 "-bf",
2127 "0",
2128 "-x264-params",
2129 "partitions=all:8x8dct=1",
2130 ],
2131 ),
2132 ];
2133 for (tag, extra) in cases {
2134 let mut args = extra.to_vec();
2135 args.extend(["-qp", "26"]);
2136 match x264_encode_gop(&dir, tag, "176x144", 12, &args) {
2137 None => failures.push(format!("{tag}: ffmpeg cannot encode")),
2138 Some(stream) => match compare_sequence(&stream) {
2139 Ok(n) => {
2140 assert!(
2141 pps_enables_8x8(&stream),
2142 "{tag}: encoder did not enable the 8x8 transform"
2143 );
2144 eprintln!("8x8 {tag}: {n} frames bit-exact");
2145 }
2146 Err(e) => failures.push(format!("{tag}: {e}")),
2147 },
2148 }
2149 }
2150 let _ = std::fs::remove_dir_all(&dir);
2151 assert!(failures.is_empty(), "{failures:#?}");
2152}
2153
2154/// An open-GOP boundary's non-IDR I picture (`nal_unit_type` 1, not 5) is
2155/// followed in decode order by leading B pictures that display *before* it
2156/// but predict from the previous GOP. A decoder started fresh at that I
2157/// picture — what a seek does — never decoded those previous-GOP references,
2158/// so it must not hand back the leading B pictures at all (H.264's analogue
2159/// of HEVC's RASL/`NoRaslOutputFlag` case): output must resume at the I
2160/// picture itself, per D.2.8 absent a recovery_point SEI.
2161#[test]
2162fn h264_seek_matches_linear_open_gop() {
2163 if !have_ffmpeg() {
2164 eprintln!("SKIP: ffmpeg not on PATH");
2165 return;
2166 }
2167 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4");
2168 if !require_fixtures(
2169 &src,
2170 "the open-GOP fixture",
2171 "scripts/gen-fixtures.sh (fixtures/video/h264-open-gop.mp4)",
2172 ) {
2173 return;
2174 }
2175 let dir = scratch("open-gop");
2176 std::fs::create_dir_all(&dir).unwrap();
2177 let annexb = dir.join("open-gop.264");
2178 assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction");
2179 let data = std::fs::read(&annexb).unwrap();
2180 let _ = std::fs::remove_dir_all(&dir);
2181
2182 // Split into access units the way a demuxer would: a new one starts at
2183 // each slice NAL (type 1 or 5).
2184 let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
2185 .map(<[u8]>::to_vec)
2186 .collect();
2187 let mut access_units: Vec<Vec<u8>> = Vec::new();
2188 let mut current: Vec<u8> = Vec::new();
2189 let mut current_has_slice = false;
2190 for unit in &units {
2191 let is_slice = matches!(unit[0] & 0x1F, 1 | 5);
2192 if is_slice && current_has_slice {
2193 access_units.push(std::mem::take(&mut current));
2194 current_has_slice = false;
2195 }
2196 current_has_slice |= is_slice;
2197 current.extend_from_slice(&[0, 0, 0, 1]);
2198 current.extend_from_slice(unit);
2199 }
2200 if current_has_slice {
2201 access_units.push(current);
2202 }
2203
2204 // Linear decode: every picture from the start, display frame 30 kept for
2205 // comparison (the fixture's second I picture, `keyint=30`).
2206 const TARGET: usize = 30;
2207 let mut dec = Decoder::new();
2208 let mut linear_frame_30 = None;
2209 let mut index = 0usize;
2210 for nal in ec_h264_syntax::AnnexBIter::new(&data) {
2211 if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary {
2212 dec.end_picture().expect("end_picture");
2213 dec.push_nal(nal).expect("re-push");
2214 }
2215 while let Some(f) = dec.next_frame() {
2216 if index == TARGET {
2217 linear_frame_30 = Some(frame_bytes(&f));
2218 }
2219 index += 1;
2220 }
2221 }
2222 dec.flush().expect("flush");
2223 while let Some(f) = dec.next_frame() {
2224 if index == TARGET {
2225 linear_frame_30 = Some(frame_bytes(&f));
2226 }
2227 index += 1;
2228 }
2229 let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
2230
2231 // Find the access unit whose first VCL NAL is a non-IDR I slice
2232 // (`nal_unit_type` 1, `slice_type % 5 == 2`) — the open-GOP boundary.
2233 let is_open_gop_i = |au: &[u8]| -> bool {
2234 let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else {
2235 return false;
2236 };
2237 if header & 0x1F != 1 {
2238 return false;
2239 }
2240 let mut r = ec_core::BitReader::new(payload);
2241 if r.read_ue().is_err() {
2242 return false;
2243 }
2244 matches!(r.read_ue(), Ok(code) if code % 5 == 2)
2245 };
2246 let cra_at = access_units
2247 .iter()
2248 .position(|au| is_open_gop_i(au))
2249 .expect("an open-GOP I access unit exists");
2250
2251 // A seek reuses the parameter sets a decoder already learned; a fresh one
2252 // is primed the way `Decoder::reset_pictures`'s doc comment expects: the
2253 // leading IDR's parameter sets are decoded and its picture discarded.
2254 let mut seek_dec = Decoder::new();
2255 for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) {
2256 seek_dec.push_nal(nal).expect("prime parameter sets");
2257 }
2258 seek_dec.end_picture().expect("end priming IDR");
2259 seek_dec.reset_pictures();
2260
2261 let mut seeked_frame = None;
2262 'outer: for au in &access_units[cra_at..] {
2263 for nal in ec_h264_syntax::AnnexBIter::new(au) {
2264 if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary {
2265 seek_dec.end_picture().expect("end_picture");
2266 seek_dec.push_nal(nal).expect("re-push");
2267 }
2268 }
2269 if let Some(f) = seek_dec.next_frame() {
2270 seeked_frame = Some(frame_bytes(&f));
2271 break 'outer;
2272 }
2273 }
2274 if seeked_frame.is_none() {
2275 seek_dec.flush().expect("flush");
2276 seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f));
2277 }
2278 let seeked_frame = seeked_frame.expect("a frame came out after the seek");
2279
2280 assert_eq!(
2281 seeked_frame, linear_frame_30,
2282 "seeking to the open-GOP I before frame 30 handed back a different \
2283 picture than a linear decode of frame 30 — leading pictures with \
2284 missing references were not dropped"
2285 );
2286}