diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 62f271ea..01f5abb9 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -134,6 +134,19 @@ pub struct Decoder { out: VecDeque, /// Presentation timestamp to attach to the next picture started. pending_pts: Option, + /// `PicOrderCnt` of the random-access point most recently established by + /// [`Decoder::reset_pictures`] — the first picture decoded after it, + /// i.e. the I picture a seek landed on. `None` before that picture + /// completes. Absent a recovery_point SEI (not parsed here), D.2.8's + /// recovery point defaults to this picture itself: anything with a + /// smaller POC that had to guess a reference (see `cur_ref_padded`) + /// predicts from something never decoded since the seek and must not + /// reach the caller. + recovery_poc: Option, + /// Set while decoding the open picture if `build_ref_lists` had to pad a + /// reference list, i.e. this picture asked for a reference the DPB does + /// not have. Reset per picture in `start_picture`. + cur_ref_padded: bool, } /// What [`Decoder::push_nal`] did with a NAL unit. @@ -199,6 +212,8 @@ impl Decoder { output_order: OutputOrder::default(), out: VecDeque::new(), pending_pts: None, + recovery_poc: None, + cur_ref_padded: false, } } @@ -301,13 +316,18 @@ impl Decoder { self.cur.extend_borders(); self.cur.complete = true; self.last_decoded = self.cur.id; + // The first picture completed after a reset is the random-access + // point the seek landed on; its own POC becomes the recovery + // threshold (see `recovery_poc`'s doc comment). + let recovery_poc = *self.recovery_poc.get_or_insert(self.cur.poc); + let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc); 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); - let stored = self.dpb.store(pic, &sps, &self.cur_info, marking); + let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok); self.sps_map[sps_id] = Some(sps); stored?; self.has_picture = false; @@ -357,6 +377,7 @@ impl Decoder { self.out.clear(); self.last_decoded = -1; self.pending_pts = None; + self.recovery_poc = None; } /// Move pictures out of the decoded picture buffer into the output queue. @@ -472,7 +493,7 @@ impl Decoder { [RefList::default(), RefList::default()] } else { self.dpb.number_short_term(sh.frame_num, sps); - self.dpb.build_ref_lists( + let (lists, padded) = self.dpb.build_ref_lists( sh.slice_type, self.cur.poc, sh.frame_num as i32, @@ -480,7 +501,15 @@ impl Decoder { sh.num_ref_idx_l0_active as usize, sh.num_ref_idx_l1_active as usize, (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), - )? + )?; + // A ref list shorter than requested was padded by repeating an + // available entry (8.2.4.2's unspecified tail) rather than the + // reference this slice actually asked for. Right after a seek's + // reset, that means the picture predicts from something never + // decoded since the random-access start; recorded here so + // `end_picture` can hold its output back (see `recovery_poc`). + self.cur_ref_padded |= padded; + lists }; let mut r = if pps.entropy_coding_mode { @@ -632,6 +661,7 @@ impl Decoder { sh: &SliceHeader, header: NalHeader, ) -> Result<()> { + self.cur_ref_padded = false; let info = PicInfo { is_idr: header.is_idr(), is_reference: header.ref_idc != 0, diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs index 7ca2d3dc..a784910c 100644 --- a/crates/ec-h264/src/dpb.rs +++ b/crates/ec-h264/src/dpb.rs @@ -644,7 +644,8 @@ impl Dpb { num_l0: usize, num_l1: usize, mods: (&[RefPicListMod], &[RefPicListMod]), - ) -> Result<[RefList; 2]> { + ) -> Result<([RefList; 2], bool)> { + let mut padded = false; let mut lists = [RefList::default(), RefList::default()]; // Short-term candidates, then long-term, both by index into `frames`. let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; @@ -737,13 +738,16 @@ impl Dpb { // conformant stream fills it by modification; repeating entry 0 // keeps every index in range meanwhile. let first = lists[x].entries[0]; + if lists[x].len < wanted[x] { + padded = true; + } while lists[x].len < wanted[x] { lists[x].push(usize::from(first)); } lists[x].len = wanted[x]; self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); } - Ok(lists) + Ok((lists, padded)) } /// Reference picture list modification (clause 8.2.4.3), following the @@ -826,15 +830,22 @@ impl Dpb { } /// Store a decoded picture and apply the reference marking of 8.2.5. + /// + /// `output_ok` is false for a picture that predicted from a reference + /// never decoded since the last `reset()` (a random-access leading + /// picture whose ref list build had to pad) — it still joins the DPB, as + /// a reference for later pictures and for `PicNum`/`FrameNumWrap` + /// bookkeeping, but the bumping process must never hand it to a caller. pub(crate) fn store( &mut self, mut pic: Picture, sps: &Sps, info: &PicInfo, marking: Option<&DecRefPicMarking>, + output_ok: bool, ) -> Result<()> { let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); - pic.output = true; + pic.output = output_ok; pic.complete = true; // Clause 8.2.4.1 against this picture's frame_num, which is what both // the sliding window (8.2.5.3) and the MMCO picture numbers (8.2.5.4) @@ -1275,7 +1286,7 @@ mod tests { lt.long_term_frame_idx = 1; lt.pic_num = 1; dpb.frames.push(lt); - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[])) .unwrap(); let nums: Vec = (0..lists[0].len()) @@ -1292,7 +1303,7 @@ mod tests { push_ref(&mut dpb, 1, 8, Mark::Short); push_ref(&mut dpb, 2, 4, Mark::Short); push_ref(&mut dpb, 3, 12, Mark::Short); - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) .unwrap(); let poc = |l: &RefList| -> Vec { @@ -1313,7 +1324,7 @@ mod tests { push_ref(&mut dpb, 1, 2, Mark::Short); // Both references precede the current picture, so initialisation gives // list 0 and list 1 the same descending-POC order. - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) .unwrap(); let l0: Vec = (0..2) @@ -1338,7 +1349,7 @@ mod tests { abs_diff_pic_num_minus1: 2, add: false, }]; - let lists = dpb + let (lists, _) = dpb .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[])) .unwrap(); let nums: Vec = (0..3) diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 619ae22d..5d19b39a 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -2245,3 +2245,134 @@ fn high_profile_8x8_inter_sequences_match_ffmpeg() { let _ = std::fs::remove_dir_all(&dir); assert!(failures.is_empty(), "{failures:#?}"); } + +/// An open-GOP boundary's non-IDR I picture (`nal_unit_type` 1, not 5) is +/// followed in decode order by leading B pictures that display *before* it +/// but predict from the previous GOP. A decoder started fresh at that I +/// picture — what a seek does — never decoded those previous-GOP references, +/// so it must not hand back the leading B pictures at all (H.264's analogue +/// of HEVC's RASL/`NoRaslOutputFlag` case): output must resume at the I +/// picture itself, per D.2.8 absent a recovery_point SEI. +#[test] +fn h264_seek_matches_linear_open_gop() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4"); + if !src.is_file() { + eprintln!("SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)"); + return; + } + let dir = scratch("open-gop"); + std::fs::create_dir_all(&dir).unwrap(); + let annexb = dir.join("open-gop.264"); + assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction"); + let data = std::fs::read(&annexb).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + + // Split into access units the way a demuxer would: a new one starts at + // each slice NAL (type 1 or 5). + let units: Vec> = ec_h264_syntax::AnnexBIter::new(&data) + .map(<[u8]>::to_vec) + .collect(); + let mut access_units: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + let mut current_has_slice = false; + for unit in &units { + let is_slice = matches!(unit[0] & 0x1F, 1 | 5); + if is_slice && current_has_slice { + access_units.push(std::mem::take(&mut current)); + current_has_slice = false; + } + current_has_slice |= is_slice; + current.extend_from_slice(&[0, 0, 0, 1]); + current.extend_from_slice(unit); + } + if current_has_slice { + access_units.push(current); + } + + // Linear decode: every picture from the start, display frame 30 kept for + // comparison (the fixture's second I picture, `keyint=30`). + const TARGET: usize = 30; + let mut dec = Decoder::new(); + let mut linear_frame_30 = None; + let mut index = 0usize; + for nal in ec_h264_syntax::AnnexBIter::new(&data) { + if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary { + dec.end_picture().expect("end_picture"); + dec.push_nal(nal).expect("re-push"); + } + while let Some(f) = dec.next_frame() { + if index == TARGET { + linear_frame_30 = Some(frame_bytes(&f)); + } + index += 1; + } + } + dec.flush().expect("flush"); + while let Some(f) = dec.next_frame() { + if index == TARGET { + linear_frame_30 = Some(frame_bytes(&f)); + } + index += 1; + } + let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); + + // Find the access unit whose first VCL NAL is a non-IDR I slice + // (`nal_unit_type` 1, `slice_type % 5 == 2`) — the open-GOP boundary. + let is_open_gop_i = |au: &[u8]| -> bool { + let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else { + return false; + }; + if header & 0x1F != 1 { + return false; + } + let mut r = ec_core::BitReader::new(payload); + if r.read_ue().is_err() { + return false; + } + matches!(r.read_ue(), Ok(code) if code % 5 == 2) + }; + let cra_at = access_units + .iter() + .position(|au| is_open_gop_i(au)) + .expect("an open-GOP I access unit exists"); + + // A seek reuses the parameter sets a decoder already learned; a fresh one + // is primed the way `Decoder::reset_pictures`'s doc comment expects: the + // leading IDR's parameter sets are decoded and its picture discarded. + let mut seek_dec = Decoder::new(); + for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) { + seek_dec.push_nal(nal).expect("prime parameter sets"); + } + seek_dec.end_picture().expect("end priming IDR"); + seek_dec.reset_pictures(); + + let mut seeked_frame = None; + 'outer: for au in &access_units[cra_at..] { + for nal in ec_h264_syntax::AnnexBIter::new(au) { + if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary { + seek_dec.end_picture().expect("end_picture"); + seek_dec.push_nal(nal).expect("re-push"); + } + } + if let Some(f) = seek_dec.next_frame() { + seeked_frame = Some(frame_bytes(&f)); + break 'outer; + } + } + if seeked_frame.is_none() { + seek_dec.flush().expect("flush"); + seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f)); + } + let seeked_frame = seeked_frame.expect("a frame came out after the seek"); + + assert_eq!( + seeked_frame, linear_frame_30, + "seeking to the open-GOP I before frame 30 handed back a different \ + picture than a linear decode of frame 30 — leading pictures with \ + missing references were not dropped" + ); +} diff --git a/crates/ec-hw/src/dec/dpb264.rs b/crates/ec-hw/src/dec/dpb264.rs index 50a53308..7fc2f73a 100644 --- a/crates/ec-hw/src/dec/dpb264.rs +++ b/crates/ec-hw/src/dec/dpb264.rs @@ -420,7 +420,8 @@ impl Dpb { num_l0: usize, num_l1: usize, mods: (&[RefPicListMod], &[RefPicListMod]), - ) -> Result<[RefList; 2]> { + ) -> Result<([RefList; 2], bool)> { + let mut padded = false; let mut lists = [RefList::default(), RefList::default()]; let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; let mut n_short = 0usize; @@ -505,13 +506,16 @@ impl Dpb { ))); } let first = lists[x].entries[0]; + if lists[x].len < wanted[x] { + padded = true; + } while lists[x].len < wanted[x] { lists[x].push(usize::from(first)); } lists[x].len = wanted[x]; self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); } - Ok(lists) + Ok((lists, padded)) } /// Reference picture list modification (8.2.4.3), by the insert-and-compact @@ -589,15 +593,21 @@ impl Dpb { } /// Store a decoded picture and apply the reference marking of 8.2.5. + /// + /// `output_ok` is false for a picture that predicted from a reference + /// never decoded since the last `reset()` (a random-access leading + /// picture whose ref list build had to pad) — it still joins the DPB as + /// a reference and for bookkeeping, but must never be handed to a caller. pub(crate) fn store( &mut self, mut pic: Picture, sps: &Sps, info: &PicInfo, marking: Option<&DecRefPicMarking>, + output_ok: bool, ) -> Result<()> { let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); - pic.output = true; + pic.output = output_ok; self.number_short_term(info.frame_num, sps); pic.frame_num_wrap = pic.frame_num as i32; pic.pic_num = pic.frame_num as i32; diff --git a/crates/ec-hw/src/dec/h264.rs b/crates/ec-hw/src/dec/h264.rs index 31843549..fdabb8ce 100644 --- a/crates/ec-hw/src/dec/h264.rs +++ b/crates/ec-hw/src/dec/h264.rs @@ -38,6 +38,8 @@ struct Current { /// Parameter and data buffers submitted so far. buffers: Vec, slices: usize, + /// Set if any slice's ref list build had to pad (see `H264Decoder::recovery_poc`). + ref_padded: bool, } /// A stateless H.264 decoder. @@ -52,6 +54,14 @@ pub struct H264Decoder { /// Reusable unescape buffer; NAL payloads are rewritten into it in turn. rbsp: Vec, gap_frames: u64, + /// `PicOrderCnt` of the random-access point most recently established by + /// `reset()` — the first picture decoded after it. `None` before that + /// picture completes. Absent a recovery_point SEI (not parsed here), + /// D.2.8's recovery point defaults to this picture itself: anything with + /// a smaller POC that had to guess a reference (`Current::ref_padded`) + /// predicts from something never decoded since the seek and must not + /// reach the caller. + recovery_poc: Option, } impl H264Decoder { @@ -68,6 +78,7 @@ impl H264Decoder { current: None, rbsp: Vec::new(), gap_frames: 0, + recovery_poc: None, } } @@ -132,6 +143,7 @@ impl H264Decoder { self.dpb.clear(); self.ready.clear(); self.gap_frames = 0; + self.recovery_poc = None; } /// What the stream turned out to be, once its first SPS was seen. @@ -268,6 +280,7 @@ impl H264Decoder { marking: sh.dec_ref_pic_marking.clone(), buffers: Vec::new(), slices: 0, + ref_padded: false, }); Ok(()) } @@ -317,7 +330,7 @@ impl H264Decoder { [RefList::default(), RefList::default()] } else { self.dpb.number_short_term(sh.frame_num, sps); - self.dpb.build_ref_lists( + let (lists, padded) = self.dpb.build_ref_lists( sh.slice_type, current.poc.value, sh.frame_num as i32, @@ -325,7 +338,9 @@ impl H264Decoder { sh.num_ref_idx_l0_active as usize, sh.num_ref_idx_l1_active as usize, (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), - )? + )?; + current.ref_padded |= padded; + lists }; let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb); @@ -359,6 +374,10 @@ impl H264Decoder { session.submit(¤t.surface, current.buffers)?; + // See `recovery_poc`'s doc comment. + let recovery_poc = *self.recovery_poc.get_or_insert(current.poc.value); + let output_ok = !(current.ref_padded && current.poc.value < recovery_poc); + let picture = Picture { id: current.id, surface: Arc::clone(¤t.surface), @@ -376,7 +395,7 @@ impl H264Decoder { output: true, }; self.dpb - .store(picture, &sps, ¤t.info, current.marking.as_ref())?; + .store(picture, &sps, ¤t.info, current.marking.as_ref(), output_ok)?; self.bump(false); Ok(()) } diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index 6f0f5ea9..bbab2c96 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -1104,6 +1104,100 @@ fn hevc_seek_matches_linear_mkv() { ); } +/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice +/// (`nal_unit_type` 1) whose predecessors in decode order can still hold +/// references from before it, so leading pictures between it and the next +/// IDR may predict from a picture never decoded since a fresh start there — +/// exactly what a seek does. A decoder started at that I must drop those +/// leading pictures per D.2.8's recovery point default, or its output shifts +/// by however many leading pictures the GOP has. +#[test] +fn h264_seek_matches_linear_open_gop() { + let Some(display) = display() else { return }; + let path = bitstreams().join("h264-open-gop.mp4"); + let Some(data) = elementary(&path, Codec::H264, 60) else { + eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)"); + return; + }; + let units = split_access_units(&data, Codec::H264); + + // Linear decode: every picture from the start, frame 30 kept for + // comparison (the fixture's second I picture, `keyint=30`). + const TARGET: usize = 30; + let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + let mut linear_frame_30 = None; + let mut index = 0usize; + decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { + if index == TARGET { + linear_frame_30 = Some(frame.to_i420().expect("readback")); + } + index += 1; + }) + .expect("linear decode"); + let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); + + // Find the access unit whose first VCL NAL is the open-GOP I picture at + // this GOP boundary, and feed the decoder from there on, exactly as a + // seek would: nothing from before it goes in. + let open_gop_at = units + .iter() + .position(|au| is_open_gop_i(au)) + .expect("an open-GOP I access unit exists"); + + // A seek reuses the parameter sets a decoder already learned; a fresh one + // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a + // caller to: decode the leading IDR (its picture is thrown away) and + // reset picture state before feeding the seek target. + let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); + seek_decoder.decode(units[0], 0).expect("prime parameter sets"); + seek_decoder.reset(); + let mut seeked_frame = None; + for (i, unit) in units[open_gop_at..].iter().enumerate() { + seek_decoder.decode(unit, i as i64).expect("seek decode"); + if let Some(frame) = seek_decoder.next_frame() { + seeked_frame = Some(frame.to_i420().expect("readback")); + break; + } + } + if seeked_frame.is_none() { + seek_decoder.flush().expect("flush"); + seeked_frame = seek_decoder + .next_frame() + .map(|f| f.to_i420().expect("readback")); + } + let seeked_frame = seeked_frame.expect("a frame came out after the seek"); + + assert_eq!( + seeked_frame, linear_frame_30, + "seeking to the open-GOP I before frame 30 handed back a different \ + picture than a linear decode of frame 30 — leading pictures with \ + missing references were not dropped" + ); +} + +/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice +/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the +/// access unit's first start code rather than assuming a fixed prefix length. +fn is_open_gop_i(au: &[u8]) -> bool { + let mut i = 0usize; + while i + 3 < au.len() { + if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { + i += 1; + continue; + } + let header = au[i + 3]; + if header & 0x1f != 1 { + return false; + } + let mut r = ec_core::BitReader::new(&au[i + 4..]); + if r.read_ue().is_err() { + return false; + } + return matches!(r.read_ue(), Ok(code) if code % 5 == 2); + } + false +} + /// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). /// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past /// non-VCL NALs to the first one that carries a slice. diff --git a/scripts/gen-fixtures.sh b/scripts/gen-fixtures.sh index 64ce90d9..cbcb5f8d 100755 --- a/scripts/gen-fixtures.sh +++ b/scripts/gen-fixtures.sh @@ -198,6 +198,15 @@ for spec in "${VIDEO_CODECS[@]}"; do esac done +# Open-GOP H.264: a non-IDR I picture (nal_unit_type 1, not 5) at a GOP +# boundary, with B-pyramid pictures around it referencing across the +# boundary. A decoder started fresh at that I (what a seek does) must not +# hand back a picture whose references it never decoded — the H.264 sibling +# of the HEVC RASL/NoRaslOutputFlag case. +gen "$FIXTURES/video/h264-open-gop.mp4" \ + -f lavfi -i "testsrc2=size=320x240:rate=30:duration=4" -pix_fmt yuv420p \ + -c:v libx264 -x264-params "keyint=30:min-keyint=30:open-gop=1:bframes=3:b-pyramid=normal:scenecut=0" + # -------------------------------------------------------------- summary ----- printf '\n%s\n' "== fixtures: $FIXTURES ==" printf '%-42s %10s %s\n' FILE SIZE PROBE