forge
Explore
Log in

Don't you dare go Hollow

A Matroska file is read forward without rechecking its index

Browse files at this commit

8d969d023454ea8bad9e5e1b109b405ed0272ad7Ahmet Kaan GümüşParent: 84ee43f
  • perf
    • a Matroska file is read forward without rechecking its index
Show full message
⚡ perf(demux): a Matroska file is read forward without rechecking its index

Reading a cued file from end to end got slower than the whole-cluster walk it
replaced -- 4.8 s to 192.8 s on a 4.9 GB AV1 remux, and worse the longer the
film. The window of blocks grows by a cluster on every read and nothing
trimmed it, while both index checks scanned that window from the front: every
cue the walk had already passed was re-anchored per cluster, and every anchor
scanned to the far end of the window twice. Quadratic in the file's length, so
the numbers only looked fine on a fixture.

Each cue is now checked once. `checked` is how far that has got through the
cue list, and a cue the window jumped past is stepped over rather than
re-examined -- the cue a seek actually anchors on is checked by `jump` itself.
Both scans inside `anchor` are bounded by `REORDER`, which is what they were
describing all along: the block a cue names sits at its own index less
whatever was reordered across it, and only a cue that is not where it says it
is pays the full scan -- once, because that answer degrades to the whole walk.
The cue lookup a seek does is a binary search now, the list being sorted.

  4.9 GB AV1, 282024 blocks   walk 4810 ms -> 3927 ms   open 2654 ms -> 0.5 ms
  7.1 GB HEVC, 171432 blocks  walk 6393 ms -> 5821 ms   open 7326 ms -> 1.8 ms

against the whole-cluster walk this replaced, same access-unit hash on both
files and the same landing for every seek. Reading forward is now cheaper than
the walk instead of 40x it, and the open the cue index bought stays.

A read error while rebuilding the window is no longer dropped on the floor:
answering a seek off a window that belongs to another part of the file is a
landing nobody asked for, so the fallback is named -- the whole walk, the one
index that does not depend on the window.

`a_cue_that_lies_about_its_time_degrades_to_the_walk` is the other half: a real
fixture with one `CueTime` moved a tick, which is a well-formed index naming a
block that does not exist. The walk takes over where the read meets it, every
frame still comes back, and every seek lands where the honest file's does.
crates/engine/src/demux.rsmodified+151 -11
@@ -802,6 +802,10 @@ pub struct MkvDemuxer {
802 base: usize,802 base: usize,
803 /// The keyframe index off the file's `Cues`, empty for a file walked whole.803 /// The keyframe index off the file's `Cues`, empty for a file walked whole.
804 cues: Vec<Cue>,804 cues: Vec<Cue>,
805+ /// How far [`Self::cues_agree`] has got through `cues`: everything before it
806+ /// has been checked against real blocks, or walked past by a jump, and is
807+ /// never looked at again.
808+ checked: usize,
805 /// Where the next cluster to be walked into the window begins, and where the809 /// Where the next cluster to be walked into the window begins, and where the
806 /// segment it belongs to starts and ends.810 /// segment it belongs to starts and ends.
807 reach: u64,811 reach: u64,
@@ -894,6 +898,7 @@ impl MkvDemuxer {
894 next: 0,898 next: 0,
895 base: 0,899 base: 0,
896 cues,900 cues,
901+ checked: 0,
897 reach: segment.0,902 reach: segment.0,
898 segment,903 segment,
899 number: video.number,904 number: video.number,
@@ -1065,9 +1070,29 @@ impl MkvDemuxer {
1065 /// three frames -- and it is counted here, in the window that block was1070 /// three frames -- and it is counted here, in the window that block was
1066 /// found in, rather than assumed to be zero. Assumed zero, a 60-frame HEVC1071 /// found in, rather than assumed to be zero. Assumed zero, a 60-frame HEVC
1067 /// fixture reports 62 frames and seeks two frames past every cut.1072 /// fixture reports 62 frames and seeks two frames past every cut.
1073+ ///
1074+ /// Both scans are bounded, and that is not an optimisation: the window grows
1075+ /// by a cluster on every sequential read, so a scan of it per cue was a walk
1076+ /// of the whole film per ten seconds of it -- 4.8 s of reading a 4.9 GB file
1077+ /// became 192 s. The block a cue names sits at `cue.index - base` less
1078+ /// whatever was reordered across it, so it is looked for in the [`REORDER`]
1079+ /// blocks ending there and only a cue that is not where it says it is costs
1080+ /// the full scan -- once, because that answer degrades to the whole walk.
1068 fn anchor(&self, cue: Cue) -> Option<(usize, usize)> {1081 fn anchor(&self, cue: Cue) -> Option<(usize, usize)> {
1069- let at = self.blocks.iter().position(|b| b.ts == cue.time)?;1082+ let hint = cue.index.saturating_sub(self.base);
1070- let lag = self.blocks[at + 1..]1083+ let lo = hint.saturating_sub(REORDER);
1084+ let hi = (hint + 1).min(self.blocks.len());
1085+ let at = self.blocks[lo..hi]
1086+ .iter()
1087+ .position(|b| b.ts == cue.time)
1088+ .map(|at| lo + at)
1089+ .or_else(|| self.blocks.iter().position(|b| b.ts == cue.time))?;
1090+ // Same bound on the other side: a picture shown before the cue's own is
1091+ // within the encoder's reorder depth of it in storage, which is what
1092+ // `REORDER` is. Counting to the end of the window instead only ever
1093+ // added blocks nothing reordered.
1094+ let tail = self.blocks.len().min(at + 1 + REORDER);
1095+ let lag = self.blocks[at + 1..tail]
1071 .iter()1096 .iter()
1072 .filter(|b| b.ts < cue.time)1097 .filter(|b| b.ts < cue.time)
1073 .count();1098 .count();
@@ -1087,12 +1112,29 @@ impl MkvDemuxer {
1087 /// Cues within [`REORDER`] of the far end of the window are left for the1112 /// Cues within [`REORDER`] of the far end of the window are left for the
1088 /// next cluster: their own reordering has not been walked yet, so checking1113 /// next cluster: their own reordering has not been walked yet, so checking
1089 /// them here would fail a file that is perfectly consistent.1114 /// them here would fail a file that is perfectly consistent.
1090- fn cues_agree(&self) -> bool {1115+ ///
1116+ /// Each cue is checked **once**, in index order, [`Self::checked`] being how
1117+ /// far that has got: a sequential read calls this per cluster, and rechecking
1118+ /// every cue the window had already covered turned reading a film into
1119+ /// quadratic work. A cue the window skipped past -- one before `base` after a
1120+ /// jump -- cannot be checked against blocks nobody walked, so it is stepped
1121+ /// over rather than failed; the cue a seek actually anchors on is checked by
1122+ /// [`Self::jump`] itself.
1123+ fn cues_agree(&mut self) -> bool {
1091 let end = (self.base + self.blocks.len()).saturating_sub(REORDER);1124 let end = (self.base + self.blocks.len()).saturating_sub(REORDER);
1092- self.cues1125+ while let Some(&cue) = self.cues.get(self.checked) {
1093- .iter()1126+ if cue.index >= end {
1094- .filter(|c| (self.base..end).contains(&c.index))1127+ break;
1095- .all(|&c| matches!(self.anchor(c), Some((at, index)) if self.base + at == index))1128+ }
1129+ self.checked += 1;
1130+ if cue.index < self.base {
1131+ continue;
1132+ }
1133+ if !matches!(self.anchor(cue), Some((at, index)) if self.base + at == index) {
1134+ return false;
1135+ }
1136+ }
1137+ true
1096 }1138 }
1097 1139
1098 /// Drops the window and rebuilds it at `cue`'s cluster: the one place the1140 /// Drops the window and rebuilds it at `cue`'s cluster: the one place the
@@ -1151,7 +1193,9 @@ impl MkvDemuxer {
1151 if self.complete {1193 if self.complete {
1152 return Ok(());1194 return Ok(());
1153 }1195 }
1154- let Some(cue) = self.cues.iter().rposition(|c| c.index <= frame) else {1196+ // Binary search, the cues being sorted by index: a 2160p film indexes
1197+ // eleven thousand keyframes and a seek asks this per call.
1198+ let Some(cue) = self.cues.partition_point(|c| c.index <= frame).checked_sub(1) else {
1155 // A file cued from somewhere after its own first frame, seeked to1199 // A file cued from somewhere after its own first frame, seeked to
1156 // before the first cue: nothing indexes that stretch, so the walk1200 // before the first cue: nothing indexes that stretch, so the walk
1157 // does.1201 // does.
@@ -1214,9 +1258,19 @@ impl MkvDemuxer {
1214 let target = (frame as usize).min(self.frames.saturating_sub(1));1258 let target = (frame as usize).min(self.frames.saturating_sub(1));
1215 // The window that holds it, off the `Cues`. A file that cannot be1259 // The window that holds it, off the `Cues`. A file that cannot be
1216 // indexed that way answers here by having been walked whole -- either at1260 // indexed that way answers here by having been walked whole -- either at
1217- // open or by this call -- so a read error is not a refusal, it is the1261+ // open or by this call.
1218- // window staying where it was.1262+ //
1219- let _ = self.window_for(target);1263+ // A read that fails while rebuilding the window leaves the window it had,
1264+ // which is a *different part of the file* -- answering the seek off it
1265+ // would land somewhere the caller did not ask for. So the fallback is
1266+ // named rather than swallowed: the whole walk, the one index that does
1267+ // not depend on the window. If the file cannot be read at all that fails
1268+ // too, and then the window is genuinely all there is; the same error
1269+ // comes back out of the next `next_access_unit`, which has a `Result` to
1270+ // carry it and is where a caller learns the file went away.
1271+ if self.window_for(target).is_err() {
1272+ let _ = self.complete_index();
1273+ }
1220 let local = target1274 let local = target
1221 .saturating_sub(self.base)1275 .saturating_sub(self.base)
1222 .min(self.blocks.len().saturating_sub(1));1276 .min(self.blocks.len().saturating_sub(1));
@@ -3487,6 +3541,92 @@ mod tests {
3487 }3541 }
3488 }3542 }
3489 3543
3544+ /// A `Cues` element that lies is caught and the file is read anyway: the
3545+ /// whole walk answers, and the caller cannot tell.
3546+ ///
3547+ /// The fixture is a real one with its first `CueTime` overwritten -- one
3548+ /// tick on, so it is still a well-formed integer of the same width naming a
3549+ /// frame number the file could have, and still a timestamp no block in the
3550+ /// file carries. That is the shape of the file this whole path exists to
3551+ /// survive: an index whose arithmetic cannot be checked against a block, from
3552+ /// a variable-rate capture or a muxer with a bug. [`MkvDemuxer::cues_agree`]
3553+ /// refuses it at open and [`MkvDemuxer::complete_index`] takes over, and what
3554+ /// must not differ is the answer -- frame count, and where every frame of the
3555+ /// file seeks to.
3556+ #[test]
3557+ fn a_cue_that_lies_about_its_time_degrades_to_the_walk() {
3558+ let source = asset("test_hevc.mkv");
3559+ let mut bytes = std::fs::read(&source).expect("test_hevc.mkv");
3560+ // Where the first `CueTime` sits, found with the reader's own parsers
3561+ // rather than by scanning the file for a byte pattern.
3562+ let mut file = File::open(&source).expect("test_hevc.mkv");
3563+ let end = file.metadata().expect("stat").len();
3564+ let segment = mkv_segment(&mut file, end).expect("segment");
3565+ let (body, stop) = mkv_cues_element(&mut file, segment)
3566+ .expect("the Cues element")
3567+ .expect("a fixture that carries cues");
3568+ let mut cues = vec![0u8; (stop - body) as usize];
3569+ read_exact_at(&mut file, body, &mut cues).expect("the Cues element's bytes");
3570+ let (at, width) = first_cue_time(&cues).expect("a CueTime in the fixture");
3571+ let was = uint_in(&cues, at, at + width);
3572+ let at = body as usize + at;
3573+ bytes[at..at + width].copy_from_slice(&(was + 1).to_be_bytes()[8 - width..]);
3574+ let path = crate::scratch::Scratch::file("lying_cue", "mkv");
3575+ std::fs::write(&path, &bytes).expect("the fixture with one cue changed");
3576+
3577+ let (want, mut walked) = MkvDemuxer::open(&source).expect("the honest file");
3578+ let (got, mut lying) = MkvDemuxer::open(&path).expect("the file whose cue lies");
3579+ assert!(
3580+ !walked.complete && !walked.cues.is_empty(),
3581+ "the source fixture is the cue path, so the comparison means something"
3582+ );
3583+ assert!(
3584+ !lying.complete,
3585+ "the lie is not visible at open -- it is caught where the walk meets it"
3586+ );
3587+ assert_eq!(got.frame_count, want.frame_count, "frame count");
3588+ // Reading the file is what walks past the lying cue, and `cues_agree`
3589+ // catches it there: a cue is only checkable once the blocks around it
3590+ // have been walked, which for a cue at the front of the file is one
3591+ // cluster in.
3592+ let mut read = 0;
3593+ while lying.next_access_unit().expect("read past the lying cue").is_some() {
3594+ read += 1;
3595+ }
3596+ assert_eq!(read, got.frame_count, "every frame of the file came back");
3597+ assert!(
3598+ lying.complete && lying.cues.is_empty(),
3599+ "a cue naming no block was believed"
3600+ );
3601+ for frame in 0..got.frame_count {
3602+ assert_eq!(
3603+ lying.seek_to_sync_at_or_before(frame),
3604+ walked.seek_to_sync_at_or_before(frame),
3605+ "seek to frame {frame} off a cue index that lies"
3606+ );
3607+ }
3608+ }
3609+
3610+ /// Offset (into the `Cues` element's own bytes) and width of the first
3611+ /// `CueTime` there, for the test above.
3612+ fn first_cue_time(cues: &[u8]) -> Option<(usize, usize)> {
3613+ let mut at = 0;
3614+ while let Some((id, body, stop)) = ebml_in(cues, at) {
3615+ at = stop;
3616+ if id != CUE_POINT {
3617+ continue;
3618+ }
3619+ let mut child = body;
3620+ while let Some((id, body, stop)) = ebml_in(&cues[..stop], child) {
3621+ child = stop;
3622+ if id == CUE_TIME {
3623+ return Some((body, stop - body));
3624+ }
3625+ }
3626+ }
3627+ None
3628+ }
3629+
3490 /// What a `TrackEntry` states it is in, whichever of the two elements it3630 /// What a `TrackEntry` states it is in, whichever of the two elements it
3491 /// states it in -- [`mkv_language`]'s whole rule, as asserts.3631 /// states it in -- [`mkv_language`]'s whole rule, as asserts.
3492 #[test]3632 #[test]