forge
Explore
Log in

Don't you dare go Hollow

A seek lands on the frame it names in an open-GOP stream

Browse files at this commit

ea25339a638419097c276c6b40b109e2c69a5cd5Ahmet Kaan GümüşParent: 8651b15
  • fix
    • a seek lands on the frame it names in an open-GOP stream
Show full message
🐛 fix(decode): a seek lands on the frame it names in an open-GOP stream

A picture's index everywhere above the demuxer is its rank in *display* order,
but both demuxers answered a seek with the position the sync point is *stored*
at. The two are the same number only while nothing is coded out of order -- and
an open-GOP HEVC stream, which is what x265 writes by default and so what every
film off a disc or a web rip is, stores the CRA that opens a GOP ahead of the
RASL leading pictures shown before it. In `test_hevc.mkv` the keyframe shown
30th is block 28, so scrubbing to frame 45 handed back frame 47, and to a
different frame again in a GOP carrying another number of leading pictures.
This is the film-scrub path for a 4K HEVC library.

`sync_display_order` ranks every sync point by the presentation time the
container states -- Matroska block timestamps, an mp4's `stts + ctts`
composition times -- and the seek picks and reports the keyframe at or before
the target *on screen*. The mp4 half is that and nothing else; a track with no
`ctts` box keeps the sample-id path it had, untouched.

The Matroska half has one more thing to say, because its blocks are a window
of ten seconds and a display rank is a statement about the whole film. The
`Cues` already carry that statement: a `CueTime` over the track's frame
duration is how many pictures are *shown* before that keyframe, counted by the
muxer over the file. So the window is ranked among itself by timestamp -- the
same function, the same rule -- and shifted onto the cue's own number, which
makes the two answers one answer. A file walked whole shifts by zero: its
window is the file.

Kept per window rather than per seek, so scrubbing a file that has no usable
cues -- the one case where the window is the whole walk -- ranks it once.

`the_cue_index_and_the_whole_walk_are_the_same_index` now states the claim in
display order too: the lazy window and the whole walk must name the same
picture, and it is the walk's own ranking that says which.
`hw_decode::seek_matches_linear_every_container` sweeps every fixture
container/codec pair at targets on, either side of and away from a keyframe,
plus frame 0 and the last one; it fails on the old code at `test_hevc.mkv`
frame 29.
crates/engine/src/demux.rsmodified+277 -19
@@ -535,6 +535,14 @@ pub struct Mp4Demuxer {
535535 /// `stss` entries, ascending 1-based sample ids. Empty means no `stss` box
536536 /// at all, i.e. every sample is a sync sample.
537537 sync_samples: Vec<u32>,
538+ /// Where every sync sample really sits on screen: `(display index, 0-based
539+ /// sample index)` per [`sync_display_order`]. Empty -- and then unused, the
540+ /// `stss` table above answering on its own -- for a track with no `ctts`
541+ /// box, whose samples are stored in the order they are shown in.
542+ sync_display: Vec<(u32, u32)>,
543+ /// Display index of [`Self::first_sample`], i.e. of frame 0. Zero without a
544+ /// `ctts` box, and not the sample's own position with one.
545+ first_display: u32,
538546 next_sample: u32,
539547 /// Bits per luma sample; see [`Demuxer::bit_depth`].
540548 bit_depth: u8,
@@ -655,6 +663,25 @@ impl Mp4Demuxer {
655663 // Where a seek to frame 0 would put the cursor: the samples the edit list
656664 // trims are still read, they are references for the ones that show.
657665 let next_sample = sync_at_or_before(&sync_samples, first_sample);
666+ // Only a track that carries composition offsets stores its samples out
667+ // of display order, and only an `stss` table makes "which keyframe" a
668+ // question at all -- without either, a sample id *is* a display index
669+ // and the table below would be an index of itself.
670+ let (sync_display, first_display) = match track.trak.mdia.minf.stbl.ctts.as_ref() {
671+ Some(ctts) if !sync_samples.is_empty() => {
672+ let times = composition_times(
673+ stts_pairs(track),
674+ ctts.entries
675+ .iter()
676+ .map(|e| (e.sample_count, e.sample_offset)),
677+ );
678+ let syncs = sync_display_order(&times, |i| {
679+ sync_samples.binary_search(&(i as u32 + 1)).is_ok()
680+ });
681+ (syncs, display_index(&times, first_sample - 1))
682+ }
683+ _ => (Vec::new(), 0),
684+ };
658685 Ok((
659686 VideoMeta {
660687 // The samples the edit list trims off the front are not frames of
@@ -676,6 +703,8 @@ impl Mp4Demuxer {
676703 parameter_sets,
677704 nal_length,
678705 sync_samples,
706+ sync_display,
707+ first_display,
679708 next_sample,
680709 bit_depth,
681710 light: mp4_light(path, track_id),
@@ -725,6 +754,16 @@ impl Mp4Demuxer {
725754 /// sample sits inside what the edit list trims, i.e. those pictures decode as
726755 /// references but are not frame 0 or later.
727756 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
757+ // With composition offsets in play, which sync sample is "at or before"
758+ // the target is a question about display order and sample ids cannot
759+ // answer it ([`sync_display_order`]).
760+ if !self.sync_display.is_empty() {
761+ let target = frame.saturating_add(self.first_display);
762+ let (display, sample) =
763+ sync_display_at_or_before(&self.sync_display, target).unwrap_or((0, 0));
764+ self.next_sample = sample + 1;
765+ return i64::from(display) - i64::from(self.first_display);
766+ }
728767 let target = frame
729768 .saturating_add(self.first_sample)
730769 .clamp(1, self.sample_count.max(1));
@@ -809,6 +848,10 @@ pub struct MkvDemuxer {
809848 base: usize,
810849 /// The keyframe index off the file's `Cues`, empty for a file walked whole.
811850 cues: Vec<Cue>,
851+ /// [`Self::window_syncs`]'s answer, and the `(base, length)` of the window it
852+ /// answers for: recomputed when the window moves and not per seek.
853+ syncs: Vec<(i64, usize)>,
854+ syncs_for: Option<(usize, usize)>,
812855 /// How far [`Self::cues_agree`] has got through `cues`: everything before it
813856 /// has been checked against real blocks, or walked past by a jump, and is
814857 /// never looked at again.
@@ -906,6 +949,8 @@ impl MkvDemuxer {
906949 next: 0,
907950 base: 0,
908951 cues,
952+ syncs: Vec::new(),
953+ syncs_for: None,
909954 checked: 0,
910955 reach: segment.0,
911956 segment,
@@ -1280,21 +1325,79 @@ impl MkvDemuxer {
12801325 if self.window_for(target).is_err() {
12811326 let _ = self.complete_index();
12821327 }
1283- let local = target
1284- .saturating_sub(self.base)
1285- .min(self.blocks.len().saturating_sub(1));
1286- // The keyframe at or before the target, or -- for a stream whose first
1287- // block is not one -- the earliest block there is, which is the only
1288- // place a decoder can be started from anyway. The window starts at a cue,
1289- // which *is* a keyframe, so "the earliest block there is" is the same
1290- // block the whole walk would have landed on.
1291- let chosen = self
1292- .blocks
1293- .get(..=local)
1294- .and_then(|window| window.iter().rposition(|b| b.key))
1295- .unwrap_or(0);
1296- self.next = self.base + chosen;
1297- self.next as i64
1328+ // The keyframe shown at or before the target -- not the one *stored*
1329+ // before it, which is a different block on any stream that codes
1330+ // pictures out of order ([`sync_display_order`]).
1331+ let target = target as i64;
1332+ let syncs = self.window_syncs();
1333+ let (display, at) = match syncs.partition_point(|&(display, _)| display <= target) {
1334+ // Nothing in the window shows at or before the target: the earliest
1335+ // sync point it holds, which is the only place a decoder can be
1336+ // started from anyway. The window starts at a cue, which *is* a
1337+ // keyframe, so that is the block the whole walk would land on too.
1338+ 0 => syncs.first().copied().unwrap_or((self.base as i64, 0)),
1339+ i => syncs[i - 1],
1340+ };
1341+ self.next = self.base + at;
1342+ display
1343+ }
1344+
1345+ /// Every keyframe of the window paired with the display index it really has
1346+ /// in the *file*: `(display, position in the window)`, ascending.
1347+ ///
1348+ /// Which is the one thing a window makes harder than a walk. A picture's
1349+ /// index everywhere above this tier is its rank on screen, and that rank is a
1350+ /// statement about the whole film while this holds ten seconds of it. What
1351+ /// ties the two together is the cue: `Cue::index` *is* a display rank, the
1352+ /// muxer having counted it over the whole file, so the window is ranked among
1353+ /// itself by timestamp ([`sync_display_order`], the same function the mp4
1354+ /// side uses) and that ranking is shifted onto the cue's own number. A file
1355+ /// walked whole is the same rule with the shift at zero -- its window is the
1356+ /// file, and this is then `sync_display_order` exactly.
1357+ ///
1358+ /// Kept for the window it was computed over: a seek into a file that has no
1359+ /// usable cues ranks the whole walk, and scrubbing must not pay that twice.
1360+ fn window_syncs(&mut self) -> &[(i64, usize)] {
1361+ let window = (self.base, self.blocks.len());
1362+ if self.syncs_for == Some(window) {
1363+ return &self.syncs;
1364+ }
1365+ let times: Vec<i64> = self.blocks.iter().map(|b| b.ts).collect();
1366+ let ranked = sync_display_order(&times, |i| self.blocks[i].key);
1367+ let shift = self.window_shift(&ranked);
1368+ self.syncs = ranked
1369+ .into_iter()
1370+ .map(|(display, at)| (i64::from(display) + shift, at as usize))
1371+ .collect();
1372+ self.syncs_for = Some(window);
1373+ &self.syncs
1374+ }
1375+
1376+ /// What the window's own ranking has to be moved by to be the file's: the
1377+ /// display index a cue states for one block of the window, less the rank the
1378+ /// window gives that same block. Zero for a file walked whole.
1379+ fn window_shift(&self, ranked: &[(u32, u32)]) -> i64 {
1380+ if self.complete {
1381+ return 0;
1382+ }
1383+ let held = self.base..self.base + self.blocks.len();
1384+ let first = self.cues.partition_point(|c| c.index < held.start);
1385+ for &cue in &self.cues[first..] {
1386+ if !held.contains(&cue.index) {
1387+ break;
1388+ }
1389+ let Some((at, _)) = self.anchor(cue) else {
1390+ continue;
1391+ };
1392+ if let Some(&(display, _)) = ranked.iter().find(|&&(_, pos)| pos as usize == at) {
1393+ return cue.index as i64 - i64::from(display);
1394+ }
1395+ }
1396+ // No cue of the window names a block it holds, which is the index this
1397+ // demuxer would already have degraded to the walk over. Until it does,
1398+ // the window's own numbering is the file's -- exact for anything not
1399+ // reordered, and never more than the reorder depth out.
1400+ self.base as i64
12981401 }
12991402 }
13001403
@@ -3077,6 +3180,89 @@ fn first_frame_sample(entries: impl IntoIterator<Item = (u32, u32)>, trim: Optio
30773180 trim.map_or(1, |t| packet_at(entries, t, 0).0)
30783181 }
30793182
3183+/// Every sync point of a track paired with the *display* index it is really at:
3184+/// `(display index, decode position)`, ascending. `times` holds each access
3185+/// unit's presentation time in **decode** order -- Matroska block timestamps,
3186+/// mp4 `stts + ctts` composition times -- and `sync` says which of them a
3187+/// decoder may be started on.
3188+///
3189+/// A picture's index everywhere above this tier is its rank in *presentation*
3190+/// order, and a stream that codes pictures out of order does not put its sync
3191+/// points at the same rank in the two: an **open-GOP** HEVC stream (x265's
3192+/// default, so every film off a disc or a web rip) writes the RASL leading
3193+/// pictures of a GOP *after* the CRA that opens it in decode order and *before*
3194+/// it on screen, so the keyframe stored 28th is the 30th picture shown. Seeking
3195+/// by its stored position and then counting frames from there lands two
3196+/// pictures late -- and by however many leading pictures that GOP happens to
3197+/// carry elsewhere, which is why no constant can stand in for this.
3198+///
3199+/// The sort is stable, so blocks sharing a timestamp keep decode order.
3200+fn sync_display_order(times: &[i64], sync: impl Fn(usize) -> bool) -> Vec<(u32, u32)> {
3201+ let mut order: Vec<u32> = (0..times.len() as u32).collect();
3202+ order.sort_by_key(|&i| times[i as usize]);
3203+ order
3204+ .into_iter()
3205+ .enumerate()
3206+ .filter(|&(_, decode)| sync(decode as usize))
3207+ .map(|(display, decode)| (display as u32, decode))
3208+ .collect()
3209+}
3210+
3211+/// Composition (presentation) time of every sample of an mp4 track, in decode
3212+/// order and media ticks: the `stts` decode times with the `ctts` offsets added
3213+/// on, which is the pair that says a B-frame is shown before the picture stored
3214+/// ahead of it. Both tables arrive as their `(sample_count, value)` runs, the
3215+/// shape [`stts_pairs`] already hands the `stts` over in; the `ctts` runs may
3216+/// cover fewer samples than exist, in which case the rest carry no offset.
3217+fn composition_times(
3218+ stts: impl IntoIterator<Item = (u32, u32)>,
3219+ ctts: impl IntoIterator<Item = (u32, i32)>,
3220+) -> Vec<i64> {
3221+ let mut times = Vec::new();
3222+ let mut decode = 0i64;
3223+ for (count, delta) in stts {
3224+ for _ in 0..count {
3225+ times.push(decode);
3226+ decode += i64::from(delta);
3227+ }
3228+ }
3229+ let mut sample = 0usize;
3230+ for (count, offset) in ctts {
3231+ for _ in 0..count {
3232+ match times.get_mut(sample) {
3233+ Some(t) => *t += i64::from(offset),
3234+ None => return times,
3235+ }
3236+ sample += 1;
3237+ }
3238+ }
3239+ times
3240+}
3241+
3242+/// Rank of the sample at 0-based decode index `sample` in presentation order,
3243+/// tie-broken by decode order exactly as [`sync_display_order`]'s stable sort
3244+/// is. Used for frame 0, which an edit list can put at any sample.
3245+fn display_index(times: &[i64], sample: u32) -> u32 {
3246+ let Some(&at) = times.get(sample as usize) else {
3247+ return sample;
3248+ };
3249+ times
3250+ .iter()
3251+ .enumerate()
3252+ .filter(|&(i, &t)| (t, i as u32) < (at, sample))
3253+ .count() as u32
3254+}
3255+
3256+/// The latest sync point at or before display index `frame`, out of a
3257+/// [`sync_display_order`] table. `None` when the track's first sync point is
3258+/// already past `frame`, i.e. there is nothing decodable earlier.
3259+fn sync_display_at_or_before(syncs: &[(u32, u32)], frame: u32) -> Option<(u32, u32)> {
3260+ match syncs.partition_point(|&(display, _)| display <= frame) {
3261+ 0 => None,
3262+ i => Some(syncs[i - 1]),
3263+ }
3264+}
3265+
30803266 /// Largest entry of the ascending sync table that is `<= sample_id`. An empty
30813267 /// table means every sample is a sync sample. When `sample_id` sits before the
30823268 /// first sync sample there is nothing decodable earlier, so that one wins.
@@ -3739,14 +3925,26 @@ mod tests {
37393925 assert_eq!(whole.base, 0, "{name}: a sequential read moved the base");
37403926 assert_eq!(whole.blocks, walk, "{name}: the lazy walk is not the walk");
37413927 // ...and every seek lands where the walk's own rule says, jumping
3742- // backwards and forwards through the cues to get there.
3928+ // backwards and forwards through the cues to get there. The rule is
3929+ // the walk's *display* order ([`sync_display_order`]): which keyframe
3930+ // is "at or before" a frame is a question about the screen, and the
3931+ // window has to answer it out of ten seconds of the file.
3932+ let syncs = {
3933+ let times: Vec<i64> = walk.iter().map(|b| b.ts).collect();
3934+ sync_display_order(&times, |i| walk[i].key)
3935+ };
37433936 for frame in (0..walk.len()).chain((0..walk.len()).rev()) {
37443937 let landed = lazy.seek_to_sync_at_or_before(frame as u32);
3745- let want = walk[..=frame].iter().rposition(|b| b.key).unwrap_or(0);
3746- assert_eq!(landed, want as i64, "{name}: seek to frame {frame}");
3938+ let (display, want) =
3939+ sync_display_at_or_before(&syncs, frame as u32).unwrap_or((0, 0));
3940+ assert_eq!(
3941+ landed,
3942+ i64::from(display),
3943+ "{name}: seek to frame {frame} named a picture the walk does not"
3944+ );
37473945 assert_eq!(
37483946 lazy.blocks[lazy.next - lazy.base],
3749- walk[want],
3947+ walk[want as usize],
37503948 "{name}: the block frame {frame} lands on"
37513949 );
37523950 }
@@ -4348,6 +4546,66 @@ mod tests {
43484546 assert_eq!(sync_at_or_before(&[1, 31, 61], 900), 61, "past the last");
43494547 }
43504548
4549+ /// The open-GOP seek bug: `test_hevc.mkv`'s own timestamps, in the order the
4550+ /// file stores them. The GOP-opening CRA is block 28 and the two blocks
4551+ /// after it are its leading pictures, shown at 28 and 29 -- so the keyframe
4552+ /// is the *30th* picture, and a seek that answered 28 handed back frame 47
4553+ /// when it was asked for 45 (`hw_decode::seek_matches_linear_every_container`).
4554+ #[test]
4555+ fn a_keyframe_is_indexed_by_when_it_shows_not_where_it_is_stored() {
4556+ // ms timestamps: 0, then the 3-picture reorder x265 writes, then the CRA
4557+ // at 1000 ms with two leading pictures behind it in storage.
4558+ let mut times: Vec<i64> = (0..28).map(|i| i64::from(i) * 100 / 3).collect();
4559+ times.swap(1, 3);
4560+ times.extend([1000, 967, 933]);
4561+ let syncs = sync_display_order(&times, |i| i == 0 || i == 28);
4562+ assert_eq!(syncs, vec![(0, 0), (30, 28)], "the CRA is shown 30th");
4563+
4564+ assert_eq!(sync_display_at_or_before(&syncs, 45), Some((30, 28)));
4565+ assert_eq!(
4566+ sync_display_at_or_before(&syncs, 29),
4567+ Some((0, 0)),
4568+ "a leading picture is only reachable from the GOP before it"
4569+ );
4570+ assert_eq!(sync_display_at_or_before(&syncs, 30), Some((30, 28)));
4571+ assert_eq!(sync_display_at_or_before(&syncs, 900), Some((30, 28)));
4572+ assert_eq!(
4573+ sync_display_at_or_before(&[(5, 5)], 2),
4574+ None,
4575+ "nothing decodable before the first sync point"
4576+ );
4577+
4578+ // Decode order back when nothing is reordered, which is what keeps every
4579+ // closed-GOP stream exactly where it was.
4580+ let plain: Vec<i64> = (0..8).map(|i| i64::from(i) * 33).collect();
4581+ assert_eq!(
4582+ sync_display_order(&plain, |i| i % 4 == 0),
4583+ vec![(0, 0), (4, 4)]
4584+ );
4585+ }
4586+
4587+ /// `ctts` is what makes an mp4's samples arrive out of display order, and a
4588+ /// run it does not cover leaves those samples at their decode time.
4589+ #[test]
4590+ fn composition_times_add_the_ctts_delay() {
4591+ // 4 samples, 100 ticks each; the first two swapped by a 100/-100 pair.
4592+ let times = composition_times([(4u32, 100u32)], [(1u32, 100i32), (1, -100)]);
4593+ assert_eq!(times, vec![100, 0, 200, 300]);
4594+ assert_eq!(display_index(&times, 0), 1, "sample 1 is shown second");
4595+ assert_eq!(display_index(&times, 1), 0);
4596+ assert_eq!(display_index(&times, 3), 3);
4597+ assert_eq!(
4598+ composition_times([(2u32, 100u32)], []),
4599+ vec![0, 100],
4600+ "no ctts run at all leaves decode time standing"
4601+ );
4602+ assert_eq!(
4603+ composition_times([(2u32, 100u32)], [(9u32, 50i32)]),
4604+ vec![50, 150],
4605+ "a ctts run past the last sample does not panic"
4606+ );
4607+ }
4608+
43514609 /// The desync bug: NTSC rates must survive the sample table as themselves.
43524610 #[test]
43534611 fn ntsc_frame_rates_come_out_fractional() {
crates/engine/tests/hw_decode.rsmodified+66 -0
@@ -185,6 +185,72 @@ fn seek_matches_linear() {
185185 );
186186 }
187187
188+/// The same promise as [`seek_matches_linear`], made of every container and
189+/// codec pair there is a fixture for and at targets on, either side of and away
190+/// from a keyframe -- because which of them holds is a property of the *stream's
191+/// structure*, not of the seek code alone.
192+///
193+/// An open-GOP HEVC stream (x265's default, so `test_hevc.mkv` and its 10-bit
194+/// twin, and every film off a disc or a web rip) stores the CRA that opens a GOP
195+/// *ahead of* the RASL leading pictures that are shown *before* it: keyframe 30
196+/// on screen is the 28th block in the file. A seek that counts stored positions
197+/// rather than displayed pictures therefore hands back a picture two frames
198+/// later than the index it labels, and by a different amount in a GOP with
199+/// another number of leading pictures. `test_baseline.mp4` alone never showed
200+/// it: it has exactly one keyframe, at frame 0, where the two orders agree.
201+#[test]
202+#[ignore = "needs libengine_hw.so and a VA-API driver"]
203+fn seek_matches_linear_every_container() {
204+ // The hardware path for all of these: there is no software HEVC or AV1
205+ // decoder to compare against. SAFETY: --test-threads=1.
206+ unsafe { std::env::remove_var("VE_SW") };
207+ for name in [
208+ "test_baseline.mp4",
209+ "test_high.mp4",
210+ "test_hevc.mp4",
211+ "test_hevc.mkv",
212+ "test_hevc10.mkv",
213+ "test_h264.mkv",
214+ "test_av1.mkv",
215+ ] {
216+ let path = asset(name);
217+ let (meta, rx) = DecodeSession::open(&path).unwrap_or_else(|e| panic!("{name}: open: {e}"));
218+ // On a keyframe, either side of one, well inside a GOP, the first
219+ // picture and the last -- deduplicated for a fixture short enough that
220+ // some of those coincide.
221+ let mut targets = vec![0, 1, 29, 30, 31, 45, meta.frame_count - 1];
222+ targets.retain(|&t| t < meta.frame_count);
223+ targets.sort_unstable();
224+ targets.dedup();
225+ let linear: Vec<(u32, Vec<u8>)> = rx
226+ .into_iter()
227+ .filter(|f| targets.contains(&f.index))
228+ .map(|f| (f.index, f.bgra))
229+ .collect();
230+ assert_eq!(
231+ linear.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
232+ targets,
233+ "{name}: linear decode never delivered every target"
234+ );
235+ for (target, want) in linear {
236+ let (_, rx, _cancel) = DecodeSession::open_at(&path, target)
237+ .unwrap_or_else(|e| panic!("{name}: open_at({target}): {e}"));
238+ let seeked = rx
239+ .into_iter()
240+ .next()
241+ .unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"));
242+ assert_eq!(
243+ seeked.index, target,
244+ "{name}: first frame after seek is not the target"
245+ );
246+ assert!(
247+ seeked.bgra == want,
248+ "{name}: seek to {target} handed back a different picture than a linear decode of {target}"
249+ );
250+ }
251+ }
252+}
253+
188254 /// Drains a bounded session, returning the indices it delivered. The loop ends
189255 /// only on `RecvError`, i.e. the worker closed the channel by itself.
190256 fn range_indices(path: &Path, start: u32, end: u32) -> Vec<u32> {