forge
Explore
Log in

Don't you dare go Hollow

CABAC conformance sweep, QP and geometry matrices, no-panic floor

Browse files at this commit

c7660d1cdc6f3fed896d9e115d8dddb8db9ff4adAhmet Kaan GümüşParent: 2127132
  • test
    • CABAC conformance sweep, QP and geometry matrices, no-panic floor
Show full message
test(h264): CABAC conformance sweep, QP and geometry matrices, no-panic floor

The vector sweep is dynamic, so the eight JVT streams whose only barrier was
CABAC I-decode moved from refused to bit-exact on their own: CABA1_SVA_B,
CABA2_SVA_B, CABA3_SVA_B, CACQP3_Sony_D and CANL1..4_SVA_B. 18 bit-exact and
17 refused becomes 26 bit-exact and 9 refused; CAMACI3_Sony_C, CAMASL3_Sony_B
and MR9_BT_B moved from the CABAC refusal to the interlaced one, which is what
they also use, and nothing is unaccounted for.

Added around that:
- the 51-quantiser ffmpeg matrix and the geometry/slice matrix now run under
  both entropy coders (`-coder ac` for CABAC, verified to set
  entropy_coding_mode_flag), which walks context initialisation across every
  SliceQPY and re-initialisation across slice boundaries;
- inter slices under CABAC are refused by name after the intra pictures of the
  same GOP decode, so the arithmetic decoder cannot be mistaken for P and B
  support;
- the 8x8 transform refusal is proved under CABAC as well as CAVLC, where the
  flag is a context-coded bin;
- the zero-allocation proof and the corrupt-stream no-panic sweep both gained
  a CABAC stream.

ns/MB, first IDR, single thread, deblocking included: CABA1_SVA_B 1860,
CABA3_SVA_B 1892, against 923..1321 for the CAVLC streams.
crates/ec-h264/tests/conformance.rsmodified+194 -74
@@ -257,30 +257,36 @@ fn steady_state_decode_loop_zero_alloc() {
257257 eprintln!("SKIP: fixtures missing");
258258 return;
259259 }
260- let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture");
261- let bytes = std::fs::read(stream).unwrap();
260+ // One stream per entropy coder: the CABAC reader carries its 402 context
261+ // variables inline for exactly this reason.
262262 let mut dec = Decoder::new();
263- // Warm-up: full first picture, growing every reusable buffer.
264- let _ = dec.decode_first_idr(&bytes).expect("warm-up decode");
263+ for name in ["BA1_Sony_D", "CABA1_SVA_B"] {
264+ let stream = find_stream(&base.join(name)).expect("fixture");
265+ let bytes = std::fs::read(stream).unwrap();
266+ // Warm-up: full first picture, growing every reusable buffer.
267+ let _ = dec.decode_first_idr(&bytes).expect("warm-up decode");
265268
266- // Steady state: same IDR slices again, counted.
267- let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
268- ALLOCS.store(0, Ordering::SeqCst);
269- COUNTING_HERE.with(|c| c.set(true));
270- let mut decoded = false;
271- for nal in &nals {
272- match dec.push_nal(nal) {
273- Ok(ec_h264::NalOutcome::PictureBoundary) => break,
274- Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true,
275- Ok(_) => {}
276- Err(e) => panic!("steady-state push failed: {e}"),
269+ // Steady state: same IDR slices again, counted.
270+ let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect();
271+ ALLOCS.store(0, Ordering::SeqCst);
272+ COUNTING_HERE.with(|c| c.set(true));
273+ let mut decoded = false;
274+ for nal in &nals {
275+ match dec.push_nal(nal) {
276+ Ok(ec_h264::NalOutcome::PictureBoundary) => break,
277+ Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true,
278+ Ok(_) => {}
279+ Err(e) => panic!("steady-state push failed: {e}"),
280+ }
277281 }
282+ dec.end_picture().expect("end_picture");
283+ COUNTING_HERE.with(|c| c.set(false));
284+ assert!(decoded, "no slice decoded in steady-state pass of {name}");
285+ let n = ALLOCS.load(Ordering::SeqCst);
286+ assert_eq!(n, 0, "{name}: steady-state decode loop allocated {n} times");
278287 }
279- dec.end_picture().expect("end_picture");
280- COUNTING_HERE.with(|c| c.set(false));
281- assert!(decoded, "no slice decoded in steady-state pass");
282- let n = ALLOCS.load(Ordering::SeqCst);
283- assert_eq!(n, 0, "steady-state decode loop allocated {n} times");
288+ let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap();
289+ let _ = dec.decode_first_idr(&bytes).expect("decode");
284290
285291 // Sanity: the counter is alive — frame emission does allocate.
286292 ALLOCS.store(0, Ordering::SeqCst);
@@ -304,7 +310,13 @@ fn ns_per_macroblock_measurement() {
304310 eprintln!("SKIP: fixtures missing");
305311 return;
306312 }
307- for name in ["BA1_Sony_D", "CI_MW_D", "NL1_Sony_D"] {
313+ for name in [
314+ "BA1_Sony_D",
315+ "CI_MW_D",
316+ "NL1_Sony_D",
317+ "CABA1_SVA_B",
318+ "CABA3_SVA_B",
319+ ] {
308320 let Some(stream) = find_stream(&base.join(name)) else {
309321 continue;
310322 };
@@ -348,8 +360,19 @@ fn corrupt_streams_never_panic() {
348360 eprintln!("SKIP: fixtures missing");
349361 return;
350362 }
351- let stream = find_stream(&base.join("BA1_Sony_D")).expect("BA1_Sony_D fixture");
352- let bytes = std::fs::read(stream).unwrap();
363+ // One stream per entropy coder: CABAC's arithmetic decoder indexes context
364+ // and coefficient arrays from stream-derived values, so it needs the same
365+ // no-panic floor as the CAVLC tables.
366+ for name in ["BA1_Sony_D", "CABA1_SVA_B"] {
367+ let stream = find_stream(&base.join(name)).expect("fixture");
368+ corrupt_sweep(&std::fs::read(stream).unwrap());
369+ }
370+}
371+
372+/// Truncate and bit-flip `bytes` many ways; every decode must return, error or
373+/// succeed, and never panic.
374+fn corrupt_sweep(bytes: &[u8]) {
375+ let bytes = bytes.to_vec();
353376
354377 // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data.
355378 for len in (0..bytes.len().min(4096))
@@ -474,12 +497,23 @@ fn round_trip(dir: &Path, tag: &str, size: &str, extra: &[&str]) -> Result<usize
474497 .count())
475498 }
476499
477-/// Every quantisation parameter, bit-exact against ffmpeg.
500+/// The two entropy coders, as ffmpeg encoder arguments. Baseline forces CAVLC;
501+/// Main with `-coder ac` selects CABAC. Neither profile admits the 8x8
502+/// transform, so both stay inside this release's scope.
503+const ENTROPY_MODES: [(&str, &[&str]); 2] = [
504+ ("cavlc", &["-profile:v", "baseline"]),
505+ ("cabac", &["-profile:v", "main", "-coder", "ac"]),
506+];
507+
508+/// Every quantisation parameter, bit-exact against ffmpeg, under both entropy
509+/// coders.
478510 ///
479511 /// The deblocking filter's alpha, beta and tC0 tables (8-16 and 8-17) are
480512 /// indexed by QP; the conformance vectors touch only a few of their 52 rows,
481513 /// and a whole wrong column there passes the vectors (it did, once). One
482-/// all-intra Baseline picture per QP covers every row.
514+/// all-intra picture per QP covers every row. Under CABAC the same sweep walks
515+/// the context initialisation of clause 9.3.1.1 across all 52 SliceQPY values,
516+/// which the fixed-QP conformance vectors barely touch.
483517 #[test]
484518 fn every_quantiser_matches_ffmpeg() {
485519 if !have_ffmpeg() {
@@ -487,22 +521,27 @@ fn every_quantiser_matches_ffmpeg() {
487521 return;
488522 }
489523 let dir = scratch("qp-sweep");
490- let mut checked = 0usize;
491524 let mut failures = Vec::new();
492- for qp in 1..=51u32 {
493- // Baseline is CAVLC, 4:2:0, no 8x8 transform and no scaling matrices:
494- // exactly this release's scope, with the loop filter on.
495- let extra = ["-profile:v", "baseline", "-qp", &qp.to_string() as &str];
496- match round_trip(&dir, &format!("q{qp}"), "176x144", &extra) {
497- Ok(0) => checked += 1,
498- Ok(n) => failures.push(format!("qp {qp}: {n} bytes differ")),
499- Err(e) => failures.push(e),
525+ for (mode, profile) in ENTROPY_MODES {
526+ let mut checked = 0usize;
527+ for qp in 1..=51u32 {
528+ let mut extra = profile.to_vec();
529+ let qp_string = qp.to_string();
530+ extra.extend(["-qp", &qp_string]);
531+ match round_trip(&dir, &format!("{mode}-q{qp}"), "176x144", &extra) {
532+ Ok(0) => checked += 1,
533+ Ok(n) => failures.push(format!("{mode} qp {qp}: {n} bytes differ")),
534+ Err(e) => failures.push(e),
535+ }
500536 }
537+ assert!(
538+ checked >= 40,
539+ "too few {mode} quantisers exercised: {checked}"
540+ );
541+ eprintln!("{mode}: {checked} quantisers bit-exact against ffmpeg");
501542 }
502543 let _ = std::fs::remove_dir_all(&dir);
503544 assert!(failures.is_empty(), "{failures:#?}");
504- assert!(checked >= 40, "too few quantisers exercised: {checked}");
505- eprintln!("{checked} quantisers bit-exact against ffmpeg");
506545 }
507546
508547 /// Geometry and slice structure: cropping, odd sizes, multiple slices, the
@@ -517,63 +556,48 @@ fn geometry_and_slice_structure_match_ffmpeg() {
517556 let dir = scratch("geometry");
518557 let cases: &[(&str, &str, &[&str])] = &[
519558 // 1080 lines are coded as 68 macroblock rows and cropped back to 1080.
520- ("hd", "1920x1080", &["-profile:v", "baseline", "-qp", "26"]),
559+ ("hd", "1920x1080", &["-qp", "26"]),
521560 // A width that is not a multiple of 16 crops horizontally as well.
522- ("odd", "1916x1080", &["-profile:v", "baseline", "-qp", "26"]),
523- // Four slices: neighbour availability stops at every slice boundary.
561+ ("odd", "1916x1080", &["-qp", "26"]),
562+ // Four slices: neighbour availability stops at every slice boundary,
563+ // and under CABAC every slice re-initialises its own contexts.
524564 (
525565 "slices",
526566 "352x288",
527- &[
528- "-profile:v",
529- "baseline",
530- "-qp",
531- "24",
532- "-x264-params",
533- "slices=4",
534- ],
567+ &["-qp", "24", "-x264-params", "slices=4"],
535568 ),
536569 // No loop filter at all.
537570 (
538571 "nodeblock",
539572 "352x288",
540- &[
541- "-profile:v",
542- "baseline",
543- "-qp",
544- "30",
545- "-x264-params",
546- "no-deblock=1",
547- ],
573+ &["-qp", "30", "-x264-params", "no-deblock=1"],
548574 ),
549575 // A non-zero chroma QP offset moves the chroma deblock thresholds.
550576 (
551577 "chromaqp",
552578 "352x288",
553- &[
554- "-profile:v",
555- "baseline",
556- "-qp",
557- "30",
558- "-x264-params",
559- "chroma_qp_offset=6",
560- ],
579+ &["-qp", "30", "-x264-params", "chroma_qp_offset=6"],
561580 ),
562581 // One macroblock wide: every neighbour is unavailable.
563- ("tiny", "16x16", &["-profile:v", "baseline", "-qp", "20"]),
582+ ("tiny", "16x16", &["-qp", "20"]),
564583 ];
565584 let mut table = String::new();
566585 let mut failures = Vec::new();
567- for (tag, size, extra) in cases {
568- match round_trip(&dir, tag, size, extra) {
569- Ok(0) => table.push_str(&format!("{tag:<10} {size:<10} bit-exact\n")),
570- Ok(n) => {
571- table.push_str(&format!("{tag:<10} {size:<10} MISMATCH {n} bytes\n"));
572- failures.push(format!("{tag}: {n} bytes differ"));
573- }
574- Err(e) => {
575- table.push_str(&format!("{tag:<10} {size:<10} {e}\n"));
576- failures.push(e);
586+ for (mode, profile) in ENTROPY_MODES {
587+ for (tag, size, case) in cases {
588+ let mut extra = profile.to_vec();
589+ extra.extend_from_slice(case);
590+ let tag = format!("{mode}-{tag}");
591+ match round_trip(&dir, &tag, size, &extra) {
592+ Ok(0) => table.push_str(&format!("{tag:<16} {size:<10} bit-exact\n")),
593+ Ok(n) => {
594+ table.push_str(&format!("{tag:<16} {size:<10} MISMATCH {n} bytes\n"));
595+ failures.push(format!("{tag}: {n} bytes differ"));
596+ }
597+ Err(e) => {
598+ table.push_str(&format!("{tag:<16} {size:<10} {e}\n"));
599+ failures.push(e);
600+ }
577601 }
578602 }
579603 }
@@ -652,6 +676,22 @@ fn refusals_name_a_feature_the_stream_really_uses() {
652676 ],
653677 "8x8 transform",
654678 ),
679+ // The 8x8 transform is refused under CABAC too, where the flag is a
680+ // context-coded bin rather than a raw one.
681+ (
682+ "transform8x8-cabac",
683+ &[
684+ "-profile:v",
685+ "high",
686+ "-qp",
687+ "26",
688+ "-coder",
689+ "ac",
690+ "-x264-params",
691+ "8x8dct=1",
692+ ],
693+ "8x8 transform",
694+ ),
655695 (
656696 "yuv422",
657697 &[
@@ -711,6 +751,86 @@ fn refusals_name_a_feature_the_stream_really_uses() {
711751 assert!(proved >= 2, "too few refusals proved against real streams");
712752 }
713753
754+/// Inter slices are refused by name under CABAC as well as CAVLC: the
755+/// arithmetic decoder landing does not imply P and B macroblock parsing, and a
756+/// stream whose first picture decodes must not silently produce wrong pixels
757+/// for its second.
758+#[test]
759+fn inter_slices_under_cabac_are_refused_by_name() {
760+ if !have_ffmpeg() {
761+ eprintln!("SKIP: ffmpeg not on PATH");
762+ return;
763+ }
764+ let dir = scratch("inter-cabac");
765+ let stream = dir.join("gop.264");
766+ let ok = run(
767+ "ffmpeg",
768+ &[
769+ "-hide_banner",
770+ "-loglevel",
771+ "error",
772+ "-y",
773+ "-f",
774+ "lavfi",
775+ "-i",
776+ "testsrc=size=176x144:rate=25:duration=1",
777+ "-pix_fmt",
778+ "yuv420p",
779+ "-c:v",
780+ "libx264",
781+ "-frames:v",
782+ "6",
783+ "-profile:v",
784+ "main",
785+ "-coder",
786+ "ac",
787+ "-qp",
788+ "26",
789+ "-f",
790+ "h264",
791+ &stream.to_string_lossy(),
792+ ],
793+ );
794+ assert!(ok, "ffmpeg cannot encode a CABAC GOP");
795+ let bytes = std::fs::read(&stream).unwrap();
796+
797+ // The first (IDR) picture decodes; the first P slice must refuse by name.
798+ let mut dec = Decoder::new();
799+ let first = dec.decode_first_idr(&bytes).expect("CABAC IDR decodes");
800+ assert_eq!((first.width, first.height), (176, 144));
801+
802+ let mut refusal = None;
803+ let mut pictures = 1;
804+ for nal in ec_h264_syntax::AnnexBIter::new(&bytes) {
805+ match dec.push_nal(nal) {
806+ Ok(ec_h264::NalOutcome::PictureBoundary) => {
807+ dec.end_picture().expect("end_picture");
808+ pictures += 1;
809+ if let Err(e) = dec.push_nal(nal) {
810+ refusal = Some(e);
811+ break;
812+ }
813+ }
814+ Ok(_) => {}
815+ Err(e) => {
816+ refusal = Some(e);
817+ break;
818+ }
819+ }
820+ }
821+ let _ = std::fs::remove_dir_all(&dir);
822+ match refusal {
823+ Some(Error::Unsupported { what, why }) => {
824+ assert!(
825+ what.contains("non-I slice") || why.contains("P/B"),
826+ "refused as {what} ({why}), expected the inter-slice refusal"
827+ );
828+ eprintln!("CABAC GOP: {pictures} intra picture(s) decoded, then refused: {what}");
829+ }
830+ other => panic!("expected an inter-slice refusal, got {other:?}"),
831+ }
832+}
833+
714834 /// The `avcC` entry path: parameter sets out of band and NAL units length
715835 /// prefixed — how an MP4 or Matroska demuxer hands H.264 over.
716836 #[test]