forge
Explore
Log in

Don't you dare go Hollow

The SeekHead really points at the Cues, and four track facts a host needs

Browse files at this commit

c2c209e3e51d4c62a55eeca303fb38de54a18219Ahmet Kaan GümüşParent: f26a1d2
  • fix
    • the SeekHead really points at the Cues, and four track facts a host needs
Show full message
fix(matroska): the SeekHead really points at the Cues, and four track facts a host needs

The `SeekHead` stated the `Cues` position twice off the segment: `cues_at` was
already relative and the table subtracted the segment body again, so the pointer
landed in the middle of a cluster. This crate's own demuxer never noticed --
finding no `Cues` there it falls back to the cluster-header walk and reads the
file perfectly -- while symphonia's reader follows the pointer, meets an element
that cannot be there and refuses the file outright. Found by driving an exported
`.mkv` back through symphonia. The remux test now resolves every `SeekHead`
entry and asserts the element it lands on is the one it names.

Four accessors a host cannot do without, all off the `Tracks` element that was
already parsed:

- `track_codec_id` -- the file's own `CodecID` (`A_EAC3`, `S_HDMV/PGS`), which
  says more than the `CodecId` it maps to and is what a copy and a refusal name.
- `track_title` -- `TrackName`, now parsed and now written: `set_track_title`
  puts it back, so a subtitle track called "Signs" survives a remux.
- `track_refusal` / `track_is_plain` -- what a `ContentEncodings` this cannot
  undo did, asked at the header instead of a cluster later, so one unreadable
  subtitle track is listed beside the readable ones rather than failing the file.
- `unread_tracks` -- the `TrackEntry`s this crate hands no stream for, with
  their type: "MPEG-2 video nothing here decodes" is an answer, "no video track"
  is a lie about the same file.

And `set_track_delay`, which writes `CodecDelay` for a track whose encoder delay
only the caller knows: Opus states its own pre-skip in the `OpusHead` and is
unaffected, AAC's is one access unit and nothing in the file says so -- a track
written without it plays ~21 ms early against the picture.
crates/ec-matroska/src/demux.rsmodified+76 -2
@@ -76,6 +76,16 @@ struct Track {
76 /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this76 /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this
77 /// build has no codec id for — its blocks are walked past, not refused.77 /// build has no codec id for — its blocks are walked past, not refused.
78 stream: Option<u32>,78 stream: Option<u32>,
79+ /// The file's own `CodecID` string (`A_EAC3`, `S_HDMV/PGS`), which says
80+ /// more than the [`CodecId`] it maps to: `A_AAC/MPEG4/LC/SBR` and `A_AAC`
81+ /// are one codec and two container declarations.
82+ codec_id: String,
83+ /// `TrackName` — "Japanese 5.1", "Signs" — empty where the file has none.
84+ name: String,
85+ /// What `TrackType` said, for the tracks with no `stream` of their own:
86+ /// "MPEG-2 *video* nothing here decodes" is an answer, "no video track" is
87+ /// not.
88+ media: Option<MediaType>,
79 unpack: Unpack,89 unpack: Unpack,
80 /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by90 /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by
81 /// and what a block with no `BlockDuration` lasts.91 /// and what a block with no `BlockDuration` lasts.
@@ -361,10 +371,69 @@ impl<R: Read + Seek> MatroskaDemuxer<R> {
361 /// file's, and it is what a caller naming one language of a dual-audio371 /// file's, and it is what a caller naming one language of a dual-audio
362 /// remux is holding.372 /// remux is holding.
363 pub fn track_number(&self, stream: u32) -> Option<u64> {373 pub fn track_number(&self, stream: u32) -> Option<u64> {
374+ self.track(stream).map(|t| t.number)
375+ }
376+
377+ /// The file's own `CodecID` for a stream (`A_EAC3`, `S_TEXT/ASS`).
378+ ///
379+ /// [`StreamInfo::params`] names the codec this build decodes it with; this
380+ /// is what the container declared, which is what a remux copies and what a
381+ /// refusal names.
382+ pub fn track_codec_id(&self, stream: u32) -> Option<&str> {
383+ self.track(stream).map(|t| t.codec_id.as_str())
384+ }
385+
386+ /// `TrackName`, the title a muxer wrote beside the language ("Commentary",
387+ /// "Signs"); [`None`] where the track has none.
388+ pub fn track_title(&self, stream: u32) -> Option<&str> {
389+ self.track(stream)
390+ .map(|t| t.name.as_str())
391+ .filter(|n| !n.is_empty())
392+ }
393+
394+ /// Why this track's frames cannot be read back — a `ContentEncodings` this
395+ /// crate cannot undo — in the words a caller refuses with; [`None`] for the
396+ /// tracks it can.
397+ ///
398+ /// The same sentence [`Demuxer::next_packet`] raises when it reaches such a
399+ /// frame. Asked *here*, a caller lists one unreadable subtitle track beside
400+ /// the readable ones instead of discovering it a cluster later.
401+ pub fn track_refusal(&self, stream: u32) -> Option<&str> {
402+ match &self.track(stream)?.unpack {
403+ Unpack::Refused(why) => Some(why),
404+ _ => None,
405+ }
406+ }
407+
408+ /// `(TrackNumber, CodecID, TrackType)` of every `TrackEntry` this crate
409+ /// hands no stream for — a codec it has no id for, walked past rather than
410+ /// refused.
411+ ///
412+ /// What a *caller's* refusal is written from: a file whose only picture is
413+ /// MPEG-2 has a video track, and telling its user it has none is a lie about
414+ /// their file.
415+ pub fn unread_tracks(&self) -> Vec<(u64, &str, Option<MediaType>)> {
364 self.tracks416 self.tracks
365 .iter()417 .iter()
366- .find(|t| t.stream == Some(stream))418+ .filter(|t| t.stream.is_none())
367- .map(|t| t.number)419+ .map(|t| (t.number, t.codec_id.as_str(), t.media))
420+ .collect()
421+ }
422+
423+ /// Whether this track's frames arrive as the encoder wrote them — no
424+ /// `ContentEncodings` over them at all.
425+ ///
426+ /// What a *remux* asks: a stripped or zlib-compressed frame is put back
427+ /// together here, so it decodes, but the bytes handed over are then no
428+ /// longer the ones the source file holds and copying them into another
429+ /// container is not a copy.
430+ pub fn track_is_plain(&self, stream: u32) -> bool {
431+ self.track(stream)
432+ .is_some_and(|t| t.unpack == Unpack::None)
433+ }
434+
435+ fn track(&self, stream: u32) -> Option<&Track> {
436+ self.tracks.iter().find(|t| t.stream == Some(stream))
368 }437 }
369 438
370 /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of439 /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of
@@ -1000,6 +1069,7 @@ fn parse_tracks(
1000 let start = range.start;1069 let start = range.start;
1001 let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new());1070 let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new());
1002 let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None);1071 let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None);
1072+ let mut name = String::new();
1003 let (mut default_duration, mut unpack) = (None, Unpack::None);1073 let (mut default_duration, mut unpack) = (None, Unpack::None);
1004 let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default());1074 let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default());
1005 let mut display = (0u64, 0u64);1075 let mut display = (0u64, 0u64);
@@ -1012,6 +1082,7 @@ fn parse_tracks(
1012 ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]),1082 ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]),
1013 ebml::CODEC_ID => codec = ebml::string_of(&buf[child]),1083 ebml::CODEC_ID => codec = ebml::string_of(&buf[child]),
1014 ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])),1084 ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])),
1085+ ebml::TRACK_NAME => name = ebml::string_of(&buf[child]),
1015 ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]),1086 ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]),
1016 // The spec's own precedence: a modern file states its languages1087 // The spec's own precedence: a modern file states its languages
1017 // in `LanguageBCP47` and leaves the legacy element out.1088 // in `LanguageBCP47` and leaves the legacy element out.
@@ -1121,6 +1192,9 @@ fn parse_tracks(
1121 tracks.push(Track {1192 tracks.push(Track {
1122 number,1193 number,
1123 stream,1194 stream,
1195+ codec_id: codec,
1196+ name,
1197+ media,
1124 unpack,1198 unpack,
1125 default_duration: step,1199 default_duration: step,
1126 });1200 });
crates/ec-matroska/src/ebml.rsmodified+1 -0
@@ -37,6 +37,7 @@ pub const CODEC_PRIVATE: u32 = 0x63A2;
37 pub const CODEC_DELAY: u32 = 0x56AA;37 pub const CODEC_DELAY: u32 = 0x56AA;
38 pub const SEEK_PRE_ROLL: u32 = 0x56BB;38 pub const SEEK_PRE_ROLL: u32 = 0x56BB;
39 pub const DEFAULT_DURATION: u32 = 0x23E383;39 pub const DEFAULT_DURATION: u32 = 0x23E383;
40+pub const TRACK_NAME: u32 = 0x536E;
40 pub const TRACK_LANGUAGE: u32 = 0x22B59C;41 pub const TRACK_LANGUAGE: u32 = 0x22B59C;
41 pub const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;42 pub const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D;
42 43
crates/ec-matroska/src/mux.rsmodified+68 -5
@@ -46,6 +46,10 @@ struct MuxTrack {
46 time_base: TimeBase,46 time_base: TimeBase,
47 /// Nanoseconds a frame lasts, where the stream stated a rate.47 /// Nanoseconds a frame lasts, where the stream stated a rate.
48 frame_ns: Option<u64>,48 frame_ns: Option<u64>,
49+ /// `TrackName`, where a caller named the track.
50+ title: String,
51+ /// `CodecDelay` in nanoseconds, where a caller stated one.
52+ delay_ns: Option<u64>,
49 }53 }
50 54
51 /// One `CuePoint` waiting for [`Muxer::finish`].55 /// One `CuePoint` waiting for [`Muxer::finish`].
@@ -121,6 +125,47 @@ impl<W: Write + Seek> MatroskaMuxer<W> {
121 }125 }
122 }126 }
123 127
128+ /// Names a track: `TrackName`, the title a player's menu shows beside the
129+ /// language ("Signs", "Commentary"). Must be set before the first packet,
130+ /// which is when the `Tracks` element is written.
131+ pub fn set_track_title(&mut self, stream: u32, title: &str) -> Result<()> {
132+ let track = self
133+ .tracks
134+ .get_mut(stream as usize)
135+ .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to name")))?;
136+ if self.pos > 0 {
137+ return Err(Error::corrupt(
138+ "Matroska: a track named after the first packet",
139+ ));
140+ }
141+ track.title = title.to_string();
142+ Ok(())
143+ }
144+
145+ /// States a track's encoder delay: `CodecDelay`, nanoseconds of decoded
146+ /// output a player throws away before the audible stream starts.
147+ ///
148+ /// Opus needs no call — its `OpusHead` states the pre-skip and that is read
149+ /// straight off the extradata. AAC does: its delay is one access unit and
150+ /// nothing in the bitstream or the container says so, so an mp4 reader drops
151+ /// it by convention while Matroska has to be told. A track written without
152+ /// it plays ~21 ms early against the picture.
153+ ///
154+ /// Must be set before the first packet, which is when `Tracks` is written.
155+ pub fn set_track_delay(&mut self, stream: u32, delay_ns: u64) -> Result<()> {
156+ if self.pos > 0 {
157+ return Err(Error::corrupt(
158+ "Matroska: a track delayed after the first packet",
159+ ));
160+ }
161+ let track = self
162+ .tracks
163+ .get_mut(stream as usize)
164+ .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to delay")))?;
165+ track.delay_ns = Some(delay_ns);
166+ Ok(())
167+ }
168+
124 fn write(&mut self, bytes: &[u8]) -> Result<()> {169 fn write(&mut self, bytes: &[u8]) -> Result<()> {
125 self.w.write_all(bytes)?;170 self.w.write_all(bytes)?;
126 self.pos += bytes.len() as u64;171 self.pos += bytes.len() as u64;
@@ -187,14 +232,15 @@ impl<W: Write + Seek> MatroskaMuxer<W> {
187 self.tracks_at = head.len() as u64;232 self.tracks_at = head.len() as u64;
188 let mut tracks = Vec::new();233 let mut tracks = Vec::new();
189 for (i, info) in self.streams.clone().iter().enumerate() {234 for (i, info) in self.streams.clone().iter().enumerate() {
190- let entry = self.track_entry(info, self.tracks[i].number)?;235+ let entry = self.track_entry(info, i)?;
191 elem(&mut tracks, ebml::TRACK_ENTRY, &entry);236 elem(&mut tracks, ebml::TRACK_ENTRY, &entry);
192 }237 }
193 elem(&mut head, ebml::TRACKS, &tracks);238 elem(&mut head, ebml::TRACKS, &tracks);
194 self.write(&head)239 self.write(&head)
195 }240 }
196 241
197- fn track_entry(&self, info: &StreamInfo, number: u64) -> Result<Vec<u8>> {242+ fn track_entry(&self, info: &StreamInfo, track: usize) -> Result<Vec<u8>> {
243+ let number = self.tracks[track].number;
198 let params = &info.params;244 let params = &info.params;
199 let codec = matroska_codec_id(params.codec)?;245 let codec = matroska_codec_id(params.codec)?;
200 if self.webm246 if self.webm
@@ -228,6 +274,13 @@ impl<W: Write + Seek> MatroskaMuxer<W> {
228 {274 {
229 elem(&mut entry, ebml::CODEC_PRIVATE, extradata);275 elem(&mut entry, ebml::CODEC_PRIVATE, extradata);
230 }276 }
277+ if !self.tracks[track].title.is_empty() {
278+ elem(
279+ &mut entry,
280+ ebml::TRACK_NAME,
281+ self.tracks[track].title.as_bytes(),
282+ );
283+ }
231 // A track that states no language is English by spec, so a track whose284 // A track that states no language is English by spec, so a track whose
232 // source said nothing says `und` here rather than claiming a language.285 // source said nothing says `und` here rather than claiming a language.
233 elem(286 elem(
@@ -320,7 +373,11 @@ impl<W: Write + Seek> MatroskaMuxer<W> {
320 // and a track written without it plays 6.5 ms early against the373 // and a track written without it plays 6.5 ms early against the
321 // picture. The pre-roll is the 80 ms the spec asks a seek to374 // picture. The pre-roll is the 80 ms the spec asks a seek to
322 // decode and throw away.375 // decode and throw away.
323- if params.codec == CodecId::Opus376+ // A caller that stated the delay outright is believed first:
377+ // AAC's is one access unit and nothing in the file says so.
378+ if let Some(ns) = self.tracks[track].delay_ns {
379+ uint(&mut entry, ebml::CODEC_DELAY, ns);
380+ } else if params.codec == CodecId::Opus
324 && let Some(head) = &params.extradata381 && let Some(head) = &params.extradata
325 && head.len() >= 12382 && head.len() >= 12
326 && head.starts_with(b"OpusHead")383 && head.starts_with(b"OpusHead")
@@ -456,6 +513,8 @@ impl<W: Write + Seek + Send> Muxer for MatroskaMuxer<W> {
456 media: info.params.codec.media_type(),513 media: info.params.codec.media_type(),
457 time_base: info.time_base,514 time_base: info.time_base,
458 frame_ns,515 frame_ns,
516+ title: String::new(),
517+ delay_ns: None,
459 });518 });
460 let mut info = info;519 let mut info = info;
461 info.index = index;520 info.index = index;
@@ -512,8 +571,12 @@ impl<W: Write + Seek + Send> Muxer for MatroskaMuxer<W> {
512 }571 }
513 self.flush()?;572 self.flush()?;
514 573
515- // The index, in the order a seek reads it.574+ // The index, in the order a seek reads it. Kept as a file offset like
516- let cues_at = self.pos - self.segment_body;575+ // the other two: the `SeekHead` below is what makes them all relative,
576+ // and a position taken off the segment twice points at the middle of a
577+ // cluster — where a reader that follows it finds an element that cannot
578+ // be there and gives up on the file.
579+ let cues_at = self.pos;
517 let mut cues = Vec::new();580 let mut cues = Vec::new();
518 for cue in std::mem::take(&mut self.cues) {581 for cue in std::mem::take(&mut self.cues) {
519 let mut positions = Vec::new();582 let mut positions = Vec::new();
crates/ec-matroska/tests/matroska.rsmodified+79 -0
@@ -200,6 +200,78 @@ fn remux(src: &Path, dst: &Path) -> usize {
200 packets200 packets
201 }201 }
202 202
203+/// Every `SeekHead` entry of `path` resolves to an element of the id it names.
204+///
205+/// `SeekPosition` is stated from the start of the `Segment`'s payload, and a
206+/// position taken off that twice lands inside a cluster: the element id read
207+/// there is whatever byte happened to be at the offset.
208+fn seek_head_points_at_what_it_names(path: &Path) {
209+ let bytes = std::fs::read(path).expect("the written file");
210+ // Element headers, by hand: an id is a variable-length integer with its
211+ // marker bit kept, a size is one with the marker stripped.
212+ let elem = |at: usize| -> (u32, usize, u64) {
213+ let len = (bytes[at].leading_zeros() + 1) as usize;
214+ let id = bytes[at..at + len]
215+ .iter()
216+ .fold(0u32, |acc, &b| (acc << 8) | u32::from(b));
217+ let szn = (bytes[at + len].leading_zeros() + 1) as usize;
218+ let mut size = u64::from(bytes[at + len]) & (0xFFu64 >> szn);
219+ for &b in &bytes[at + len + 1..at + len + szn] {
220+ size = (size << 8) | u64::from(b);
221+ }
222+ (id, at + len + szn, size)
223+ };
224+ let (_, ebml_body, ebml_size) = elem(0);
225+ let segment_at = ebml_body + ebml_size as usize;
226+ let (id, segment_body, _) = elem(segment_at);
227+ assert_eq!(id, 0x1853_8067, "{}: no Segment", path.display());
228+ let (id, head_body, head_size) = elem(segment_body);
229+ assert_eq!(id, 0x114D_9B74, "{}: no SeekHead", path.display());
230+
231+ let mut found = 0;
232+ let mut at = head_body;
233+ while at < head_body + head_size as usize {
234+ let (id, body, size) = elem(at);
235+ at = body + size as usize;
236+ if id != 0x4DBB {
237+ continue;
238+ }
239+ let (mut want, mut pos) = (None, None);
240+ let mut child = body;
241+ while child < at {
242+ let (id, body, size) = elem(child);
243+ child = body + size as usize;
244+ match id {
245+ 0x53AB => {
246+ want = Some(
247+ bytes[body..body + size as usize]
248+ .iter()
249+ .fold(0u32, |acc, &b| (acc << 8) | u32::from(b)),
250+ );
251+ }
252+ 0x53AC => {
253+ pos = Some(
254+ bytes[body..body + size as usize]
255+ .iter()
256+ .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)),
257+ );
258+ }
259+ _ => {}
260+ }
261+ }
262+ let (want, pos) = (want.expect("a SeekID"), pos.expect("a SeekPosition"));
263+ let (id, ..) = elem(segment_body + pos as usize);
264+ assert_eq!(
265+ id,
266+ want,
267+ "{}: SeekHead names {want:#x} at {pos} and finds {id:#x}",
268+ path.display()
269+ );
270+ found += 1;
271+ }
272+ assert!(found >= 3, "{}: {found} SeekHead entries", path.display());
273+}
274+
203 #[test]275 #[test]
204 fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {276 fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
205 let files = matroska_fixtures();277 let files = matroska_fixtures();
@@ -222,6 +294,13 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() {
222 src.display()294 src.display()
223 );295 );
224 296
297+ // ...and the `SeekHead` really names the elements it says it does. A
298+ // demuxer that finds nothing there falls back to a walk and reads the
299+ // file perfectly well, so nothing above this notices — while a stricter
300+ // reader (symphonia's) follows the pointer into the middle of a cluster
301+ // and refuses the file outright. Checked by resolving every entry.
302+ seek_head_points_at_what_it_names(&dst);
303+
225 // ...and it decodes, which is the only claim a field compare cannot make.304 // ...and it decodes, which is the only claim a field compare cannot make.
226 let decode = Command::new("ffmpeg")305 let decode = Command::new("ffmpeg")
227 .args(["-v", "error", "-i"])306 .args(["-v", "error", "-i"])