forge
Explore
Log in

Don't you dare go Hollow

Drop leading pictures after a seek's open-GOP recovery point

Browse files at this commit

03dc6e9978cbbbba112bf5c6ad925845ede8c744Ahmet Kaan GümüşParent: 002ea6d
  • fix
    • drop leading pictures after a seek's open-GOP recovery point
Show full message
fix(h264): drop leading pictures after a seek's open-GOP recovery point

Root cause (crates/ec-h264/src/dpb.rs, crates/ec-h264/src/decoder.rs;
mirrored in crates/ec-hw/src/dec/dpb264.rs, crates/ec-hw/src/dec/h264.rs):
an open-GOP I picture is not an IDR — it is a plain I slice whose
predecessors in decode order can still be referenced by pictures that
follow it. A decoder started fresh at that I (exactly what a seek does)
has none of those earlier references, so `build_ref_lists` pads the
missing entries with whatever it has. The old code decoded and output
those leading pictures anyway, handing back frames predicted from padded
(garbage) references before the stream ever reaches a picture whose
references are all real.

Annex D.2.8 defines a `recovery_point` SEI whose absence (the common
case, and this fixture's case) defaults `recovery_frame_cnt` to 0: the
recovery point is the RAP's own POC, i.e. only pictures with a POC at or
after the leading I's own POC are guaranteed fully referenced. The SEI
itself is deliberately not parsed — the default already gives the
correct threshold for the case that matters (mid-GOP seek), and a real
non-zero `recovery_frame_cnt` is out of scope for this fix.

`build_ref_lists` now returns whether it had to pad a list
((lists, padded)); `Decoder`/`H264Decoder` OR that per-slice into
`cur_ref_padded`/`Current::ref_padded`, latch the first post-reset
picture's POC into `recovery_poc` on `end_picture`/`finish_picture`, and
compute `output_ok = !(ref_padded && poc < recovery_poc)`. `Dpb::store`
takes that flag and marks the picture `Mark::Unused`-eligible for output
gating (`pic.output = output_ok`) — it still joins the DPB as a
reference and for bookkeeping, but a gated picture is never handed to a
caller. `reset_pictures` clears `recovery_poc` so a later seek gets its
own threshold.

New test `h264_seek_matches_linear_open_gop` in both suites drives this
through the real entry surface: fixtures/video/h264-open-gop.mp4
(x264 open-GOP, generated via scripts/gen-fixtures.sh) primes a fresh
decoder with the leading IDR's parameter sets, resets picture state (a
seek's exact contract), feeds it from the open-GOP I access unit before
display frame 30, and asserts the first decoded picture matches a linear
decode of frame 30. Confirmed failing before this fix (forcing
output_ok true reproduces the mismatch) and passing after, on both the
software decoder (crates/ec-h264/tests/conformance.rs) and the VA-API
path (crates/ec-hw/tests/gpu.rs, real hardware).

cargo test -p ec-h264: 70 lib + 23 conformance + 8 encode passed, 0
failed. cargo test -p ec-hw --test gpu -- --test-threads=1: 19 passed
(18 pre-existing + the new one), 0 failed.
crates/ec-h264/src/decoder.rsmodified+33 -3
@@ -134,6 +134,19 @@ pub struct Decoder {
134134 out: VecDeque<VideoFrame>,
135135 /// Presentation timestamp to attach to the next picture started.
136136 pending_pts: Option<Timestamp>,
137+ /// `PicOrderCnt` of the random-access point most recently established by
138+ /// [`Decoder::reset_pictures`] — the first picture decoded after it,
139+ /// i.e. the I picture a seek landed on. `None` before that picture
140+ /// completes. Absent a recovery_point SEI (not parsed here), D.2.8's
141+ /// recovery point defaults to this picture itself: anything with a
142+ /// smaller POC that had to guess a reference (see `cur_ref_padded`)
143+ /// predicts from something never decoded since the seek and must not
144+ /// reach the caller.
145+ recovery_poc: Option<i32>,
146+ /// Set while decoding the open picture if `build_ref_lists` had to pad a
147+ /// reference list, i.e. this picture asked for a reference the DPB does
148+ /// not have. Reset per picture in `start_picture`.
149+ cur_ref_padded: bool,
137150 }
138151
139152 /// What [`Decoder::push_nal`] did with a NAL unit.
@@ -199,6 +212,8 @@ impl Decoder {
199212 output_order: OutputOrder::default(),
200213 out: VecDeque::new(),
201214 pending_pts: None,
215+ recovery_poc: None,
216+ cur_ref_padded: false,
202217 }
203218 }
204219
@@ -301,13 +316,18 @@ impl Decoder {
301316 self.cur.extend_borders();
302317 self.cur.complete = true;
303318 self.last_decoded = self.cur.id;
319+ // The first picture completed after a reset is the random-access
320+ // point the seek landed on; its own POC becomes the recovery
321+ // threshold (see `recovery_poc`'s doc comment).
322+ let recovery_poc = *self.recovery_poc.get_or_insert(self.cur.poc);
323+ let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc);
304324 let sps_id = self.cur.sps_id as usize;
305325 let sps = self.sps_map[sps_id]
306326 .take()
307327 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
308328 let pic = core::mem::take(&mut self.cur);
309329 let marking = self.has_marking.then_some(&self.cur_marking);
310- let stored = self.dpb.store(pic, &sps, &self.cur_info, marking);
330+ let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok);
311331 self.sps_map[sps_id] = Some(sps);
312332 stored?;
313333 self.has_picture = false;
@@ -357,6 +377,7 @@ impl Decoder {
357377 self.out.clear();
358378 self.last_decoded = -1;
359379 self.pending_pts = None;
380+ self.recovery_poc = None;
360381 }
361382
362383 /// Move pictures out of the decoded picture buffer into the output queue.
@@ -472,7 +493,7 @@ impl Decoder {
472493 [RefList::default(), RefList::default()]
473494 } else {
474495 self.dpb.number_short_term(sh.frame_num, sps);
475- self.dpb.build_ref_lists(
496+ let (lists, padded) = self.dpb.build_ref_lists(
476497 sh.slice_type,
477498 self.cur.poc,
478499 sh.frame_num as i32,
@@ -480,7 +501,15 @@ impl Decoder {
480501 sh.num_ref_idx_l0_active as usize,
481502 sh.num_ref_idx_l1_active as usize,
482503 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
483- )?
504+ )?;
505+ // A ref list shorter than requested was padded by repeating an
506+ // available entry (8.2.4.2's unspecified tail) rather than the
507+ // reference this slice actually asked for. Right after a seek's
508+ // reset, that means the picture predicts from something never
509+ // decoded since the random-access start; recorded here so
510+ // `end_picture` can hold its output back (see `recovery_poc`).
511+ self.cur_ref_padded |= padded;
512+ lists
484513 };
485514
486515 let mut r = if pps.entropy_coding_mode {
@@ -632,6 +661,7 @@ impl Decoder {
632661 sh: &SliceHeader,
633662 header: NalHeader,
634663 ) -> Result<()> {
664+ self.cur_ref_padded = false;
635665 let info = PicInfo {
636666 is_idr: header.is_idr(),
637667 is_reference: header.ref_idc != 0,
crates/ec-h264/src/dpb.rsmodified+18 -7
@@ -644,7 +644,8 @@ impl Dpb {
644644 num_l0: usize,
645645 num_l1: usize,
646646 mods: (&[RefPicListMod], &[RefPicListMod]),
647- ) -> Result<[RefList; 2]> {
647+ ) -> Result<([RefList; 2], bool)> {
648+ let mut padded = false;
648649 let mut lists = [RefList::default(), RefList::default()];
649650 // Short-term candidates, then long-term, both by index into `frames`.
650651 let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
@@ -737,13 +738,16 @@ impl Dpb {
737738 // conformant stream fills it by modification; repeating entry 0
738739 // keeps every index in range meanwhile.
739740 let first = lists[x].entries[0];
741+ if lists[x].len < wanted[x] {
742+ padded = true;
743+ }
740744 while lists[x].len < wanted[x] {
741745 lists[x].push(usize::from(first));
742746 }
743747 lists[x].len = wanted[x];
744748 self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
745749 }
746- Ok(lists)
750+ Ok((lists, padded))
747751 }
748752
749753 /// Reference picture list modification (clause 8.2.4.3), following the
@@ -826,15 +830,22 @@ impl Dpb {
826830 }
827831
828832 /// Store a decoded picture and apply the reference marking of 8.2.5.
833+ ///
834+ /// `output_ok` is false for a picture that predicted from a reference
835+ /// never decoded since the last `reset()` (a random-access leading
836+ /// picture whose ref list build had to pad) — it still joins the DPB, as
837+ /// a reference for later pictures and for `PicNum`/`FrameNumWrap`
838+ /// bookkeeping, but the bumping process must never hand it to a caller.
829839 pub(crate) fn store(
830840 &mut self,
831841 mut pic: Picture,
832842 sps: &Sps,
833843 info: &PicInfo,
834844 marking: Option<&DecRefPicMarking>,
845+ output_ok: bool,
835846 ) -> Result<()> {
836847 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
837- pic.output = true;
848+ pic.output = output_ok;
838849 pic.complete = true;
839850 // Clause 8.2.4.1 against this picture's frame_num, which is what both
840851 // the sliding window (8.2.5.3) and the MMCO picture numbers (8.2.5.4)
@@ -1275,7 +1286,7 @@ mod tests {
12751286 lt.long_term_frame_idx = 1;
12761287 lt.pic_num = 1;
12771288 dpb.frames.push(lt);
1278- let lists = dpb
1289+ let (lists, _) = dpb
12791290 .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[]))
12801291 .unwrap();
12811292 let nums: Vec<i32> = (0..lists[0].len())
@@ -1292,7 +1303,7 @@ mod tests {
12921303 push_ref(&mut dpb, 1, 8, Mark::Short);
12931304 push_ref(&mut dpb, 2, 4, Mark::Short);
12941305 push_ref(&mut dpb, 3, 12, Mark::Short);
1295- let lists = dpb
1306+ let (lists, _) = dpb
12961307 .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[]))
12971308 .unwrap();
12981309 let poc = |l: &RefList| -> Vec<i32> {
@@ -1313,7 +1324,7 @@ mod tests {
13131324 push_ref(&mut dpb, 1, 2, Mark::Short);
13141325 // Both references precede the current picture, so initialisation gives
13151326 // list 0 and list 1 the same descending-POC order.
1316- let lists = dpb
1327+ let (lists, _) = dpb
13171328 .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[]))
13181329 .unwrap();
13191330 let l0: Vec<i32> = (0..2)
@@ -1338,7 +1349,7 @@ mod tests {
13381349 abs_diff_pic_num_minus1: 2,
13391350 add: false,
13401351 }];
1341- let lists = dpb
1352+ let (lists, _) = dpb
13421353 .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[]))
13431354 .unwrap();
13441355 let nums: Vec<i32> = (0..3)
crates/ec-h264/tests/conformance.rsmodified+131 -0
@@ -2245,3 +2245,134 @@ fn high_profile_8x8_inter_sequences_match_ffmpeg() {
22452245 let _ = std::fs::remove_dir_all(&dir);
22462246 assert!(failures.is_empty(), "{failures:#?}");
22472247 }
2248+
2249+/// An open-GOP boundary's non-IDR I picture (`nal_unit_type` 1, not 5) is
2250+/// followed in decode order by leading B pictures that display *before* it
2251+/// but predict from the previous GOP. A decoder started fresh at that I
2252+/// picture — what a seek does — never decoded those previous-GOP references,
2253+/// so it must not hand back the leading B pictures at all (H.264's analogue
2254+/// of HEVC's RASL/`NoRaslOutputFlag` case): output must resume at the I
2255+/// picture itself, per D.2.8 absent a recovery_point SEI.
2256+#[test]
2257+fn h264_seek_matches_linear_open_gop() {
2258+ if !have_ffmpeg() {
2259+ eprintln!("SKIP: ffmpeg not on PATH");
2260+ return;
2261+ }
2262+ let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4");
2263+ if !src.is_file() {
2264+ eprintln!("SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)");
2265+ return;
2266+ }
2267+ let dir = scratch("open-gop");
2268+ std::fs::create_dir_all(&dir).unwrap();
2269+ let annexb = dir.join("open-gop.264");
2270+ assert!(extract_annexb(&src, &annexb, 120), "ffmpeg extraction");
2271+ let data = std::fs::read(&annexb).unwrap();
2272+ let _ = std::fs::remove_dir_all(&dir);
2273+
2274+ // Split into access units the way a demuxer would: a new one starts at
2275+ // each slice NAL (type 1 or 5).
2276+ let units: Vec<Vec<u8>> = ec_h264_syntax::AnnexBIter::new(&data)
2277+ .map(<[u8]>::to_vec)
2278+ .collect();
2279+ let mut access_units: Vec<Vec<u8>> = Vec::new();
2280+ let mut current: Vec<u8> = Vec::new();
2281+ let mut current_has_slice = false;
2282+ for unit in &units {
2283+ let is_slice = matches!(unit[0] & 0x1F, 1 | 5);
2284+ if is_slice && current_has_slice {
2285+ access_units.push(std::mem::take(&mut current));
2286+ current_has_slice = false;
2287+ }
2288+ current_has_slice |= is_slice;
2289+ current.extend_from_slice(&[0, 0, 0, 1]);
2290+ current.extend_from_slice(unit);
2291+ }
2292+ if current_has_slice {
2293+ access_units.push(current);
2294+ }
2295+
2296+ // Linear decode: every picture from the start, display frame 30 kept for
2297+ // comparison (the fixture's second I picture, `keyint=30`).
2298+ const TARGET: usize = 30;
2299+ let mut dec = Decoder::new();
2300+ let mut linear_frame_30 = None;
2301+ let mut index = 0usize;
2302+ for nal in ec_h264_syntax::AnnexBIter::new(&data) {
2303+ if dec.push_nal(nal).expect("push_nal") == NalOutcome::PictureBoundary {
2304+ dec.end_picture().expect("end_picture");
2305+ dec.push_nal(nal).expect("re-push");
2306+ }
2307+ while let Some(f) = dec.next_frame() {
2308+ if index == TARGET {
2309+ linear_frame_30 = Some(frame_bytes(&f));
2310+ }
2311+ index += 1;
2312+ }
2313+ }
2314+ dec.flush().expect("flush");
2315+ while let Some(f) = dec.next_frame() {
2316+ if index == TARGET {
2317+ linear_frame_30 = Some(frame_bytes(&f));
2318+ }
2319+ index += 1;
2320+ }
2321+ let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
2322+
2323+ // Find the access unit whose first VCL NAL is a non-IDR I slice
2324+ // (`nal_unit_type` 1, `slice_type % 5 == 2`) — the open-GOP boundary.
2325+ let is_open_gop_i = |au: &[u8]| -> bool {
2326+ let Some((&header, payload)) = au.get(4).zip(au.get(5..)) else {
2327+ return false;
2328+ };
2329+ if header & 0x1F != 1 {
2330+ return false;
2331+ }
2332+ let mut r = ec_core::BitReader::new(payload);
2333+ if r.read_ue().is_err() {
2334+ return false;
2335+ }
2336+ matches!(r.read_ue(), Ok(code) if code % 5 == 2)
2337+ };
2338+ let cra_at = access_units
2339+ .iter()
2340+ .position(|au| is_open_gop_i(au))
2341+ .expect("an open-GOP I access unit exists");
2342+
2343+ // A seek reuses the parameter sets a decoder already learned; a fresh one
2344+ // is primed the way `Decoder::reset_pictures`'s doc comment expects: the
2345+ // leading IDR's parameter sets are decoded and its picture discarded.
2346+ let mut seek_dec = Decoder::new();
2347+ for nal in ec_h264_syntax::AnnexBIter::new(&access_units[0]) {
2348+ seek_dec.push_nal(nal).expect("prime parameter sets");
2349+ }
2350+ seek_dec.end_picture().expect("end priming IDR");
2351+ seek_dec.reset_pictures();
2352+
2353+ let mut seeked_frame = None;
2354+ 'outer: for au in &access_units[cra_at..] {
2355+ for nal in ec_h264_syntax::AnnexBIter::new(au) {
2356+ if seek_dec.push_nal(nal).expect("seek decode") == NalOutcome::PictureBoundary {
2357+ seek_dec.end_picture().expect("end_picture");
2358+ seek_dec.push_nal(nal).expect("re-push");
2359+ }
2360+ }
2361+ if let Some(f) = seek_dec.next_frame() {
2362+ seeked_frame = Some(frame_bytes(&f));
2363+ break 'outer;
2364+ }
2365+ }
2366+ if seeked_frame.is_none() {
2367+ seek_dec.flush().expect("flush");
2368+ seeked_frame = seek_dec.next_frame().map(|f| frame_bytes(&f));
2369+ }
2370+ let seeked_frame = seeked_frame.expect("a frame came out after the seek");
2371+
2372+ assert_eq!(
2373+ seeked_frame, linear_frame_30,
2374+ "seeking to the open-GOP I before frame 30 handed back a different \
2375+ picture than a linear decode of frame 30 — leading pictures with \
2376+ missing references were not dropped"
2377+ );
2378+}
crates/ec-hw/src/dec/dpb264.rsmodified+13 -3
@@ -420,7 +420,8 @@ impl Dpb {
420420 num_l0: usize,
421421 num_l1: usize,
422422 mods: (&[RefPicListMod], &[RefPicListMod]),
423- ) -> Result<[RefList; 2]> {
423+ ) -> Result<([RefList; 2], bool)> {
424+ let mut padded = false;
424425 let mut lists = [RefList::default(), RefList::default()];
425426 let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
426427 let mut n_short = 0usize;
@@ -505,13 +506,16 @@ impl Dpb {
505506 )));
506507 }
507508 let first = lists[x].entries[0];
509+ if lists[x].len < wanted[x] {
510+ padded = true;
511+ }
508512 while lists[x].len < wanted[x] {
509513 lists[x].push(usize::from(first));
510514 }
511515 lists[x].len = wanted[x];
512516 self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
513517 }
514- Ok(lists)
518+ Ok((lists, padded))
515519 }
516520
517521 /// Reference picture list modification (8.2.4.3), by the insert-and-compact
@@ -589,15 +593,21 @@ impl Dpb {
589593 }
590594
591595 /// Store a decoded picture and apply the reference marking of 8.2.5.
596+ ///
597+ /// `output_ok` is false for a picture that predicted from a reference
598+ /// never decoded since the last `reset()` (a random-access leading
599+ /// picture whose ref list build had to pad) — it still joins the DPB as
600+ /// a reference and for bookkeeping, but must never be handed to a caller.
592601 pub(crate) fn store(
593602 &mut self,
594603 mut pic: Picture,
595604 sps: &Sps,
596605 info: &PicInfo,
597606 marking: Option<&DecRefPicMarking>,
607+ output_ok: bool,
598608 ) -> Result<()> {
599609 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
600- pic.output = true;
610+ pic.output = output_ok;
601611 self.number_short_term(info.frame_num, sps);
602612 pic.frame_num_wrap = pic.frame_num as i32;
603613 pic.pic_num = pic.frame_num as i32;
crates/ec-hw/src/dec/h264.rsmodified+22 -3
@@ -38,6 +38,8 @@ struct Current {
3838 /// Parameter and data buffers submitted so far.
3939 buffers: Vec<Buffer>,
4040 slices: usize,
41+ /// Set if any slice's ref list build had to pad (see `H264Decoder::recovery_poc`).
42+ ref_padded: bool,
4143 }
4244
4345 /// A stateless H.264 decoder.
@@ -52,6 +54,14 @@ pub struct H264Decoder {
5254 /// Reusable unescape buffer; NAL payloads are rewritten into it in turn.
5355 rbsp: Vec<u8>,
5456 gap_frames: u64,
57+ /// `PicOrderCnt` of the random-access point most recently established by
58+ /// `reset()` — the first picture decoded after it. `None` before that
59+ /// picture completes. Absent a recovery_point SEI (not parsed here),
60+ /// D.2.8's recovery point defaults to this picture itself: anything with
61+ /// a smaller POC that had to guess a reference (`Current::ref_padded`)
62+ /// predicts from something never decoded since the seek and must not
63+ /// reach the caller.
64+ recovery_poc: Option<i32>,
5565 }
5666
5767 impl H264Decoder {
@@ -68,6 +78,7 @@ impl H264Decoder {
6878 current: None,
6979 rbsp: Vec::new(),
7080 gap_frames: 0,
81+ recovery_poc: None,
7182 }
7283 }
7384
@@ -132,6 +143,7 @@ impl H264Decoder {
132143 self.dpb.clear();
133144 self.ready.clear();
134145 self.gap_frames = 0;
146+ self.recovery_poc = None;
135147 }
136148
137149 /// What the stream turned out to be, once its first SPS was seen.
@@ -268,6 +280,7 @@ impl H264Decoder {
268280 marking: sh.dec_ref_pic_marking.clone(),
269281 buffers: Vec::new(),
270282 slices: 0,
283+ ref_padded: false,
271284 });
272285 Ok(())
273286 }
@@ -317,7 +330,7 @@ impl H264Decoder {
317330 [RefList::default(), RefList::default()]
318331 } else {
319332 self.dpb.number_short_term(sh.frame_num, sps);
320- self.dpb.build_ref_lists(
333+ let (lists, padded) = self.dpb.build_ref_lists(
321334 sh.slice_type,
322335 current.poc.value,
323336 sh.frame_num as i32,
@@ -325,7 +338,9 @@ impl H264Decoder {
325338 sh.num_ref_idx_l0_active as usize,
326339 sh.num_ref_idx_l1_active as usize,
327340 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
328- )?
341+ )?;
342+ current.ref_padded |= padded;
343+ lists
329344 };
330345
331346 let slice_param = slice_parameters(sh, pps, nal, &lists, &self.dpb);
@@ -359,6 +374,10 @@ impl H264Decoder {
359374
360375 session.submit(&current.surface, current.buffers)?;
361376
377+ // See `recovery_poc`'s doc comment.
378+ let recovery_poc = *self.recovery_poc.get_or_insert(current.poc.value);
379+ let output_ok = !(current.ref_padded && current.poc.value < recovery_poc);
380+
362381 let picture = Picture {
363382 id: current.id,
364383 surface: Arc::clone(&current.surface),
@@ -376,7 +395,7 @@ impl H264Decoder {
376395 output: true,
377396 };
378397 self.dpb
379- .store(picture, &sps, &current.info, current.marking.as_ref())?;
398+ .store(picture, &sps, &current.info, current.marking.as_ref(), output_ok)?;
380399 self.bump(false);
381400 Ok(())
382401 }
crates/ec-hw/tests/gpu.rsmodified+94 -0
@@ -1104,6 +1104,100 @@ fn hevc_seek_matches_linear_mkv() {
11041104 );
11051105 }
11061106
1107+/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice
1108+/// (`nal_unit_type` 1) whose predecessors in decode order can still hold
1109+/// references from before it, so leading pictures between it and the next
1110+/// IDR may predict from a picture never decoded since a fresh start there —
1111+/// exactly what a seek does. A decoder started at that I must drop those
1112+/// leading pictures per D.2.8's recovery point default, or its output shifts
1113+/// by however many leading pictures the GOP has.
1114+#[test]
1115+fn h264_seek_matches_linear_open_gop() {
1116+ let Some(display) = display() else { return };
1117+ let path = bitstreams().join("h264-open-gop.mp4");
1118+ let Some(data) = elementary(&path, Codec::H264, 60) else {
1119+ eprintln!("skipped: no h264-open-gop.mp4 fixture (run scripts/gen-fixtures.sh)");
1120+ return;
1121+ };
1122+ let units = split_access_units(&data, Codec::H264);
1123+
1124+ // Linear decode: every picture from the start, frame 30 kept for
1125+ // comparison (the fixture's second I picture, `keyint=30`).
1126+ const TARGET: usize = 30;
1127+ let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1128+ let mut linear_frame_30 = None;
1129+ let mut index = 0usize;
1130+ decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| {
1131+ if index == TARGET {
1132+ linear_frame_30 = Some(frame.to_i420().expect("readback"));
1133+ }
1134+ index += 1;
1135+ })
1136+ .expect("linear decode");
1137+ let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30");
1138+
1139+ // Find the access unit whose first VCL NAL is the open-GOP I picture at
1140+ // this GOP boundary, and feed the decoder from there on, exactly as a
1141+ // seek would: nothing from before it goes in.
1142+ let open_gop_at = units
1143+ .iter()
1144+ .position(|au| is_open_gop_i(au))
1145+ .expect("an open-GOP I access unit exists");
1146+
1147+ // A seek reuses the parameter sets a decoder already learned; a fresh one
1148+ // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a
1149+ // caller to: decode the leading IDR (its picture is thrown away) and
1150+ // reset picture state before feeding the seek target.
1151+ let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens");
1152+ seek_decoder.decode(units[0], 0).expect("prime parameter sets");
1153+ seek_decoder.reset();
1154+ let mut seeked_frame = None;
1155+ for (i, unit) in units[open_gop_at..].iter().enumerate() {
1156+ seek_decoder.decode(unit, i as i64).expect("seek decode");
1157+ if let Some(frame) = seek_decoder.next_frame() {
1158+ seeked_frame = Some(frame.to_i420().expect("readback"));
1159+ break;
1160+ }
1161+ }
1162+ if seeked_frame.is_none() {
1163+ seek_decoder.flush().expect("flush");
1164+ seeked_frame = seek_decoder
1165+ .next_frame()
1166+ .map(|f| f.to_i420().expect("readback"));
1167+ }
1168+ let seeked_frame = seeked_frame.expect("a frame came out after the seek");
1169+
1170+ assert_eq!(
1171+ seeked_frame, linear_frame_30,
1172+ "seeking to the open-GOP I before frame 30 handed back a different \
1173+ picture than a linear decode of frame 30 — leading pictures with \
1174+ missing references were not dropped"
1175+ );
1176+}
1177+
1178+/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice
1179+/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the
1180+/// access unit's first start code rather than assuming a fixed prefix length.
1181+fn is_open_gop_i(au: &[u8]) -> bool {
1182+ let mut i = 0usize;
1183+ while i + 3 < au.len() {
1184+ if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 {
1185+ i += 1;
1186+ continue;
1187+ }
1188+ let header = au[i + 3];
1189+ if header & 0x1f != 1 {
1190+ return false;
1191+ }
1192+ let mut r = ec_core::BitReader::new(&au[i + 4..]);
1193+ if r.read_ue().is_err() {
1194+ return false;
1195+ }
1196+ return matches!(r.read_ue(), Ok(code) if code % 5 == 2);
1197+ }
1198+ false
1199+}
1200+
11071201 /// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21).
11081202 /// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past
11091203 /// non-VCL NALs to the first one that carries a slice.
scripts/gen-fixtures.shmodified+9 -0
@@ -198,6 +198,15 @@ for spec in "${VIDEO_CODECS[@]}"; do
198198 esac
199199 done
200200
201+# Open-GOP H.264: a non-IDR I picture (nal_unit_type 1, not 5) at a GOP
202+# boundary, with B-pyramid pictures around it referencing across the
203+# boundary. A decoder started fresh at that I (what a seek does) must not
204+# hand back a picture whose references it never decoded — the H.264 sibling
205+# of the HEVC RASL/NoRaslOutputFlag case.
206+gen "$FIXTURES/video/h264-open-gop.mp4" \
207+ -f lavfi -i "testsrc2=size=320x240:rate=30:duration=4" -pix_fmt yuv420p \
208+ -c:v libx264 -x264-params "keyint=30:min-keyint=30:open-gop=1:bframes=3:b-pyramid=normal:scenecut=0"
209+
201210 # -------------------------------------------------------------- summary -----
202211 printf '\n%s\n' "== fixtures: $FIXTURES =="
203212 printf '%-42s %10s %s\n' FILE SIZE PROBE