From 6e48da7f58e2235aaf0c8b58563f3db752b21797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 13:36:58 +0300 Subject: [PATCH] test(h264): B pictures, display order, frame_num gaps, zero-alloc on B MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - b_pictures_match_ffmpeg_every_frame: spatial and temporal direct, B-pyramid and weighted prediction, under both entropy coders, every frame bit-exact. The first version of this test measured nothing: x264's adaptive decision produced no B slices at all on the synthetic source, so the test now counts slice types out of the stream and fails if the encoder did not actually emit any. - output_is_display_order_and_the_reorder_is_real: display order matches ffmpeg frame for frame, and the same stream decoded in decode order is a genuine permutation of it — 15 of 20 frames move. - a_frame_num_gap_keeps_decoding: dropping a whole picture leaves the remaining 11 decodable, which is what a seek into a GOP looks like. - The zero-allocation proof now covers a B-slice, multi-reference stream and counts a whole second pass over the stream rather than one picture, so picture-pool recycling is part of the claim. Emitting a picture no longer looks its parameter set up: a stored picture carries its own crop, output size and colour description, which also removes the per-slice parameter-set clone that made the decode loop allocate. --- crates/ec-h264/src/decoder.rs | 55 ++-- crates/ec-h264/src/dpb.rs | 19 ++ crates/ec-h264/tests/conformance.rs | 406 ++++++++++++++++++++-------- 3 files changed, 348 insertions(+), 132 deletions(-) diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 3667ee1d..21197e87 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -304,13 +304,15 @@ impl Decoder { self.cur.extend_borders(); self.cur.complete = true; self.last_decoded = self.cur.id; - let sps = self.sps_map[self.cur.sps_id as usize] - .as_ref() - .ok_or_else(|| Error::corrupt("active SPS vanished"))? - .clone(); + let sps_id = self.cur.sps_id as usize; + let sps = self.sps_map[sps_id] + .take() + .ok_or_else(|| Error::corrupt("active SPS vanished"))?; let pic = core::mem::take(&mut self.cur); let marking = self.has_marking.then_some(&self.cur_marking); - self.dpb.store(pic, &sps, &self.cur_info, marking)?; + let stored = self.dpb.store(pic, &sps, &self.cur_info, marking); + self.sps_map[sps_id] = Some(sps); + stored?; self.has_picture = false; self.pump_output(false) } @@ -381,11 +383,8 @@ impl Decoder { /// Copy a stored picture out as a cropped I420 frame. fn picture_to_frame(&self, pic: &Picture) -> Result { - let sps = self.sps_map[pic.sps_id as usize] - .as_ref() - .ok_or_else(|| Error::corrupt("active SPS vanished"))?; - let (w, h) = (sps.width as usize, sps.height as usize); - let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize); + let (w, h) = (pic.out_size.0 as usize, pic.out_size.1 as usize); + let (cx, cy) = (pic.crop.0 as usize, pic.crop.1 as usize); let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane { let mut out = vec![0u8; w * h]; for row in 0..h { @@ -400,14 +399,7 @@ impl Decoder { copy(&pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), ]; let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; - if let Some(vui) = &sps.vui { - frame.color.full_range = vui.video_full_range; - if let Some((p, t, m)) = vui.colour_description { - frame.color.primaries = p; - frame.color.transfer = t; - frame.color.matrix = m; - } - } + frame.color = pic.color; frame.pts = pic.pts; Ok(frame) } @@ -433,11 +425,30 @@ impl Decoder { check_supported(sps, pps, slice_type_code)?; let sh = SliceHeader::parse(rbsp, header, sps, pps)?; - let sps = sps.clone(); - let pps = pps.clone(); - + // Borrow the parameter sets out of their slots for the duration of the + // slice: cloning them per slice would allocate, and a decode loop that + // allocates per slice is the thing the whole layout is built to avoid. + let sps_slot = pps.sps_id as usize; + let sps = self.sps_map[sps_slot].take().expect("checked above"); + let pps = self.pps_map[pps_id as usize].take().expect("checked above"); + let outcome = self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb); + self.sps_map[sps_slot] = Some(sps); + self.pps_map[pps_id as usize] = Some(pps); + outcome + } + + #[allow(clippy::too_many_arguments)] + fn decode_slice_data( + &mut self, + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + header: NalHeader, + rbsp: &[u8], + first_mb: u32, + ) -> Result { if !self.has_picture || self.cur.complete { - self.start_picture(&sps, &pps, &sh, header)?; + self.start_picture(sps, pps, sh, header)?; } if self.cur.sps_id != sps.id { return Err(Error::corrupt("SPS changed mid-picture")); diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs index 3954ad51..6bf30168 100644 --- a/crates/ec-h264/src/dpb.rs +++ b/crates/ec-h264/src/dpb.rs @@ -184,6 +184,14 @@ pub(crate) struct Picture { /// travels with the picture rather than with the packet, because display /// order reorders the two apart. pub pts: Option, + /// Cropped output size and the crop origin, in luma samples. A stored + /// picture describes its own output geometry so that emitting it needs no + /// lookup back into the parameter sets — which a later sequence may have + /// replaced by then. + pub out_size: (u32, u32), + pub crop: (u32, u32), + /// Colour description carried from the VUI. + pub color: ec_core::frame::ColorInfo, } impl Picture { @@ -229,6 +237,17 @@ impl Picture { self.long_term_frame_idx = 0; self.frame_num_wrap = 0; self.pic_num = 0; + self.out_size = (sps.width, sps.height); + self.crop = (sps.crop.0, sps.crop.2); + self.color = ec_core::frame::ColorInfo::default(); + if let Some(vui) = &sps.vui { + self.color.full_range = vui.video_full_range; + if let Some((p, t, m)) = vui.colour_description { + self.color.primaries = p; + self.color.transfer = t; + self.color.matrix = m; + } + } } /// Replicate every plane's borders once the picture is fully reconstructed. diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 1d211d64..cc5c4d61 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -376,11 +376,13 @@ fn jvt_cavlc_first_idr_bit_exact() { ); } -/// Steady-state decode loop performs zero heap allocations: after one warm-up -/// picture, re-decoding the same slices into the reused picture context -/// (including deblocking) must not allocate. Frame emission (`frame()`) -/// allocates the output planes and is measured separately as nonzero to prove -/// the counter works. +/// Steady-state slice decoding performs zero heap allocations. +/// +/// After a warm-up pass the picture pool, every per-picture array and the +/// parameter-set store are all sized, so decoding the same stream again must +/// not allocate at all: not per macroblock, not per slice, not per picture. +/// Emitting a frame is measured separately and *does* allocate — it hands the +/// caller owned planes — which also proves the counter is alive. #[test] fn steady_state_decode_loop_zero_alloc() { let base = vectors_dir(); @@ -388,38 +390,59 @@ fn steady_state_decode_loop_zero_alloc() { eprintln!("SKIP: fixtures missing"); return; } - // One stream per entropy coder: the CABAC reader carries its 402 context - // variables inline for exactly this reason. - let mut dec = Decoder::new(); - for name in ["BA1_Sony_D", "CABA1_SVA_B"] { - let stream = find_stream(&base.join(name)).expect("fixture"); + // One stream per entropy coder, and one with B slices and multiple + // reference frames so the decoded picture buffer really recycles pictures. + for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] { + let Some(stream) = find_stream(&base.join(name)) else { + continue; + }; let bytes = std::fs::read(stream).unwrap(); - // Warm-up: full first picture, growing every reusable buffer. - let _ = dec.decode_first_idr(&bytes).expect("warm-up decode"); + let mut dec = Decoder::new(); + let mut drive = |dec: &mut Decoder, count: bool| -> usize { + let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); + let mut frames = 0usize; + for nal in &nals { + if count { + COUNTING_HERE.with(|c| c.set(true)); + } + let outcome = dec.push_nal(nal); + if count { + COUNTING_HERE.with(|c| c.set(false)); + } + match outcome { + Ok(ec_h264::NalOutcome::PictureBoundary) => { + dec.end_picture().expect("end_picture"); + dec.push_nal(nal).expect("re-push"); + } + Ok(_) => {} + Err(e) => panic!("{name}: {e}"), + } + while dec.next_frame().is_some() { + frames += 1; + } + } + dec.flush().expect("flush"); + while dec.next_frame().is_some() { + frames += 1; + } + frames + }; + // Warm-up: every reusable buffer reaches its final size. + let warm = drive(&mut dec, false); + assert!(warm > 1, "{name}: only {warm} frames decoded"); + dec.reset_pictures(); - // Steady state: same IDR slices again, counted. - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - let mut decoded = false; - for nal in &nals { - match dec.push_nal(nal) { - Ok(ec_h264::NalOutcome::PictureBoundary) => break, - Ok(ec_h264::NalOutcome::SliceDecoded) => decoded = true, - Ok(_) => {} - Err(e) => panic!("steady-state push failed: {e}"), - } - } - dec.end_picture().expect("end_picture"); - COUNTING_HERE.with(|c| c.set(false)); - assert!(decoded, "no slice decoded in steady-state pass of {name}"); + let again = drive(&mut dec, true); let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(n, 0, "{name}: steady-state decode loop allocated {n} times"); + assert_eq!(again, warm, "{name}: frame count changed on the second pass"); + assert_eq!(n, 0, "{name}: steady-state slice decode allocated {n} times"); } + + // Sanity: the counter is alive — emitting a frame does allocate. let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap(); + let mut dec = Decoder::new(); let _ = dec.decode_first_idr(&bytes).expect("decode"); - - // Sanity: the counter is alive — frame emission does allocate. ALLOCS.store(0, Ordering::SeqCst); COUNTING_HERE.with(|c| c.set(true)); let frame = dec.frame().expect("frame"); @@ -882,86 +905,6 @@ fn refusals_name_a_feature_the_stream_really_uses() { assert!(proved >= 2, "too few refusals proved against real streams"); } -/// Inter slices are refused by name under CABAC as well as CAVLC: the -/// arithmetic decoder landing does not imply P and B macroblock parsing, and a -/// stream whose first picture decodes must not silently produce wrong pixels -/// for its second. -#[test] -fn inter_slices_under_cabac_are_refused_by_name() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = scratch("inter-cabac"); - let stream = dir.join("gop.264"); - let ok = run( - "ffmpeg", - &[ - "-hide_banner", - "-loglevel", - "error", - "-y", - "-f", - "lavfi", - "-i", - "testsrc=size=176x144:rate=25:duration=1", - "-pix_fmt", - "yuv420p", - "-c:v", - "libx264", - "-frames:v", - "6", - "-profile:v", - "main", - "-coder", - "ac", - "-qp", - "26", - "-f", - "h264", - &stream.to_string_lossy(), - ], - ); - assert!(ok, "ffmpeg cannot encode a CABAC GOP"); - let bytes = std::fs::read(&stream).unwrap(); - - // The first (IDR) picture decodes; the first P slice must refuse by name. - let mut dec = Decoder::new(); - let first = dec.decode_first_idr(&bytes).expect("CABAC IDR decodes"); - assert_eq!((first.width, first.height), (176, 144)); - - let mut refusal = None; - let mut pictures = 1; - for nal in ec_h264_syntax::AnnexBIter::new(&bytes) { - match dec.push_nal(nal) { - Ok(ec_h264::NalOutcome::PictureBoundary) => { - dec.end_picture().expect("end_picture"); - pictures += 1; - if let Err(e) = dec.push_nal(nal) { - refusal = Some(e); - break; - } - } - Ok(_) => {} - Err(e) => { - refusal = Some(e); - break; - } - } - } - let _ = std::fs::remove_dir_all(&dir); - match refusal { - Some(Error::Unsupported { what, why }) => { - assert!( - what.contains("non-I slice") || why.contains("P/B"), - "refused as {what} ({why}), expected the inter-slice refusal" - ); - eprintln!("CABAC GOP: {pictures} intra picture(s) decoded, then refused: {what}"); - } - other => panic!("expected an inter-slice refusal, got {other:?}"), - } -} - /// The `avcC` entry path: parameter sets out of band and NAL units length /// prefixed — how an MP4 or Matroska demuxer hands H.264 over. #[test] @@ -1236,3 +1179,246 @@ fn jvt_full_sequence_bit_exact() { ); assert!(failed.is_empty(), "{failed:#?}"); } + +/// Decode a whole stream in decode order rather than display order. +fn decode_all_in_decode_order(bytes: &[u8]) -> Result>, Error> { + let mut dec = Decoder::new(); + dec.set_output_order(ec_h264::OutputOrder::Decode); + let mut frames = Vec::new(); + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { + dec.end_picture()?; + dec.push_nal(nal)?; + } + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + } + dec.flush()?; + while let Some(f) = dec.next_frame() { + frames.push(frame_bytes(&f)); + } + Ok(frames) +} + +/// Count I, P and B slices in an Annex B stream, straight from the slice +/// headers. A test that claims to exercise B pictures has to prove the encoder +/// actually produced some — x264's adaptive decision drops them on flat +/// synthetic sources, and the test would then pass while measuring nothing. +fn slice_type_counts(bytes: &[u8]) -> [usize; 3] { + let mut counts = [0usize; 3]; + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { + let Some((&header, payload)) = nal.split_first() else { + continue; + }; + if !matches!(header & 0x1F, 1 | 5) { + continue; + } + let mut r = ec_core::BitReader::new(payload); + if r.read_ue().is_err() { + continue; + } + let Ok(code) = r.read_ue() else { continue }; + match code % 5 { + 0 => counts[1] += 1, + 1 => counts[2] += 1, + 2 => counts[0] += 1, + _ => {} + } + } + counts +} + +/// A GOP with B pictures, every frame bit-exact against ffmpeg, under both +/// entropy coders and both direct modes. +/// +/// B pictures are where the decoded picture buffer earns its keep: two +/// reference lists, direct prediction from a co-located picture, implicit +/// weighting, and pictures that leave the buffer in a different order than +/// they arrived. +#[test] +fn b_pictures_match_ffmpeg_every_frame() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("b-gop"); + let cases: &[(&str, &[&str])] = &[ + ("spatial", &["-x264-params", "bframes=3:b-adapt=0:direct=spatial:weightp=0"]), + ("temporal", &["-x264-params", "bframes=3:b-adapt=0:direct=temporal:weightp=0"]), + // B pictures used as references, which makes the buffer hold pictures + // that are neither the newest nor the oldest. + ( + "pyramid", + &["-x264-params", "bframes=3:b-adapt=0:b-pyramid=normal:direct=spatial"], + ), + // Weighted prediction on: explicit for P, implicit for B. + ( + "weighted", + &["-x264-params", "bframes=3:b-adapt=0:weightp=2:weightb=1:direct=spatial"], + ), + ]; + let mut failures = Vec::new(); + let mut table = String::new(); + for (mode, profile) in ENTROPY_MODES { + if mode == "cavlc" { + continue; // baseline forbids B pictures; main covers CAVLC below + } + for (tag, case) in cases { + for coder in ["ac", "0"] { + let mut extra = vec!["-profile:v", "main", "-coder", coder, "-qp", "26"]; + extra.extend_from_slice(case); + let name = format!("{tag}-{}", if coder == "ac" { "cabac" } else { "cavlc" }); + match x264_encode_gop(&dir, &name, "176x144", 20, &extra) { + Some(stream) => { + let counts = slice_type_counts(&std::fs::read(&stream).unwrap()); + if counts[2] == 0 { + failures.push(format!("{name}: encoder produced no B slices")); + continue; + } + match compare_sequence(&stream) { + Ok(n) => table.push_str(&format!( + "{name:<18} {n:>3} frames bit-exact ({} B slices)\n", + counts[2] + )), + Err(e) => failures.push(format!("{name}: {e}")), + } + } + None => failures.push(format!("{name}: ffmpeg cannot encode")), + } + } + } + let _ = profile; + } + let _ = std::fs::remove_dir_all(&dir); + eprintln!("{table}"); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Frames come out in display order, and that is a real reordering. +/// +/// Matching ffmpeg frame for frame already implies display order, but only if +/// the stream actually reorders — so this also decodes the same stream in +/// decode order and requires the two to differ. Without that second half the +/// test would pass on a decoder that never reorders anything. +#[test] +fn output_is_display_order_and_the_reorder_is_real() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("order"); + let extra = [ + "-profile:v", + "main", + "-coder", + "ac", + "-qp", + "26", + "-x264-params", + "bframes=3:b-adapt=0:b-pyramid=normal", + ]; + let stream = x264_encode_gop(&dir, "reorder", "176x144", 20, &extra).expect("encode"); + let bytes = std::fs::read(&stream).unwrap(); + let counts = slice_type_counts(&bytes); + assert!(counts[2] > 0, "the encoder produced no B slices to reorder"); + let display = decode_all(&bytes).expect("display order decode"); + let decode = decode_all_in_decode_order(&bytes).expect("decode order decode"); + let ffmpeg = ffmpeg_all_frames(&stream, display[0].len()).expect("ffmpeg"); + let _ = std::fs::remove_dir_all(&dir); + + assert_eq!(display.len(), ffmpeg.len()); + assert_eq!(decode.len(), display.len()); + for (i, (a, b)) in display.iter().zip(&ffmpeg).enumerate() { + assert!( + first_diff(a, b).is_none(), + "display-order frame {i} differs from ffmpeg" + ); + } + // Every decode-order frame is somewhere in the display-order set: the two + // are permutations of one another, not different pictures. + for (i, f) in decode.iter().enumerate() { + assert!( + display.iter().any(|d| d == f), + "decode-order frame {i} is not in the display-order output" + ); + } + let moved = decode + .iter() + .zip(&display) + .filter(|(a, b)| a != b) + .count(); + assert!( + moved > 0, + "decode order and display order are identical: the stream does not \ + reorder, so this test proves nothing" + ); + eprintln!("{} of {} frames move under reordering", moved, display.len()); +} + +/// A gap in frame_num decodes instead of stalling (clause 8.2.5.2). +/// +/// This is what a seek into the middle of a GOP looks like, and what a lossy +/// transport delivers: the pictures a later frame_num implies never arrived. +/// The spec infers them; a decoder that treats the gap as corruption drops +/// every following picture, which is the failure an editor sees as a frozen +/// preview after a seek. +#[test] +fn a_frame_num_gap_keeps_decoding() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("gap"); + let extra = [ + "-profile:v", + "baseline", + "-qp", + "26", + "-x264-params", + "bframes=0:ref=1:keyint=100", + ]; + let stream = x264_encode_gop(&dir, "gap", "176x144", 12, &extra).expect("encode"); + let bytes = std::fs::read(&stream).unwrap(); + let units: Vec> = ec_h264_syntax::AnnexBIter::new(&bytes) + .map(<[u8]>::to_vec) + .collect(); + let _ = std::fs::remove_dir_all(&dir); + + // Drop the fourth picture entirely, leaving frame_num 3 missing. + let mut vcl_seen = 0; + let mut dec = Decoder::new(); + let mut frames = 0usize; + let mut errors = Vec::new(); + for unit in &units { + if matches!(unit[0] & 0x1F, 1 | 5) { + vcl_seen += 1; + if vcl_seen == 4 { + continue; // the lost picture + } + } + match dec.push_nal(unit) { + Ok(NalOutcome::PictureBoundary) => { + dec.end_picture().expect("end_picture"); + dec.push_nal(unit).expect("re-push"); + } + Ok(_) => {} + Err(e) => errors.push(format!("{e}")), + } + while dec.next_frame().is_some() { + frames += 1; + } + } + dec.flush().expect("flush"); + while dec.next_frame().is_some() { + frames += 1; + } + assert!(errors.is_empty(), "decoding stopped at the gap: {errors:?}"); + // 12 pictures coded, one dropped; the gap is filled by an inferred frame, + // so every remaining picture still decodes and is output. + assert!( + frames >= 11, + "only {frames} frames survived a single dropped picture" + ); + eprintln!("frame_num gap: {frames} frames decoded after dropping one picture"); +}