forge
Explore
Log in

Don't you dare go Hollow

Open a Matroska file off its Cues, not off every cluster

Browse files at this commit

84ee43f333815fabf7ed2c96765959544cfb6669Ahmet Kaan GümüşParent: 1d9b2f4
  • perf
    • open a Matroska file off its Cues, not off every cluster
Show full message
⚡ perf(demux): open a Matroska file off its Cues, not off every cluster

Opening a Matroska file walked the whole segment -- every cluster header
of every gigabyte -- because Matroska carries no sample table and the
frame count and the sync points had to come from somewhere. That is
seconds of disk per open, and an open happens on every seek, every clip
span and every export source, not once per file.

Matroska has an index of its own and nothing here read it: `Cues`, one
entry per keyframe, written at the far end of the segment and found
through the `SeekHead` in kilobytes. Now the open parses that, and the
clusters are walked only where a caller asks to read -- one cue interval
at a time, ten seconds of film.

Measured, cold (page cache dropped per file) and warm, on the library:

  file                       open cold      open warm     bytes read
  4.9 GB AV1 remux         4027 -> 26 ms   469 -> 0.6 ms  9.9 MB -> 99 KB
  12.1 GB 2160p HEVC       9508 -> 54 ms   958 -> 8.6 ms  13.2 MB -> 1.3 MB
  1.4 GB 720p H.264 (ep)    395 -> 1.8 ms   64 -> 0.2 ms  1.5 MB -> 20 KB

Same answers, not similar ones
- The frame count stays exact at open: the last cue's index plus the
  blocks after it, counted by walking from that cue to the end of the
  segment. No duration-times-rate estimate, nothing corrected under the
  UI later.
- A cue states a *timestamp*, and a stream with B-frames does not store
  its blocks in that order: `anchor` counts the blocks written after a
  cue and shown before it, which is the difference between the frames
  shown before it and its place in the file. Without that a 60-frame
  HEVC fixture reports 62 and every seek lands two frames late.
- `cues_agree` checks that arithmetic against the file's own blocks
  wherever a walk meets a cue. A file that disagrees -- variable rate,
  cue times naming no block -- falls back to the whole walk rather than
  seeking to the wrong frame. So do files with no `Cues` at all, and
  tracks with no `DefaultDuration` (nothing to turn a cue time into a
  frame number with).
- `probe_bitrate` completes the index first: it adds block lengths up
  and wants the file, so it pays the walk it always paid.
- The `Cues` element is read whole and parsed in memory. Element by
  element through the file, a 2160p film's ten thousand cue points cost
  a `pread` apiece: 118 ms of open against 8.6.

Checks
- `demux::tests::the_cue_index_and_the_whole_walk_are_the_same_index`:
  for all 20 Matroska fixtures, the cue index and the whole walk agree
  on the block list, the frame count, and where every frame of the file
  seeks to -- asserted per frame, forwards and backwards.
- `a_file_with_no_cues_is_the_walk_it_always_was`: a fixture with its
  `Cues` id and `SeekHead` pointer overwritten (no muxer here writes a
  file without an index) opens, counts and seeks identically.
- `examples/mkv_open_cost.rs`: open ms, bytes through the read syscalls,
  seek landings and a hash of every access unit. Run against the build
  before this change, the three library files above agree line for line
  on every landing and every hash.

Approach referenced from `matroska-demuxer 0.8.1` (hasenbanck), which
resolves a seek the same way; the parsing is this file's own EBML
reader, no dependency added.
crates/engine/examples/mkv_open_cost.rsadded+101 -0
@@ -0,0 +1,101 @@
1+//! What one open of a video file costs -- wall time and bytes read through the
2+//! read syscalls (`/proc/self/io`'s `rchar`) -- and what it answers: the frame
3+//! count, and where a seek to a given second lands.
4+//!
5+//! `cargo run --release -p engine --example mkv_open_cost -- <file> [secs ...] [all]`
6+//!
7+//! The point of the byte count: a Matroska open that walks every cluster reads
8+//! the whole segment's element headers, which on a multi-gigabyte film is
9+//! hundreds of megabytes of `pread` and seconds of wall clock. One that reads
10+//! the header, the `SeekHead` and the `Cues` reads kilobytes. Same tool on both
11+//! builds, so the two are comparable line for line.
12+//!
13+//! `all` walks every access unit of the file and prints a rolling hash of their
14+//! bytes with the count: two builds that disagree by one block anywhere disagree
15+//! on that number, which is what makes "the lazy index is the same index" a
16+//! check rather than a claim. The per-second lines do the same for a seek --
17+//! landing index and the hash of the access unit handed back there.
18+
19+use std::path::PathBuf;
20+use std::time::Instant;
21+
22+/// Bytes this process has read through `read`/`pread` so far, page cache or
23+/// disk -- what the walk really costs the kernel, independent of what was warm.
24+fn rchar() -> u64 {
25+ std::fs::read_to_string("/proc/self/io")
26+ .ok()
27+ .and_then(|io| {
28+ io.lines()
29+ .find_map(|l| l.strip_prefix("rchar: ")?.trim().parse().ok())
30+ })
31+ .unwrap_or(0)
32+}
33+
34+/// FNV-1a over the bytes, so a run of access units collapses to one number a
35+/// diff can compare.
36+fn fnv(hash: &mut u64, bytes: &[u8]) {
37+ for &b in bytes {
38+ *hash ^= u64::from(b);
39+ *hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
40+ }
41+}
42+
43+fn main() {
44+ let mut args = std::env::args().skip(1);
45+ let path = PathBuf::from(
46+ args.next()
47+ .expect("usage: mkv_open_cost <file> [secs ...] [all]"),
48+ );
49+ let rest: Vec<String> = args.collect();
50+ let walk_all = rest.iter().any(|a| a == "all");
51+ let seeks: Vec<f64> = rest.iter().filter_map(|a| a.parse().ok()).collect();
52+
53+ let before = rchar();
54+ let started = Instant::now();
55+ let (meta, mut demuxer) = engine::demux::Demuxer::open(&path).expect("open");
56+ let open_ms = started.elapsed().as_secs_f64() * 1e3;
57+ let open_bytes = rchar() - before;
58+ println!("file {}", path.display());
59+ println!("open {open_ms:.1} ms, {open_bytes} bytes read");
60+ println!(
61+ "meta {}x{} @ {:.6} fps, {} frames",
62+ meta.width, meta.height, meta.frame_rate, meta.frame_count
63+ );
64+
65+ for secs in seeks {
66+ let frame = (secs * meta.frame_rate).round() as u32;
67+ let before = rchar();
68+ let started = Instant::now();
69+ let landed = demuxer.seek_to_sync_at_or_before(frame);
70+ let au = demuxer.next_access_unit().expect("read after seek");
71+ let ms = started.elapsed().as_secs_f64() * 1e3;
72+ let bytes = rchar() - before;
73+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
74+ let len = au.as_ref().map_or(0, |au| au.len());
75+ if let Some(au) = &au {
76+ fnv(&mut hash, au);
77+ }
78+ println!(
79+ "seek {secs}s -> frame {frame}: landed {landed}, au {len} bytes, hash {hash:016x}, \
80+ {ms:.1} ms, {bytes} bytes read"
81+ );
82+ }
83+
84+ if walk_all {
85+ let before = rchar();
86+ let started = Instant::now();
87+ demuxer.seek_to_sync_at_or_before(0);
88+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
89+ let (mut count, mut bytes) = (0u64, 0u64);
90+ while let Some(au) = demuxer.next_access_unit().expect("read") {
91+ fnv(&mut hash, &au);
92+ bytes += au.len() as u64;
93+ count += 1;
94+ }
95+ println!(
96+ "walk {count} access units, {bytes} bytes, hash {hash:016x}, {:.1} ms, {} bytes read",
97+ started.elapsed().as_secs_f64() * 1e3,
98+ rchar() - before
99+ );
100+ }
101+}
crates/engine/src/demux.rsmodified+813 -128
@@ -224,9 +224,21 @@ pub fn probe_bitrate(path: &Path) -> MediaBitrate {
224 audio: total,224 audio: total,
225 };225 };
226 }226 }
227- let Ok((meta, demuxer)) = Demuxer::open(path) else {227+ let Ok((meta, mut demuxer)) = Demuxer::open(path) else {
228 return unstated;228 return unstated;
229 };229 };
230+ // The one caller that wants the whole index rather than a window: this adds
231+ // block *lengths* up, and a Matroska open only walks the clusters a read
232+ // asked for ([`MkvDemuxer`]). So the walk this probe always paid is paid
233+ // here, where the numbers need it, and not by the opens that seek and
234+ // decode. A file that will not walk keeps whatever window it has -- the
235+ // rates then describe part of the file, which is why the failure is not
236+ // ignored but taken as "no measurement".
237+ if let Demuxer::Mkv(d) = &mut demuxer
238+ && d.complete_index().is_err()
239+ {
240+ return unstated;
241+ }
230 // How long the *file* plays, which on a well-made file is how long its242 // How long the *file* plays, which on a well-made file is how long its
231 // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s243 // picture plays and on a badly-made one is not: a 2 s clip carrying a 60 s
232 // commentary is 60 s of file, and dividing its bytes by 2 claims thirty244 // commentary is 60 s of file, and dividing its bytes by 2 claims thirty
@@ -735,12 +747,29 @@ struct Block {
735 747
736 /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).748 /// AV1, HEVC or H.264 out of a Matroska file (`.mkv`/`.webm`).
737 ///749 ///
738-/// The whole segment is walked once at open -- element *headers* only, the block750+/// Matroska carries no sample table, so where an mp4 has an `stss` this has to
739-/// payloads are seeked over -- because Matroska carries no sample table: the751+/// read the file. What it reads is the file's own **`Cues`**: the seek index a
740-/// frame count and the sync points exist nowhere else, and Cues index only some752+/// muxer writes at the far end of the segment, one entry per keyframe, found
741-/// keyframes and only when a muxer bothered to write them.753+/// through the `SeekHead` in kilobytes rather than gigabytes. The clusters
754+/// themselves are walked **only where a caller asks to read** -- one cue
755+/// interval at a time, ten seconds of film -- and the window of [`Block`]s that
756+/// walk builds is what [`Self::next_access_unit`] hands out.
757+///
758+/// That turned a 4.9 GB film's open from 3.2 s cold (9.9 MB of element headers,
759+/// every cluster in the file) into ~30 ms, and an open happens on every seek and
760+/// every clip span, not once per file.
761+///
762+/// A file with no usable `Cues` -- no index at all, or a track that declares no
763+/// `DefaultDuration`, so a cue time cannot be turned into a frame number -- gets
764+/// the whole-segment walk this always did ([`mkv_blocks`]), which is also where
765+/// a cue index caught disagreeing with the blocks it names degrades to
766+/// ([`Self::cues_agree`]). Both paths answer the same questions with the same
767+/// numbers; only what they read to do it differs.
742 pub struct MkvDemuxer {768 pub struct MkvDemuxer {
743 file: File,769 file: File,
770+ /// The blocks walked so far, which for a lazily indexed file is the window
771+ /// around what has been read and not the file: `blocks[i]` is the file's
772+ /// block `base + i`.
744 blocks: Vec<Block>,773 blocks: Vec<Block>,
745 codec: Codec,774 codec: Codec,
746 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of775 /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of
@@ -765,14 +794,39 @@ pub struct MkvDemuxer {
765 /// megabyte and it is reframed, not handed over, so the read needs a794 /// megabyte and it is reframed, not handed over, so the read needs a
766 /// landing place of its own.795 /// landing place of its own.
767 scratch: Vec<u8>,796 scratch: Vec<u8>,
797+ /// The file's own number for the block handed out next -- an index into
798+ /// `blocks` only after `base` is taken off it.
768 next: usize,799 next: usize,
800+ /// The file's number for `blocks[0]`; `0` whenever the index is the whole
801+ /// walk, which is what makes the two paths one lookup.
802+ base: usize,
803+ /// The keyframe index off the file's `Cues`, empty for a file walked whole.
804+ cues: Vec<Cue>,
805+ /// Where the next cluster to be walked into the window begins, and where the
806+ /// segment it belongs to starts and ends.
807+ reach: u64,
808+ segment: (u64, u64),
809+ /// `TrackNumber` of the picture, which the lazy walk needs to filter the
810+ /// clusters it opens later by.
811+ number: u64,
812+ /// How many blocks the track has in the whole file: `blocks.len()` for a
813+ /// walked file, and for a cued one the last cue's index plus the blocks
814+ /// after it, counted at open ([`Self::count_frames`]). Exact either way --
815+ /// it is the clip's length on the timeline.
816+ frames: usize,
817+ /// Whether `blocks` is the whole file rather than a window: what
818+ /// [`probe_bitrate`] needs before it adds block lengths up, and what says a
819+ /// read past the end of `blocks` is the end of the track and not a cluster
820+ /// nobody has walked yet.
821+ complete: bool,
769 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]822 /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]
770 /// for a file that declares none, which is most of them.823 /// for a file that declares none, which is most of them.
771 unpack: Unpack,824 unpack: Unpack,
772- /// Block bytes per `TrackNumber`, counted by the one walk the open already825+ /// Block bytes per `TrackNumber` over the clusters walked so far -- the
773- /// does -- the sound track's as well as the picture's. [`probe_bitrate`] is826+ /// sound track's as well as the picture's, since a block's length is already
774- /// the only reader; see [`mkv_blocks`] for why it is collected here rather827+ /// parsed on the way to skipping it. [`probe_bitrate`] is the only reader,
775- /// than by a pass of its own.828+ /// and it completes the index first: on a lazily opened file this holds the
829+ /// window's tracks and not the file's.
776 track_bytes: Vec<(u64, u64)>,830 track_bytes: Vec<(u64, u64)>,
777 /// `TrackNumber` of the file's first audio track, the one831 /// `TrackNumber` of the file's first audio track, the one
778 /// [`matroska_audio_codec`] also answers for; `None` for a silent file.832 /// [`matroska_audio_codec`] also answers for; `None` for a silent file.
@@ -815,8 +869,47 @@ impl MkvDemuxer {
815 if let Unpack::Refused(why) = &video.unpack {869 if let Unpack::Refused(why) = &video.unpack {
816 return Err(why.clone().into());870 return Err(why.clone().into());
817 }871 }
818- let (blocks, span, track_bytes) = mkv_blocks(&mut file, segment, video.number)?;872+ // `DefaultDuration` is nanoseconds a frame and exact -- 33333333 for
819- if blocks.is_empty() {873+ // 30 fps, 41708333 for 23.976 -- and it is what turns a `CueTime` into a
874+ // frame number, so a track that states one can be opened off the file's
875+ // seek index. `TimestampScale` is nanoseconds a tick, so their ratio is
876+ // ticks a frame, which is the unit `Cues` speak in.
877+ let ticks_per_frame = video
878+ .default_duration
879+ .map(|ns| ns as f64 / video.timestamp_scale as f64)
880+ .filter(|&t| t > 0.0);
881+ let cues = match ticks_per_frame {
882+ Some(ticks) => mkv_cues(&mut file, segment, video.number, ticks)?,
883+ None => Vec::new(),
884+ };
885+ let mut mkv = Self {
886+ file,
887+ blocks: Vec::new(),
888+ codec: video.codec,
889+ config: video.config,
890+ nal_length: video.nal_length,
891+ bit_depth: video.bit_depth,
892+ light: video.light,
893+ scratch: Vec::new(),
894+ next: 0,
895+ base: 0,
896+ cues,
897+ reach: segment.0,
898+ segment,
899+ number: video.number,
900+ frames: 0,
901+ complete: false,
902+ unpack: video.unpack,
903+ track_bytes: Vec::new(),
904+ audio_number: audio.first().map(|t| t.number),
905+ container_secs,
906+ };
907+ // What the first cluster holds, and -- for a cued file -- how many
908+ // blocks there are in the whole of it. Either answer may find the cue
909+ // index unusable and fall back to the walk, which is why the frame count
910+ // is read off the demuxer afterwards rather than returned from here.
911+ mkv.count_frames()?;
912+ if mkv.frames == 0 {
820 return Err(format!(913 return Err(format!(
821 "the {} track in this Matroska file has no frames",914 "the {} track in this Matroska file has no frames",
822 video.codec.name()915 video.codec.name()
@@ -824,11 +917,12 @@ impl MkvDemuxer {
824 .into());917 .into());
825 }918 }
826 // Timing, in this order: what the track declares, then what its own919 // Timing, in this order: what the track declares, then what its own
827- // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333920+ // timestamps say. `DefaultDuration` is preferred for being exact; the
828- // for 30 fps, 41708333 for 23.976 -- which is the whole reason it is921+ // fallback measures the presentation span instead, and that is in
829- // preferred; the fallback measures the presentation span instead, and922+ // `TimestampScale` ticks (a millisecond, as good as every muxer writes),
830- // that is in `TimestampScale` ticks (a millisecond, as good as every923+ // so it lands within ~0.05 % rather than exactly. Only a file with no
831- // muxer writes), so it lands within ~0.05 % rather than exactly.924+ // `DefaultDuration` reaches it, and such a file was walked whole just
925+ // above -- the span is the window's, and the window is the file.
832 //926 //
833 // ponytail: a genuinely variable-rate file is averaged to one rate here,927 // ponytail: a genuinely variable-rate file is averaged to one rate here,
834 // because a timeline frame is a fixed slice of a second everywhere else928 // because a timeline frame is a fixed slice of a second everywhere else
@@ -836,49 +930,238 @@ impl MkvDemuxer {
836 // a project-wide change, not a demuxer one.930 // a project-wide change, not a demuxer one.
837 let frame_rate = match video.default_duration {931 let frame_rate = match video.default_duration {
838 Some(ns) => 1e9 / ns as f64,932 Some(ns) => 1e9 / ns as f64,
839- None => match span {933+ None => {
840- Some((first, last)) if last > first && blocks.len() > 1 => {934+ let span = mkv
841- (blocks.len() - 1) as f64 * 1e9935+ .blocks
842- / ((last - first) as f64 * video.timestamp_scale as f64)936+ .iter()
937+ .map(|b| b.ts)
938+ .min()
939+ .zip(mkv.blocks.iter().map(|b| b.ts).max());
940+ match span {
941+ Some((first, last)) if last > first && mkv.blocks.len() > 1 => {
942+ (mkv.blocks.len() - 1) as f64 * 1e9
943+ / ((last - first) as f64 * video.timestamp_scale as f64)
944+ }
945+ // Nothing said and nothing measurable: `fps_from_stts`
946+ // answers an mp4 with no timing the same way.
947+ _ => 0.0,
843 }948 }
844- // Nothing said and nothing measurable: `fps_from_stts` answers949+ }
845- // an mp4 with no timing the same way.
846- _ => 0.0,
847- },
848 };950 };
849 let meta = VideoMeta {951 let meta = VideoMeta {
850 width: video.width,952 width: video.width,
851 height: video.height,953 height: video.height,
852 frame_rate,954 frame_rate,
853- frame_count: blocks.len() as u32,955+ frame_count: mkv.frames as u32,
854 codec: video.codec,956 codec: video.codec,
855 // `config` is the parameter sets by now -- Annex-B for H.264 and957 // `config` is the parameter sets by now -- Annex-B for H.264 and
856 // HEVC, the sequence header OBU for AV1 -- which is what the958 // HEVC, the sequence header OBU for AV1 -- which is what the
857 // bitstream tier reads.959 // bitstream tier reads.
858 color: ColorDescription::resolve(960 color: ColorDescription::resolve(
859 video.tags,961 video.tags,
860- bitstream_tags(video.codec, &video.config),962+ bitstream_tags(video.codec, &mkv.config),
861 video.height,963 video.height,
862 ),964 ),
863 };965 };
864- Ok((966+ Ok((meta, mkv))
865- meta,967+ }
866- Self {968+
867- file,969+ /// How many blocks the track has, and a window ready at the front of the
868- blocks,970+ /// file for the read that follows.
869- codec: video.codec,971+ ///
870- config: video.config,972+ /// For a walked file that is the walk's own length. For a cued one it is the
871- nal_length: video.nal_length,973+ /// **last cue's index plus the blocks after it**, counted by walking from
872- bit_depth: video.bit_depth,974+ /// that cue to the end of the segment -- one cue interval, ten seconds of
873- light: video.light,975+ /// film, rather than all of it. Exact at open, not a duration times a rate
874- scratch: Vec::new(),976+ /// corrected later: a clip's length on the timeline is the first thing the
875- next: 0,977+ /// UI shows and the last thing that may move under it.
876- unpack: video.unpack,978+ ///
877- track_bytes,979+ /// The first cluster is walked before that, so the cue arithmetic is checked
878- audio_number: audio.first().map(|t| t.number),980+ /// against real blocks at index 0 (where the file's own numbering starts)
879- container_secs,981+ /// before anything is counted off it.
880- },982+ fn count_frames(&mut self) -> crate::Result<()> {
881- ))983+ if self.cues.is_empty() {
984+ return self.complete_index();
985+ }
986+ self.walk_cluster()?;
987+ if !self.cues_agree() {
988+ return self.complete_index();
989+ }
990+ let Some(&last) = self.cues.last() else {
991+ return self.complete_index();
992+ };
993+ self.jump(last)?;
994+ while self.walk_cluster()? {}
995+ if !self.complete {
996+ self.frames = self.base + self.blocks.len();
997+ // Back to the front: what a decoder asks for first is frame 0, and
998+ // the tail window is the wrong end of the file for it.
999+ self.blocks.clear();
1000+ self.track_bytes.clear();
1001+ self.base = 0;
1002+ self.reach = self.segment.0;
1003+ }
1004+ Ok(())
1005+ }
1006+
1007+ /// The whole segment walked, as every open used to do it: what a file with
1008+ /// no usable `Cues` gets, and what a cue index caught disagreeing with the
1009+ /// file's own blocks degrades to. Idempotent, and the only thing that sets
1010+ /// [`Self::complete`].
1011+ fn complete_index(&mut self) -> crate::Result<()> {
1012+ if self.complete {
1013+ return Ok(());
1014+ }
1015+ let (blocks, _, track_bytes) = mkv_blocks(&mut self.file, self.segment, self.number)?;
1016+ self.frames = blocks.len();
1017+ self.blocks = blocks;
1018+ self.track_bytes = track_bytes;
1019+ self.base = 0;
1020+ self.reach = self.segment.1;
1021+ self.cues.clear();
1022+ self.complete = true;
1023+ Ok(())
1024+ }
1025+
1026+ /// Walks the next `Cluster` at or after [`Self::reach`] onto the end of the
1027+ /// window. `false` once the segment is out of clusters.
1028+ fn walk_cluster(&mut self) -> crate::Result<bool> {
1029+ let Self {
1030+ file,
1031+ blocks,
1032+ track_bytes,
1033+ reach,
1034+ segment,
1035+ number,
1036+ ..
1037+ } = self;
1038+ let mut laced = Vec::new();
1039+ while let Some((id, body, stop)) = ebml_element(file, *reach, segment.1)? {
1040+ *reach = stop;
1041+ if id != CLUSTER {
1042+ continue;
1043+ }
1044+ mkv_cluster(file, body, stop, *number, blocks, track_bytes, &mut laced)?;
1045+ // Per window rather than per file, which is the one thing the two
1046+ // paths do differently: the last lace of a window has no block after
1047+ // it *yet*. Video is never laced -- lacing is a sound-track trick,
1048+ // and `MkvAudio` reads sound off the whole walk -- so this is a
1049+ // difference of principle rather than one anything exercises.
1050+ mkv_spread_laces(blocks, &laced);
1051+ return Ok(true);
1052+ }
1053+ Ok(false)
1054+ }
1055+
1056+ /// Where the block a cue names sits in the window, and what the file's own
1057+ /// number for that block is -- `None` when the window does not hold it.
1058+ ///
1059+ /// The second number is the whole subtlety of reading `Cues`. A cue states a
1060+ /// *timestamp*, and a Matroska timestamp is a presentation time: a stream
1061+ /// with B-frames does not store its blocks in that order, so the count of
1062+ /// frames shown before a cue is not the count of blocks written before it.
1063+ /// The difference is exactly the blocks that sit *after* this one in the
1064+ /// file and are shown before it -- the encoder's reordering depth, two or
1065+ /// 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 HEVC
1067+ /// fixture reports 62 frames and seeks two frames past every cut.
1068+ fn anchor(&self, cue: Cue) -> Option<(usize, usize)> {
1069+ let at = self.blocks.iter().position(|b| b.ts == cue.time)?;
1070+ let lag = self.blocks[at + 1..]
1071+ .iter()
1072+ .filter(|b| b.ts < cue.time)
1073+ .count();
1074+ Some((at, cue.index.checked_sub(lag)?))
1075+ }
1076+
1077+ /// Every cue the window reaches names a block whose timestamp it states, at
1078+ /// the index the arithmetic says.
1079+ ///
1080+ /// This is what makes a cue index safe to count frames off: `CueTime` over
1081+ /// `DefaultDuration` is a frame number only while the track really runs at
1082+ /// that rate, and a file where it does not -- a variable-rate capture, a
1083+ /// muxer whose cue times name no block at all -- is caught here, wherever
1084+ /// the walk meets a cue, and degrades to the whole walk rather than seeking
1085+ /// to a frame that is not the one asked for.
1086+ ///
1087+ /// 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 checking
1089+ /// them here would fail a file that is perfectly consistent.
1090+ fn cues_agree(&self) -> bool {
1091+ let end = (self.base + self.blocks.len()).saturating_sub(REORDER);
1092+ self.cues
1093+ .iter()
1094+ .filter(|c| (self.base..end).contains(&c.index))
1095+ .all(|&c| matches!(self.anchor(c), Some((at, index)) if self.base + at == index))
1096+ }
1097+
1098+ /// Drops the window and rebuilds it at `cue`'s cluster: the one place the
1099+ /// file is read out of order, and the whole point of parsing `Cues`.
1100+ ///
1101+ /// The cue's own block is found in that cluster by the timestamp the cue
1102+ /// states, and [`Self::anchor`]'s number for it is what fixes the window's
1103+ /// `base` -- so a cue naming the third block of its cluster still leaves the
1104+ /// two before it numbered as the file numbers them.
1105+ fn jump(&mut self, cue: Cue) -> crate::Result<()> {
1106+ self.blocks.clear();
1107+ self.track_bytes.clear();
1108+ self.base = cue.index;
1109+ self.reach = cue.cluster;
1110+ self.walk_cluster()?;
1111+ // Enough of the file past the cue's own block to count what was
1112+ // reordered around it, which the last cluster of a segment may not have.
1113+ while self
1114+ .blocks
1115+ .iter()
1116+ .position(|b| b.ts == cue.time)
1117+ .is_some_and(|at| self.blocks.len() < at + 1 + REORDER)
1118+ && self.walk_cluster()?
1119+ {}
1120+ match self.anchor(cue) {
1121+ Some((at, index)) if index >= at => self.base = index - at,
1122+ // The cluster the cue points at does not hold the block it names, or
1123+ // names it at an index the file cannot have: the index is not
1124+ // describing this file, so stop believing it.
1125+ _ => self.complete_index()?,
1126+ }
1127+ Ok(())
1128+ }
1129+
1130+ /// Walks clusters until the window holds the file's block `want`, or until
1131+ /// the segment runs out of them.
1132+ fn extend_to(&mut self, want: usize) -> crate::Result<()> {
1133+ while !self.complete && self.base + self.blocks.len() <= want {
1134+ if !self.walk_cluster()? {
1135+ break;
1136+ }
1137+ if !self.cues_agree() {
1138+ return self.complete_index();
1139+ }
1140+ }
1141+ Ok(())
1142+ }
1143+
1144+ /// The window that holds the file's block `frame`, starting at a keyframe at
1145+ /// or before it -- the cue at or before `frame`, which is where the walk
1146+ /// this replaces would have found one too.
1147+ ///
1148+ /// Reached forward where the window already runs that far (playing on
1149+ /// through a cue costs no jump), rebuilt at the cue where it does not.
1150+ fn window_for(&mut self, frame: usize) -> crate::Result<()> {
1151+ if self.complete {
1152+ return Ok(());
1153+ }
1154+ let Some(cue) = self.cues.iter().rposition(|c| c.index <= frame) else {
1155+ // A file cued from somewhere after its own first frame, seeked to
1156+ // before the first cue: nothing indexes that stretch, so the walk
1157+ // does.
1158+ return self.complete_index();
1159+ };
1160+ let cue = self.cues[cue];
1161+ if !(self.base..self.base + self.blocks.len()).contains(&cue.index) {
1162+ self.jump(cue)?;
1163+ }
1164+ self.extend_to(frame)
882 }1165 }
883 1166
884 /// Next access unit in decode order: the block verbatim for AV1, which is1167 /// Next access unit in decode order: the block verbatim for AV1, which is
@@ -886,7 +1169,17 @@ impl MkvDemuxer {
886 /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed1169 /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed
887 /// NALs an mp4 sample does.1170 /// NALs an mp4 sample does.
888 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {1171 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
889- let Some(&block) = self.blocks.get(self.next) else {1172+ // Reading off the end of the window is not the end of the track: it is
1173+ // the next cluster, not yet walked. The end of the track is the end of
1174+ // the segment, which is what `extend_to` stops at.
1175+ if self.next >= self.base + self.blocks.len() {
1176+ self.extend_to(self.next)?;
1177+ }
1178+ let Some(&block) = self
1179+ .next
1180+ .checked_sub(self.base)
1181+ .and_then(|i| self.blocks.get(i))
1182+ else {
890 return Ok(None);1183 return Ok(None);
891 };1184 };
892 self.next += 1;1185 self.next += 1;
@@ -918,14 +1211,26 @@ impl MkvDemuxer {
918 /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska1211 /// As [`Mp4Demuxer::seek_to_sync_at_or_before`]. Never negative: Matroska
919 /// has no edit list, so block 0 is frame 0.1212 /// has no edit list, so block 0 is frame 0.
920 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {1213 fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
921- let target = (frame as usize).min(self.blocks.len().saturating_sub(1));1214+ let target = (frame as usize).min(self.frames.saturating_sub(1));
1215+ // 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 at
1217+ // open or by this call -- so a read error is not a refusal, it is the
1218+ // window staying where it was.
1219+ let _ = self.window_for(target);
1220+ let local = target
1221+ .saturating_sub(self.base)
1222+ .min(self.blocks.len().saturating_sub(1));
922 // The keyframe at or before the target, or -- for a stream whose first1223 // The keyframe at or before the target, or -- for a stream whose first
923 // block is not one -- the earliest block there is, which is the only1224 // block is not one -- the earliest block there is, which is the only
924- // place a decoder can be started from anyway.1225+ // place a decoder can be started from anyway. The window starts at a cue,
925- self.next = self.blocks[..=target]1226+ // which *is* a keyframe, so "the earliest block there is" is the same
926- .iter()1227+ // block the whole walk would have landed on.
927- .rposition(|b| b.key)1228+ let chosen = self
1229+ .blocks
1230+ .get(..=local)
1231+ .and_then(|window| window.iter().rposition(|b| b.key))
928 .unwrap_or(0);1232 .unwrap_or(0);
1233+ self.next = self.base + chosen;
929 self.next as i641234 self.next as i64
930 }1235 }
931 }1236 }
@@ -1263,6 +1568,19 @@ const CONTENT_ENCODING_TYPE: u32 = 0x5033;
1263 const CONTENT_COMPRESSION: u32 = 0x5034;1568 const CONTENT_COMPRESSION: u32 = 0x5034;
1264 const CONTENT_COMP_ALGO: u32 = 0x4254;1569 const CONTENT_COMP_ALGO: u32 = 0x4254;
1265 const CONTENT_COMP_SETTINGS: u32 = 0x4255;1570 const CONTENT_COMP_SETTINGS: u32 = 0x4255;
1571+// The seek index and the table of contents that points at it. `SeekHead` is
1572+// how a file whose `Cues` sit at the far end -- which is where every muxer but
1573+// `-cues_to_front` writes them -- is found without reading what is in between.
1574+const SEEK_HEAD: u32 = 0x114D_9B74;
1575+const SEEK: u32 = 0x4DBB;
1576+const SEEK_ID: u32 = 0x53AB;
1577+const SEEK_POSITION: u32 = 0x53AC;
1578+const CUES: u32 = 0x1C53_BB6B;
1579+const CUE_POINT: u32 = 0xBB;
1580+const CUE_TIME: u32 = 0xB3;
1581+const CUE_TRACK_POSITIONS: u32 = 0xB7;
1582+const CUE_TRACK: u32 = 0xF7;
1583+const CUE_CLUSTER_POSITION: u32 = 0xF1;
1266 const CLUSTER: u32 = 0x1F43_B675;1584 const CLUSTER: u32 = 0x1F43_B675;
1267 const CLUSTER_TIMESTAMP: u32 = 0xE7;1585 const CLUSTER_TIMESTAMP: u32 = 0xE7;
1268 const SIMPLE_BLOCK: u32 = 0xA3;1586 const SIMPLE_BLOCK: u32 = 0xA3;
@@ -1788,6 +2106,188 @@ fn vp9_bit_depth(au: &[u8]) -> crate::Result<Option<u8>> {
1788 }2106 }
1789 }2107 }
1790 2108
2109+/// How many blocks past a cue's own the walk looks to count what the encoder
2110+/// reordered around it ([`MkvDemuxer::anchor`]). Wider than any real stream
2111+/// needs: H.264 and HEVC cap `max_num_reorder_frames` at 16, and what a muxer
2112+/// actually writes is two or three.
2113+///
2114+/// ponytail: a stream that reorders further than this would have its blocks
2115+/// numbered a frame or two off. The upgrade path is the bitstream's own
2116+/// `max_num_reorder_frames` out of the SPS, which this demuxer does not parse;
2117+/// [`MkvDemuxer::cues_agree`] is what stands between that file and a wrong seek
2118+/// in the meantime -- it degrades to the whole walk instead.
2119+const REORDER: usize = 32;
2120+
2121+/// One `CuePoint` of the picture track: the timestamp it names, which block of
2122+/// the track that timestamp *is*, and where the `Cluster` holding it starts.
2123+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2124+struct Cue {
2125+ /// `CueTime`, in `TimestampScale` ticks -- the block's own timestamp, which
2126+ /// is what picks it out of its cluster once that cluster is walked.
2127+ time: i64,
2128+ /// How many frames are *shown* before it: `CueTime` over the track's
2129+ /// `DefaultDuration`. Matroska indexes time and everything above this
2130+ /// demuxer counts frames, so this one division is what the lazy index rests
2131+ /// on -- and it is a display count, which on a stream with B-frames is not
2132+ /// the block's place in the file ([`MkvDemuxer::anchor`] takes the
2133+ /// difference out). [`MkvDemuxer::cues_agree`] checks the whole arithmetic
2134+ /// against the file's own blocks wherever the walk meets a cue.
2135+ index: usize,
2136+ /// Absolute file offset of that `Cluster`; `CueClusterPosition` states it
2137+ /// relative to the start of the segment's payload.
2138+ cluster: u64,
2139+}
2140+
2141+/// The picture track's `Cues` in index order, empty for a file carrying none
2142+/// this can use -- Matroska's own seek index, which is what a player reads
2143+/// instead of the film to know where its keyframes are.
2144+///
2145+/// Approach referenced from `matroska-demuxer 0.8.1` (hasenbanck), which
2146+/// resolves a seek the same way: the `CueTrackPositions` of the wanted track,
2147+/// its `CueClusterPosition` off the segment, then that cluster. The parsing is
2148+/// this file's own EBML reader -- no dependency is added for four elements.
2149+///
2150+/// `ticks_per_frame` is the track's `DefaultDuration` in `TimestampScale`
2151+/// ticks. Without it a cue time cannot become a frame number at all, which is
2152+/// why the caller keeps the whole walk for a track that declares no duration.
2153+fn mkv_cues(
2154+ file: &mut File,
2155+ segment: (u64, u64),
2156+ number: u64,
2157+ ticks_per_frame: f64,
2158+) -> crate::Result<Vec<Cue>> {
2159+ let Some((body, end)) = mkv_cues_element(file, segment)? else {
2160+ return Ok(Vec::new());
2161+ };
2162+ // Read whole and parsed in memory, not element by element through the file:
2163+ // a 2160p film's index is ten thousand cue points and a hundred thousand
2164+ // EBML elements, and one `pread` apiece is 120 ms of open against 5 ms. The
2165+ // ceiling is what keeps a crafted header from asking for all the memory
2166+ // there is -- an hour of 24 fps cues to about 200 KB.
2167+ const LIMIT: u64 = 64 << 20;
2168+ if end.saturating_sub(body) > LIMIT {
2169+ return Ok(Vec::new());
2170+ }
2171+ let mut buf = vec![0u8; (end - body) as usize];
2172+ read_exact_at(file, body, &mut buf)?;
2173+ let mut cues = Vec::new();
2174+ let mut at = 0;
2175+ while let Some((id, body, stop)) = ebml_in(&buf, at) {
2176+ at = stop;
2177+ if id != CUE_POINT {
2178+ continue;
2179+ }
2180+ let (mut time, mut cluster) = (None, None);
2181+ let mut child = body;
2182+ while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
2183+ child = stop;
2184+ match id {
2185+ CUE_TIME => time = Some(uint_in(&buf, body, stop) as i64),
2186+ // One `CuePoint` carries a position per track -- a film's
2187+ // picture and its sound are cued at the same instant -- so the
2188+ // picture's is picked by `CueTrack` and the others skipped.
2189+ // Taking them all is an index three times too long, two thirds
2190+ // of it naming another track's clusters: one AV1 remux writes
2191+ // 3928 `CueTrackPositions` for 1174 keyframes.
2192+ CUE_TRACK_POSITIONS => {
2193+ let (mut track, mut pos) = (None, None);
2194+ let mut child = body;
2195+ while let Some((id, body, stop)) = ebml_in(&buf[..stop], child) {
2196+ child = stop;
2197+ match id {
2198+ CUE_TRACK => track = Some(uint_in(&buf, body, stop)),
2199+ CUE_CLUSTER_POSITION => pos = Some(uint_in(&buf, body, stop)),
2200+ _ => {}
2201+ }
2202+ }
2203+ if track == Some(number) {
2204+ cluster = cluster.or(pos);
2205+ }
2206+ }
2207+ _ => {}
2208+ }
2209+ }
2210+ if let (Some(time), Some(cluster)) = (time, cluster) {
2211+ cues.push(Cue {
2212+ time,
2213+ index: (time as f64 / ticks_per_frame).round().max(0.0) as usize,
2214+ cluster: segment.0 + cluster,
2215+ });
2216+ }
2217+ }
2218+ // In index order whatever order the file wrote them in: the seek picks the
2219+ // last cue at or before a frame, which is a statement about a sorted list.
2220+ cues.sort_unstable_by_key(|c| c.index);
2221+ Ok(cues)
2222+}
2223+
2224+/// Body range of the segment's `Cues` element: found among the header elements
2225+/// where a muxer wrote it in front of the clusters (`ffmpeg -cues_to_front`),
2226+/// and through the `SeekHead` where it wrote it at the far end, which is where
2227+/// nearly every file has it. `None` for a file with neither -- a live capture,
2228+/// a stream remuxed without an index -- which is the file that keeps the walk.
2229+fn mkv_cues_element(file: &mut File, segment: (u64, u64)) -> crate::Result<Option<(u64, u64)>> {
2230+ let mut seek = None;
2231+ let mut at = segment.0;
2232+ while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
2233+ at = stop;
2234+ match id {
2235+ CUES => return Ok(Some((body, stop))),
2236+ SEEK_HEAD => seek = seek.or(mkv_seek_position(file, body, stop, CUES)?),
2237+ // Past here the file is clusters, which is what this exists not to
2238+ // read.
2239+ CLUSTER => break,
2240+ _ => {}
2241+ }
2242+ }
2243+ let Some(pos) = seek else {
2244+ return Ok(None);
2245+ };
2246+ // The pointer is believed only as far as the element it lands on: a stale
2247+ // `SeekHead` -- a file edited by a tool that moved the index and left the
2248+ // table behind -- points at something that is not `Cues`, and reading that
2249+ // as one is a seek into the middle of a frame.
2250+ match ebml_element(file, segment.0 + pos, segment.1)? {
2251+ Some((CUES, body, stop)) => Ok(Some((body, stop))),
2252+ _ => Ok(None),
2253+ }
2254+}
2255+
2256+/// Where a `SeekHead` says the element with id `want` is, relative to the start
2257+/// of the segment's payload. Only the one level: a `SeekHead` pointing at
2258+/// another `SeekHead` (what a muxer writes when it appends an index later) is
2259+/// not followed, and that file falls back to the walk rather than to a guess.
2260+fn mkv_seek_position(
2261+ file: &mut File,
2262+ body: u64,
2263+ end: u64,
2264+ want: u32,
2265+) -> crate::Result<Option<u64>> {
2266+ let mut at = body;
2267+ while let Some((id, body, stop)) = ebml_element(file, at, end)? {
2268+ at = stop;
2269+ if id != SEEK {
2270+ continue;
2271+ }
2272+ let (mut found, mut pos) = (None, None);
2273+ let mut child = body;
2274+ while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
2275+ child = stop;
2276+ match id {
2277+ // The id is written as the element's own bytes, marker bit and
2278+ // all -- the same number this file's constants are.
2279+ SEEK_ID => found = Some(ebml_uint(file, body, stop)?),
2280+ SEEK_POSITION => pos = Some(ebml_uint(file, body, stop)?),
2281+ _ => {}
2282+ }
2283+ }
2284+ if found == Some(u64::from(want)) && pos.is_some() {
2285+ return Ok(pos);
2286+ }
2287+ }
2288+ Ok(None)
2289+}
2290+
1791 /// Every block of track `number`, in storage order, with the presentation span2291 /// Every block of track `number`, in storage order, with the presentation span
1792 /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback2292 /// (first and last timestamp in `TimestampScale` ticks) the frame-rate fallback
1793 /// needs -- and, third, how many block bytes *every* track of the file spends,2293 /// needs -- and, third, how many block bytes *every* track of the file spends,
@@ -1820,85 +2320,126 @@ fn mkv_blocks(
1820 if id != CLUSTER {2320 if id != CLUSTER {
1821 continue;2321 continue;
1822 }2322 }
1823- let mut cluster_ts = 0i64;2323+ mkv_cluster(
1824- let mut child = body;2324+ file,
1825- while let Some((id, body, stop)) = ebml_element(file, child, stop)? {2325+ body,
1826- child = stop;2326+ stop,
1827- let (block, key) = match id {2327+ number,
1828- CLUSTER_TIMESTAMP => {2328+ &mut blocks,
1829- cluster_ts = ebml_uint(file, body, stop)? as i64;2329+ &mut track_bytes,
1830- continue;2330+ &mut laced,
1831- }2331+ )?;
1832- SIMPLE_BLOCK => {2332+ }
1833- let block = mkv_block(file, body, stop)?;2333+ mkv_spread_laces(&mut blocks, &laced);
1834- // Bit 7 of the flags is the keyframe bit; a `Block` inside a2334+ let span = blocks
1835- // `BlockGroup` has no such bit, which is the case below.2335+ .iter()
1836- (block, block.flags & 0x80 != 0)2336+ .map(|b| b.ts)
1837- }2337+ .min()
1838- BLOCK_GROUP => {2338+ .zip(blocks.iter().map(|b| b.ts).max());
1839- let (mut found, mut key) = (None, true);2339+ Ok((blocks, span, track_bytes))
1840- let mut child = body;2340+}
1841- while let Some(e) = ebml_element(file, child, stop)? {2341+
1842- match e.0 {2342+/// One `Cluster`'s blocks, appended: those of track `number` to `blocks`, and
1843- BLOCK => found = Some(mkv_block(file, e.1, e.2)?),2343+/// every track's byte count to `track_bytes`. The laces met on the way are
1844- // A block that references another is not one a2344+/// recorded in `laced` for [`mkv_spread_laces`], which the caller runs once its
1845- // decoder can be started from.2345+/// walk is over -- a lace's real span is measured against the block *after* it,
1846- REFERENCE_BLOCK => key = false,2346+/// which the next cluster may hold.
1847- _ => {}2347+///
1848- }2348+/// Split out of [`mkv_blocks`] so the lazy index ([`MkvDemuxer::walk_cluster`])
1849- child = e.2;2349+/// walks a cluster by exactly the code the whole-segment walk does: two readers
1850- }2350+/// of one container that disagreed about what a block is would be two different
1851- match found {2351+/// files to seek in.
1852- Some(block) => (block, key),2352+fn mkv_cluster(
1853- None => continue,2353+ file: &mut File,
1854- }2354+ body: u64,
1855- }2355+ end: u64,
1856- _ => continue,2356+ number: u64,
1857- };2357+ blocks: &mut Vec<Block>,
1858- // Before the track filter, so this counts the whole file: the block2358+ track_bytes: &mut Vec<(u64, u64)>,
1859- // as it sits on disk, lace header included, which is what that track2359+ laced: &mut Vec<(usize, usize)>,
1860- // costs the container. No read is added -- `len` came out of the2360+) -> crate::Result<()> {
1861- // header that was parsed to get here.2361+ let mut cluster_ts = 0i64;
1862- match track_bytes.iter_mut().find(|(n, _)| *n == block.number) {2362+ let mut child = body;
1863- Some((_, bytes)) => *bytes += block.len as u64,2363+ while let Some((id, body, stop)) = ebml_element(file, child, end)? {
1864- None => track_bytes.push((block.number, block.len as u64)),2364+ child = stop;
1865- }2365+ let (block, key) = match id {
1866- if block.number != number {2366+ CLUSTER_TIMESTAMP => {
2367+ cluster_ts = ebml_uint(file, body, stop)? as i64;
1867 continue;2368 continue;
1868 }2369 }
1869- let ts = cluster_ts + i64::from(block.rel);2370+ SIMPLE_BLOCK => {
1870- if block.flags & 0x06 == 0 {2371+ let block = mkv_block(file, body, stop)?;
1871- blocks.push(Block {2372+ // Bit 7 of the flags is the keyframe bit; a `Block` inside a
1872- at: block.at,2373+ // `BlockGroup` has no such bit, which is the case below.
1873- len: block.len,2374+ (block, block.flags & 0x80 != 0)
1874- key,
1875- ts,
1876- });
1877- continue;
1878 }2375 }
1879- // A laced block is several frames behind a header of sizes: one2376+ BLOCK_GROUP => {
1880- // `Block` each, and only the first of them is a point a decoder can2377+ let (mut found, mut key) = (None, true);
1881- // be started from -- the rest are inside the same lace.2378+ let mut child = body;
1882- let start = blocks.len();2379+ while let Some(e) = ebml_element(file, child, stop)? {
1883- for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() {2380+ match e.0 {
1884- blocks.push(Block {2381+ BLOCK => found = Some(mkv_block(file, e.1, e.2)?),
1885- at,2382+ // A block that references another is not one a
1886- len,2383+ // decoder can be started from.
1887- key: key && i == 0,2384+ REFERENCE_BLOCK => key = false,
1888- ts,2385+ _ => {}
1889- });2386+ }
2387+ child = e.2;
2388+ }
2389+ match found {
2390+ Some(block) => (block, key),
2391+ None => continue,
2392+ }
1890 }2393 }
1891- laced.push((start, blocks.len() - start));2394+ _ => continue,
2395+ };
2396+ // Before the track filter, so this counts the whole file: the block
2397+ // as it sits on disk, lace header included, which is what that track
2398+ // costs the container. No read is added -- `len` came out of the
2399+ // header that was parsed to get here.
2400+ match track_bytes.iter_mut().find(|(n, _)| *n == block.number) {
2401+ Some((_, bytes)) => *bytes += block.len as u64,
2402+ None => track_bytes.push((block.number, block.len as u64)),
2403+ }
2404+ if block.number != number {
2405+ continue;
1892 }2406 }
2407+ let ts = cluster_ts + i64::from(block.rel);
2408+ if block.flags & 0x06 == 0 {
2409+ blocks.push(Block {
2410+ at: block.at,
2411+ len: block.len,
2412+ key,
2413+ ts,
2414+ });
2415+ continue;
2416+ }
2417+ // A laced block is several frames behind a header of sizes: one
2418+ // `Block` each, and only the first of them is a point a decoder can
2419+ // be started from -- the rest are inside the same lace.
2420+ let start = blocks.len();
2421+ for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() {
2422+ blocks.push(Block {
2423+ at,
2424+ len,
2425+ key: key && i == 0,
2426+ ts,
2427+ });
2428+ }
2429+ laced.push((start, blocks.len() - start));
1893 }2430 }
1894- // The lace fixup: a laced block writes one timestamp for all its frames, and2431+ Ok(())
1895- // stacking six E-AC-3 frames on one instant is a sound track that drifts a2432+}
1896- // fifth of a second away from the picture inside a cluster. The gap to the2433+
1897- // next block of the same track is what the lace really spans, so the frames2434+/// The lace fixup: a laced block writes one timestamp for all its frames, and
1898- // are spread across it; the last lace of a file has no block after it and2435+/// stacking six E-AC-3 frames on one instant is a sound track that drifts a
1899- // keeps the step the one before it measured.2436+/// fifth of a second away from the picture inside a cluster. The gap to the
2437+/// next block of the same track is what the lace really spans, so the frames
2438+/// are spread across it; the last lace of a walk has no block after it and
2439+/// keeps the step the one before it measured.
2440+fn mkv_spread_laces(blocks: &mut [Block], laced: &[(usize, usize)]) {
1900 let mut step = 0.0;2441 let mut step = 0.0;
1901- for (start, count) in laced {2442+ for &(start, count) in laced {
1902 let first = blocks[start].ts;2443 let first = blocks[start].ts;
1903 if let Some(next) = blocks2444 if let Some(next) = blocks
1904 .get(start + count)2445 .get(start + count)
@@ -1911,12 +2452,6 @@ fn mkv_blocks(
1911 blocks[start + i].ts = first + (i as f64 * step).round() as i64;2452 blocks[start + i].ts = first + (i as f64 * step).round() as i64;
1912 }2453 }
1913 }2454 }
1914- let span = blocks
1915- .iter()
1916- .map(|b| b.ts)
1917- .min()
1918- .zip(blocks.iter().map(|b| b.ts).max());
1919- Ok((blocks, span, track_bytes))
1920 }2455 }
1921 2456
1922 /// The frames inside a laced block: one `(offset, length)` each, in order.2457 /// The frames inside a laced block: one `(offset, length)` each, in order.
@@ -2083,6 +2618,31 @@ fn ebml_vint(buf: &[u8], strip: bool) -> crate::Result<(u64, usize)> {
2083 2618
2084 /// An EBML unsigned integer element: big-endian, as many bytes as it was2619 /// An EBML unsigned integer element: big-endian, as many bytes as it was
2085 /// written with, and an absent one is a zero by the spec's own default.2620 /// written with, and an absent one is a zero by the spec's own default.
2621+/// The EBML element at `at` inside a slice already in memory: its id, where its
2622+/// payload starts and where the element ends. `None` at the end of the slice,
2623+/// and for a header claiming more bytes than the slice holds -- which is how a
2624+/// caller bounds a child to its parent, by handing over the parent's bytes.
2625+///
2626+/// The file-backed [`ebml_element`] costs a `pread` an element, which is right
2627+/// for the handful a header is and wrong for the hundred thousand a film's
2628+/// `Cues` are. Same shapes, same unknown-length rule left out: a `Cues` element
2629+/// of unknown length is one nobody has finished writing.
2630+fn ebml_in(buf: &[u8], at: usize) -> Option<(u32, usize, usize)> {
2631+ let head = buf.get(at..).filter(|h| !h.is_empty())?;
2632+ let (id, id_len) = ebml_vint(head, false).ok()?;
2633+ let (size, size_len) = ebml_vint(head.get(id_len..)?, true).ok()?;
2634+ let body = at + id_len + size_len;
2635+ let stop = body.checked_add(usize::try_from(size).ok()?)?;
2636+ (stop <= buf.len()).then_some((u32::try_from(id).ok()?, body, stop))
2637+}
2638+
2639+/// An unsigned EBML integer out of a slice, big-endian as they all are.
2640+fn uint_in(buf: &[u8], body: usize, stop: usize) -> u64 {
2641+ buf[body..stop]
2642+ .iter()
2643+ .fold(0u64, |acc, &b| (acc << 8) | u64::from(b))
2644+}
2645+
2086 fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {2646 fn ebml_uint(file: &mut File, body: u64, stop: u64) -> crate::Result<u64> {
2087 Ok(ebml_bytes(file, body, stop)?2647 Ok(ebml_bytes(file, body, stop)?
2088 .iter()2648 .iter()
@@ -2802,6 +3362,131 @@ fn string_of(file: &mut File, body: u64, stop: u64) -> crate::Result<String> {
2802 mod tests {3362 mod tests {
2803 use super::*;3363 use super::*;
2804 3364
3365+ fn asset(name: &str) -> std::path::PathBuf {
3366+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
3367+ .join("../../assets")
3368+ .join(name)
3369+ }
3370+
3371+ /// Every Matroska fixture in `assets`, whichever of them holds a picture
3372+ /// this reads: the audio-only and subtitle-only ones refuse to open and are
3373+ /// not the subject here, so they are skipped by name of their own refusal.
3374+ fn matroska_fixtures() -> Vec<std::path::PathBuf> {
3375+ let mut found: Vec<_> = std::fs::read_dir(asset(""))
3376+ .expect("the assets directory -- run scripts/gen_fixtures.sh")
3377+ .filter_map(|e| e.ok().map(|e| e.path()))
3378+ .filter(|p| is_matroska(p))
3379+ .collect();
3380+ found.sort();
3381+ found
3382+ }
3383+
3384+ /// **The lazy index is the same index.** For every Matroska fixture, the
3385+ /// window built off the file's `Cues` and the whole-segment walk it replaced
3386+ /// agree on: the block list, the frame count, and where every one of the
3387+ /// file's frames seeks to.
3388+ ///
3389+ /// This is the claim the `Cues` path rests on -- a seek index read out of
3390+ /// the container is only worth having while it lands on the block the walk
3391+ /// would have landed on -- and it is asserted per frame rather than sampled.
3392+ #[test]
3393+ fn the_cue_index_and_the_whole_walk_are_the_same_index() {
3394+ let (mut cued, mut compared) = (0, 0);
3395+ for path in matroska_fixtures() {
3396+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
3397+ let Ok((meta, mut lazy)) = MkvDemuxer::open(&path) else {
3398+ continue;
3399+ };
3400+ compared += 1;
3401+ cued += usize::from(!lazy.complete);
3402+ // The walk, built beside it out of the same file.
3403+ let mut file = File::open(&path).expect(&name);
3404+ let (walk, _, _) = mkv_blocks(&mut file, lazy.segment, lazy.number).expect(&name);
3405+
3406+ assert_eq!(
3407+ meta.frame_count as usize,
3408+ walk.len(),
3409+ "{name}: the frame count off the cues is not the walk's"
3410+ );
3411+ // The window grown to the whole file is the whole walk, block for
3412+ // block -- offsets, lengths, keyframe flags and timestamps.
3413+ let mut whole = MkvDemuxer::open(&path).expect(&name).1;
3414+ whole.extend_to(usize::MAX).expect(&name);
3415+ assert_eq!(whole.base, 0, "{name}: a sequential read moved the base");
3416+ assert_eq!(whole.blocks, walk, "{name}: the lazy walk is not the walk");
3417+ // ...and every seek lands where the walk's own rule says, jumping
3418+ // backwards and forwards through the cues to get there.
3419+ for frame in (0..walk.len()).chain((0..walk.len()).rev()) {
3420+ let landed = lazy.seek_to_sync_at_or_before(frame as u32);
3421+ let want = walk[..=frame].iter().rposition(|b| b.key).unwrap_or(0);
3422+ assert_eq!(landed, want as i64, "{name}: seek to frame {frame}");
3423+ assert_eq!(
3424+ lazy.blocks[lazy.next - lazy.base],
3425+ walk[want],
3426+ "{name}: the block frame {frame} lands on"
3427+ );
3428+ }
3429+ }
3430+ assert!(compared >= 12, "only {compared} Matroska fixtures opened");
3431+ assert!(
3432+ cued * 2 > compared,
3433+ "only {cued} of {compared} fixtures took the cue path -- the test is \
3434+ asserting the fallback against itself"
3435+ );
3436+ }
3437+
3438+ /// A file with no `Cues` at all -- legal, and what a live capture is -- is
3439+ /// the whole walk it always was, and answers every seek the same way.
3440+ ///
3441+ /// Made by hand rather than by a muxer: neither `ffmpeg` nor `mkvmerge`
3442+ /// writes a Matroska file without an index (ffmpeg's `-cues_to_front` moves
3443+ /// them, it cannot drop them), so the fixture is a real file with the `Cues`
3444+ /// element id and the `SeekHead` pointer at it overwritten by an id nothing
3445+ /// defines. Every byte else is where it was: an EBML reader skips an unknown
3446+ /// element, which is exactly the file that has no index.
3447+ #[test]
3448+ fn a_file_with_no_cues_is_the_walk_it_always_was() {
3449+ let source = asset("test_h264.mkv");
3450+ let mut bytes = std::fs::read(&source).expect("test_h264.mkv");
3451+ let cues = CUES.to_be_bytes();
3452+ // One byte down in the last nibble: still a well-formed 4-byte EBML id,
3453+ // and not one this reader (or the spec) knows.
3454+ let unknown = (CUES - 1).to_be_bytes();
3455+ let mut hidden = 0;
3456+ for at in 0..bytes.len().saturating_sub(4) {
3457+ if bytes[at..at + 4] == cues {
3458+ bytes[at..at + 4].copy_from_slice(&unknown);
3459+ hidden += 1;
3460+ }
3461+ }
3462+ assert!(
3463+ hidden >= 2,
3464+ "the fixture states its Cues neither in a SeekHead nor as an element"
3465+ );
3466+ let path = crate::scratch::Scratch::file("no_cues", "mkv");
3467+ std::fs::write(&path, &bytes).expect("the stripped fixture");
3468+
3469+ let (want, mut walked) = MkvDemuxer::open(&source).expect("the cued file");
3470+ let (got, mut fallback) = MkvDemuxer::open(&path).expect("the file with no cues");
3471+ assert!(
3472+ fallback.complete && fallback.cues.is_empty(),
3473+ "a file with no Cues was not walked whole"
3474+ );
3475+ assert!(
3476+ !walked.complete,
3477+ "the source fixture carries no usable Cues"
3478+ );
3479+ assert_eq!(got.frame_count, want.frame_count, "frame count");
3480+ assert_eq!(got.frame_rate, want.frame_rate, "frame rate");
3481+ for frame in 0..got.frame_count {
3482+ assert_eq!(
3483+ fallback.seek_to_sync_at_or_before(frame),
3484+ walked.seek_to_sync_at_or_before(frame),
3485+ "seek to frame {frame} without cues"
3486+ );
3487+ }
3488+ }
3489+
2805 /// What a `TrackEntry` states it is in, whichever of the two elements it3490 /// What a `TrackEntry` states it is in, whichever of the two elements it
2806 /// states it in -- [`mkv_language`]'s whole rule, as asserts.3491 /// states it in -- [`mkv_language`]'s whole rule, as asserts.
2807 #[test]3492 #[test]