forge
Explore
Log in

Don't you dare go Hollow

A header-stripped or laced Matroska track plays instead of refusing

Browse files at this commit

5d028c29e4d5d55fafbf55451b79f33ce22e6516Ahmet Kaan GümüşParent: 9ebff59
  • feat
    • a header-stripped or laced Matroska track plays instead of refusing
Show full message
✨ feat(demux): a header-stripped or laced Matroska track plays instead of refusing

Two features every disc rip and streaming remux carries and this demuxer had no
reader for:

- `ContentEncodings`: header stripping (`ContentCompAlgo` 3) puts the bytes the
  muxer cut off the front of every frame back, and zlib (algo 0) inflates.
  bzlib, lzo1x, an unknown algorithm and encryption are refused *by name*, and
  per track -- a film whose sound cannot be read still shows its picture, and a
  subtitle track that cannot be read is listed with the reason like a bitmap
  one.
- Lacing: all three headers (Xiph, fixed, EBML) read into one `Block` per
  frame. The frames of a lace get a timestamp each, interpolated across the gap
  to the block after, because six E-AC-3 frames stacked on one instant is a
  sound track that walks away from the picture inside a cluster.

The two films this was cut for: a BluRay remux whose H.264 track is stripped of
one zero byte per block (no picture at all before this), and a WEB remux whose
every E-AC-3 block is fixed-laced (no sound at all before this). Both are
existence-gated tests beside the hand-built EBML fixtures.

zlib is `miniz_oxide`, which `image` already pulls into this build through
`png`: no new crate tree and nothing new to compile.
Cargo.lockmodified+1 -0
@@ -1640,6 +1640,7 @@ dependencies = [
1640 "hound",1640 "hound",
1641 "image",1641 "image",
1642 "libloading",1642 "libloading",
1643+ "miniz_oxide",
1643 "mp4",1644 "mp4",
1644 "oxideav-ac3",1645 "oxideav-ac3",
1645 "oxideav-ass",1646 "oxideav-ass",
crates/engine/Cargo.tomlmodified+6 -0
@@ -22,6 +22,12 @@ image = { version = "0.25", default-features = false, features = [
22 "webp",22 "webp",
23 ] }23 ] }
24 mp4 = "0.14"24 mp4 = "0.14"
25+# zlib, for the one Matroska `ContentEncodings` scheme that is not a byte off
26+# the front of every block: mkvmerge compressed subtitle tracks with it for
27+# years. No new crate tree and nothing new to compile -- `image` above already
28+# pulls this exact version in through `png`, and it is the pure-Rust inflate the
29+# rest of the ecosystem is built on.
30+miniz_oxide = "0.8"
25 rusty_h264 = { version = "0.8", default-features = false }31 rusty_h264 = { version = "0.8", default-features = false }
26 # Both halves of AAC, and the only crate here that is asked for both. The32 # Both halves of AAC, and the only crate here that is asked for both. The
27 # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or33 # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or
crates/engine/src/demux.rsmodified+326 -47
@@ -374,6 +374,9 @@ pub struct MkvDemuxer {
374 /// landing place of its own.374 /// landing place of its own.
375 scratch: Vec<u8>,375 scratch: Vec<u8>,
376 next: usize,376 next: usize,
377+ /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`]
378+ /// for a file that declares none, which is most of them.
379+ unpack: Unpack,
377 }380 }
378 381
379 impl MkvDemuxer {382 impl MkvDemuxer {
@@ -396,6 +399,11 @@ impl MkvDemuxer {
396 .into());399 .into());
397 }400 }
398 };401 };
402+ // A picture nothing here can put back together is a refusal at the door,
403+ // by the name of what the muxer did to it -- not a decode of garbage.
404+ if let Unpack::Refused(why) = &video.unpack {
405+ return Err(why.clone().into());
406+ }
399 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;407 let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?;
400 if blocks.is_empty() {408 if blocks.is_empty() {
401 return Err(format!(409 return Err(format!(
@@ -445,6 +453,7 @@ impl MkvDemuxer {
445 bit_depth: video.bit_depth,453 bit_depth: video.bit_depth,
446 scratch: Vec::new(),454 scratch: Vec::new(),
447 next: 0,455 next: 0,
456+ unpack: video.unpack,
448 },457 },
449 ))458 ))
450 }459 }
@@ -458,16 +467,25 @@ impl MkvDemuxer {
458 };467 };
459 self.next += 1;468 self.next += 1;
460 let head = if block.key { self.config.len() } else { 0 };469 let head = if block.key { self.config.len() } else { 0 };
470+ let Self {
471+ file,
472+ scratch,
473+ unpack,
474+ ..
475+ } = self;
476+ scratch.resize(block.len, 0);
477+ read_exact_at(file, block.at, scratch)?;
478+ // What the muxer stripped or compressed, put back before anything reads
479+ // the bytes as a codec's: a stripped block is not a NAL and an inflated
480+ // one is not where it was read from.
481+ unpack.frame(scratch)?;
461 if self.codec == Codec::Av1 {482 if self.codec == Codec::Av1 {
462- let mut au = vec![0u8; head + block.len];483+ let mut au = Vec::with_capacity(head + self.scratch.len());
463- au[..head].copy_from_slice(&self.config[..head]);484+ au.extend_from_slice(&self.config[..head]);
464- read_exact_at(&mut self.file, block.at, &mut au[head..])?;485+ au.extend_from_slice(&self.scratch);
465 return Ok(Some(au));486 return Ok(Some(au));
466 }487 }
467- let Self { file, scratch, .. } = self;488+ let mut au = Vec::with_capacity(head + self.scratch.len() + 16);
468- scratch.resize(block.len, 0);
469- read_exact_at(file, block.at, scratch)?;
470- let mut au = Vec::with_capacity(head + block.len + 16);
471 au.extend_from_slice(&self.config[..head]);489 au.extend_from_slice(&self.config[..head]);
472 append_annex_b(&self.scratch, self.nal_length, &mut au)?;490 append_annex_b(&self.scratch, self.nal_length, &mut au)?;
473 Ok(Some(au))491 Ok(Some(au))
@@ -497,7 +515,7 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result<Option<String>> {
497 let mut file = File::open(path)?;515 let mut file = File::open(path)?;
498 let end = file.metadata()?.len();516 let end = file.metadata()?.len();
499 let segment = mkv_segment(&mut file, end)?;517 let segment = mkv_segment(&mut file, end)?;
500- Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec))518+ Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec, _)| codec))
501 }519 }
502 520
503 /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio521 /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio
@@ -516,6 +534,8 @@ pub struct MkvAudio {
516 pub codec: &'static str,534 pub codec: &'static str,
517 /// Seconds one `TimestampScale` tick is worth, resolved once at open.535 /// Seconds one `TimestampScale` tick is worth, resolved once at open.
518 secs_per_tick: f64,536 secs_per_tick: f64,
537+ /// As [`MkvDemuxer::unpack`], on the sound track.
538+ unpack: Unpack,
519 }539 }
520 540
521 impl MkvAudio {541 impl MkvAudio {
@@ -528,7 +548,7 @@ impl MkvAudio {
528 let end = file.metadata()?.len();548 let end = file.metadata()?.len();
529 let segment = mkv_segment(&mut file, end)?;549 let segment = mkv_segment(&mut file, end)?;
530 let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?;550 let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?;
531- let Some((number, codec)) = audio else {551+ let Some((number, codec, unpack)) = audio else {
532 return Ok(None);552 return Ok(None);
533 };553 };
534 let codec = match codec.as_str() {554 let codec = match codec.as_str() {
@@ -536,6 +556,12 @@ impl MkvAudio {
536 "A_EAC3" => "eac3",556 "A_EAC3" => "eac3",
537 _ => return Ok(None),557 _ => return Ok(None),
538 };558 };
559+ // Named here rather than at the walk: a sound track this cannot put back
560+ // together is an error for the *audio* session, and the picture of the
561+ // same file still opens.
562+ if let Unpack::Refused(why) = &unpack {
563+ return Err(why.clone().into());
564+ }
539 let (blocks, _) = mkv_blocks(&mut file, segment, number)?;565 let (blocks, _) = mkv_blocks(&mut file, segment, number)?;
540 if blocks.is_empty() {566 if blocks.is_empty() {
541 return Err("the AC-3 track in this Matroska file has no blocks".into());567 return Err("the AC-3 track in this Matroska file has no blocks".into());
@@ -545,11 +571,12 @@ impl MkvAudio {
545 blocks,571 blocks,
546 codec,572 codec,
547 secs_per_tick: timestamp_scale as f64 / 1e9,573 secs_per_tick: timestamp_scale as f64 / 1e9,
574+ unpack,
548 }))575 }))
549 }576 }
550 577
551- /// How many blocks the track has; one syncframe each, lacing being refused578+ /// How many blocks the track has; one syncframe each, a laced block having
552- /// in [`mkv_blocks`].579+ /// been split into one per frame by [`mkv_blocks`].
553 pub fn blocks(&self) -> usize {580 pub fn blocks(&self) -> usize {
554 self.blocks.len()581 self.blocks.len()
555 }582 }
@@ -562,6 +589,7 @@ impl MkvAudio {
562 };589 };
563 let mut bytes = vec![0u8; block.len];590 let mut bytes = vec![0u8; block.len];
564 read_exact_at(&mut self.file, block.at, &mut bytes)?;591 read_exact_at(&mut self.file, block.at, &mut bytes)?;
592+ self.unpack.frame(&mut bytes)?;
565 Ok(Some(bytes))593 Ok(Some(bytes))
566 }594 }
567 595
@@ -596,6 +624,117 @@ struct MkvVideo {
596 config: Vec<u8>,624 config: Vec<u8>,
597 nal_length: usize,625 nal_length: usize,
598 bit_depth: u8,626 bit_depth: u8,
627+ unpack: Unpack,
628+}
629+
630+/// What a track's `ContentEncodings` element did to every one of its frames,
631+/// undone here on the way back out. [`Unpack::None`] is every file this project
632+/// writes and most of what it reads; the rest is what a remuxer does on the way
633+/// to shaving bytes off a disc rip.
634+#[derive(Debug, Clone, Default, PartialEq)]
635+enum Unpack {
636+ #[default]
637+ None,
638+ /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track
639+ /// begins with, cut off by the muxer and written once into
640+ /// `ContentCompSettings`. A decoder handed the rest sees garbage -- one
641+ /// stripped zero byte is the whole difference between a film that plays and
642+ /// a film that does not.
643+ Prepend(Vec<u8>),
644+ /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks
645+ /// with by default for years.
646+ Zlib,
647+ /// A scheme this cannot undo, in the words a caller refuses with. Carried
648+ /// rather than raised where the tracks are walked, so one unreadable *audio*
649+ /// track does not refuse a file whose picture is fine.
650+ Refused(String),
651+}
652+
653+impl Unpack {
654+ /// One frame put back the way the encoder wrote it, in place: a block is a
655+ /// megabyte of keyframe often enough that it is not worth copying whole for
656+ /// the sake of a byte at the front.
657+ fn frame(&self, buf: &mut Vec<u8>) -> crate::Result<()> {
658+ match self {
659+ Self::None => {}
660+ Self::Prepend(head) => drop(buf.splice(..0, head.iter().copied())),
661+ Self::Zlib => {
662+ // With a ceiling on the way out: a frame is a megabyte of
663+ // keyframe at worst, and a crafted block must not be able to
664+ // inflate into all the memory there is.
665+ const LIMIT: usize = 64 << 20;
666+ *buf = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(buf, LIMIT)
667+ .map_err(|e| format!("a zlib Matroska block did not inflate: {e}"))?;
668+ }
669+ Self::Refused(why) => return Err(why.clone().into()),
670+ }
671+ Ok(())
672+ }
673+}
674+
675+/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes
676+/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a
677+/// compressed track read as if it were plain decodes into garbage, and that is
678+/// the one thing this must not do quietly.
679+fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result<Unpack> {
680+ let mut found: Option<Unpack> = None;
681+ let mut at = body;
682+ while let Some((id, body, stop)) = ebml_element(file, at, end)? {
683+ at = stop;
684+ if id != CONTENT_ENCODING {
685+ continue;
686+ }
687+ // Scope 1 -- every frame of the track -- is the default and the only one
688+ // written in practice; the others encode the `CodecPrivate` or the next
689+ // track, and a `CodecPrivate` this cannot read is a track it cannot open
690+ // either way.
691+ let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new());
692+ let mut child = body;
693+ while let Some((id, body, stop)) = ebml_element(file, child, stop)? {
694+ match id {
695+ CONTENT_ENCODING_SCOPE => scope = ebml_uint(file, body, stop)?,
696+ CONTENT_ENCODING_TYPE => kind = ebml_uint(file, body, stop)?,
697+ CONTENT_COMPRESSION => {
698+ let mut child = body;
699+ while let Some(e) = ebml_element(file, child, stop)? {
700+ match e.0 {
701+ CONTENT_COMP_ALGO => algo = Some(ebml_uint(file, e.1, e.2)?),
702+ CONTENT_COMP_SETTINGS => settings = ebml_bytes(file, e.1, e.2)?,
703+ _ => {}
704+ }
705+ child = e.2;
706+ }
707+ }
708+ _ => {}
709+ }
710+ child = stop;
711+ }
712+ let refuse = |what: &str| {
713+ Unpack::Refused(format!(
714+ "{what} in a Matroska file are not supported — this track cannot be read back"
715+ ))
716+ };
717+ let unpack = match (kind, scope, algo.unwrap_or(0)) {
718+ (1, _, _) => refuse("encrypted tracks"),
719+ (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"),
720+ // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are
721+ // named rather than guessed at -- there is no decompressor for
722+ // either here, and nothing has written one in twenty years.
723+ (_, _, 3) => Unpack::Prepend(settings),
724+ (_, _, 0) => Unpack::Zlib,
725+ (_, _, 1) => refuse("bzlib-compressed tracks"),
726+ (_, _, 2) => refuse("lzo1x-compressed tracks"),
727+ (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")),
728+ };
729+ found = Some(match found {
730+ // Chained encodings -- compressed *and* encrypted, say -- are legal
731+ // and written by nothing. Undoing one of the two is worse than
732+ // saying so.
733+ Some(_) => refuse("chained content encodings"),
734+ None => unpack,
735+ });
736+ }
737+ Ok(found.unwrap_or_default())
599 }738 }
600 739
601 // Matroska element IDs, written with the leading length marker they carry in740 // Matroska element IDs, written with the leading length marker they carry in
@@ -613,6 +752,13 @@ const DEFAULT_DURATION: u32 = 0x23E383;
613 const VIDEO: u32 = 0xE0;752 const VIDEO: u32 = 0xE0;
614 const PIXEL_WIDTH: u32 = 0xB0;753 const PIXEL_WIDTH: u32 = 0xB0;
615 const PIXEL_HEIGHT: u32 = 0xBA;754 const PIXEL_HEIGHT: u32 = 0xBA;
755+const CONTENT_ENCODINGS: u32 = 0x6D80;
756+const CONTENT_ENCODING: u32 = 0x6240;
757+const CONTENT_ENCODING_SCOPE: u32 = 0x5032;
758+const CONTENT_ENCODING_TYPE: u32 = 0x5033;
759+const CONTENT_COMPRESSION: u32 = 0x5034;
760+const CONTENT_COMP_ALGO: u32 = 0x4254;
761+const CONTENT_COMP_SETTINGS: u32 = 0x4255;
616 const CLUSTER: u32 = 0x1F43_B675;762 const CLUSTER: u32 = 0x1F43_B675;
617 const CLUSTER_TIMESTAMP: u32 = 0xE7;763 const CLUSTER_TIMESTAMP: u32 = 0xE7;
618 const SIMPLE_BLOCK: u32 = 0xA3;764 const SIMPLE_BLOCK: u32 = 0xA3;
@@ -644,7 +790,12 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> {
644 fn mkv_tracks(790 fn mkv_tracks(
645 file: &mut File,791 file: &mut File,
646 segment: (u64, u64),792 segment: (u64, u64),
647-) -> crate::Result<(Option<MkvVideo>, Option<(u64, String)>, Option<String>, u64)> {793+) -> crate::Result<(
794+ Option<MkvVideo>,
795+ Option<(u64, String, Unpack)>,
796+ Option<String>,
797+ u64,
798+)> {
648 let (mut video, mut audio, mut other) = (None, None, None);799 let (mut video, mut audio, mut other) = (None, None, None);
649 let mut timestamp_scale = 1_000_000;800 let mut timestamp_scale = 1_000_000;
650 let mut at = segment.0;801 let mut at = segment.0;
@@ -667,8 +818,8 @@ fn mkv_tracks(
667 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {818 match mkv_track_entry(file, e.1, e.2, timestamp_scale)? {
668 MkvEntry::Video(track) if video.is_none() => video = Some(track),819 MkvEntry::Video(track) if video.is_none() => video = Some(track),
669 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),820 MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec),
670- MkvEntry::Audio(number, codec) if audio.is_none() => {821+ MkvEntry::Audio(number, codec, unpack) if audio.is_none() => {
671- audio = Some((number, codec))822+ audio = Some((number, codec, unpack))
672 }823 }
673 _ => {}824 _ => {}
674 }825 }
@@ -689,8 +840,9 @@ enum MkvEntry {
689 /// A video track in a codec this does not read, by the name it gives itself.840 /// A video track in a codec this does not read, by the name it gives itself.
690 OtherVideo(String),841 OtherVideo(String),
691 /// An audio track: its track number, which is what [`MkvAudio`] indexes the842 /// An audio track: its track number, which is what [`MkvAudio`] indexes the
692- /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...).843+ /// blocks of, its codec id (`A_AAC`, `A_EAC3`, ...), and what its blocks
693- Audio(u64, String),844+ /// have to be put back through.
845+ Audio(u64, String, Unpack),
694 /// Subtitles, buttons: nobody's here.846 /// Subtitles, buttons: nobody's here.
695 Other,847 Other,
696 }848 }
@@ -704,10 +856,12 @@ fn mkv_track_entry(
704 ) -> crate::Result<MkvEntry> {856 ) -> crate::Result<MkvEntry> {
705 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);857 let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None);
706 let (mut width, mut height, mut config) = (0, 0, Vec::new());858 let (mut width, mut height, mut config) = (0, 0, Vec::new());
859+ let mut unpack = Unpack::None;
707 let mut at = body;860 let mut at = body;
708 while let Some((id, body, stop)) = ebml_element(file, at, end)? {861 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
709 match id {862 match id {
710 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,863 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
864+ CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
711 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,865 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
712 DEFAULT_DURATION => {866 DEFAULT_DURATION => {
713 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)867 default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0)
@@ -752,7 +906,7 @@ fn mkv_track_entry(
752 (Codec::H264, nal_length, sets, 8)906 (Codec::H264, nal_length, sets, 8)
753 }907 }
754 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),908 (1, _) => return Ok(MkvEntry::OtherVideo(codec)),
755- (2, _) => return Ok(MkvEntry::Audio(number, codec)),909+ (2, _) => return Ok(MkvEntry::Audio(number, codec, unpack)),
756 _ => return Ok(MkvEntry::Other),910 _ => return Ok(MkvEntry::Other),
757 };911 };
758 Ok(MkvEntry::Video(MkvVideo {912 Ok(MkvEntry::Video(MkvVideo {
@@ -765,6 +919,7 @@ fn mkv_track_entry(
765 config,919 config,
766 nal_length,920 nal_length,
767 bit_depth,921 bit_depth,
922+ unpack,
768 }))923 }))
769 }924 }
770 925
@@ -856,7 +1011,9 @@ fn mkv_blocks(
856 number: u64,1011 number: u64,
857 ) -> crate::Result<(Vec<Block>, Option<(i64, i64)>)> {1012 ) -> crate::Result<(Vec<Block>, Option<(i64, i64)>)> {
858 let mut blocks = Vec::new();1013 let mut blocks = Vec::new();
859- let mut span: Option<(i64, i64)> = None;1014+ // Where each laced block's frames landed, so their timestamps can be spread
1015+ // once the block after is known -- see the fixup below.
1016+ let mut laced: Vec<(usize, usize)> = Vec::new();
860 let mut at = segment.0;1017 let mut at = segment.0;
861 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {1018 while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? {
862 at = stop;1019 at = stop;
@@ -901,34 +1058,137 @@ fn mkv_blocks(
901 if block.number != number {1058 if block.number != number {
902 continue;1059 continue;
903 }1060 }
904- // Lacing packs several frames into one block, behind a header of
905- // frame sizes this does not read. Video muxers write none; an audio
906- // muxer may, and guessing at frame boundaries inside a laced block
907- // is not something to do silently.
908- //
909- // ponytail: a laced audio track is refused by name rather than
910- // played. The upgrade path is the three lace headers of the spec
911- // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg,
912- // which writes the fixtures and most remuxes, laces nothing.
913- if block.flags & 0x06 != 0 {
914- return Err("laced Matroska blocks are not supported".into());
915- }
916 let ts = cluster_ts + i64::from(block.rel);1061 let ts = cluster_ts + i64::from(block.rel);
917- span = Some(match span {1062+ if block.flags & 0x06 == 0 {
918- Some((first, last)) => (first.min(ts), last.max(ts)),
919- None => (ts, ts),
920- });
921 blocks.push(Block {1063 blocks.push(Block {
922 at: block.at,1064 at: block.at,
923 len: block.len,1065 len: block.len,
924 key,1066 key,
925 ts,1067 ts,
926 });1068 });
1069+ continue;
1070+ }
1071+ // A laced block is several frames behind a header of sizes: one
1072+ // `Block` each, and only the first of them is a point a decoder can
1073+ // be started from -- the rest are inside the same lace.
1074+ let start = blocks.len();
1075+ for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() {
1076+ blocks.push(Block {
1077+ at,
1078+ len,
1079+ key: key && i == 0,
1080+ ts,
1081+ });
1082+ }
1083+ laced.push((start, blocks.len() - start));
1084+ }
1085+ }
1086+ // The lace fixup: a laced block writes one timestamp for all its frames, and
1087+ // stacking six E-AC-3 frames on one instant is a sound track that drifts a
1088+ // fifth of a second away from the picture inside a cluster. The gap to the
1089+ // next block of the same track is what the lace really spans, so the frames
1090+ // are spread across it; the last lace of a file has no block after it and
1091+ // keeps the step the one before it measured.
1092+ let mut step = 0.0;
1093+ for (start, count) in laced {
1094+ let first = blocks[start].ts;
1095+ if let Some(next) = blocks
1096+ .get(start + count)
1097+ .map(|b| b.ts)
1098+ .filter(|&next| next > first)
1099+ {
1100+ step = (next - first) as f64 / count as f64;
927 }1101 }
1102+ for i in 1..count {
1103+ blocks[start + i].ts = first + (i as f64 * step).round() as i64;
928 }1104 }
1105+ }
1106+ let span = blocks
1107+ .iter()
1108+ .map(|b| b.ts)
1109+ .min()
1110+ .zip(blocks.iter().map(|b| b.ts).max());
929 Ok((blocks, span))1111 Ok((blocks, span))
930 }1112 }
931 1113
1114+/// The frames inside a laced block: one `(offset, length)` each, in order.
1115+///
1116+/// Lacing packs several frames -- always whole ones, and only ones nothing else
1117+/// references -- into a single block behind a header of sizes, in one of the
1118+/// three shapes the spec defines. Video muxers write none, but a streaming
1119+/// service's audio is laced by the thousand: every E-AC-3 block of a WEB remux
1120+/// is fixed-laced, and a reader that refuses those is a film that plays silent.
1121+fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result<Vec<(u64, usize)>> {
1122+ // The frame count is one byte and there are at most 256 frames, each size
1123+ // at most 8 bytes of vint (or a run of 0xFF bytes in Xiph, which is bounded
1124+ // by the block itself): the header cannot be longer than this.
1125+ let head_len = (1 + 256 * 9).min(block.len);
1126+ let mut head = vec![0u8; head_len];
1127+ read_exact_at(file, block.at, &mut head)?;
1128+ let count = usize::from(*head.first().ok_or("a laced Matroska block with no frames")?) + 1;
1129+ let short = || crate::Error::from("a Matroska lace header past the end of its block");
1130+ // The cursor into the lace header, which is where the frames start once the
1131+ // sizes have been read.
1132+ let mut at = 1usize;
1133+ let mut sizes = Vec::with_capacity(count);
1134+ match (block.flags >> 1) & 0x03 {
1135+ // Xiph: every size but the last as a run of 255s and a remainder.
1136+ 1 => {
1137+ for _ in 1..count {
1138+ let mut size = 0usize;
1139+ loop {
1140+ let &b = head.get(at).ok_or_else(short)?;
1141+ at += 1;
1142+ size += usize::from(b);
1143+ if b != 255 {
1144+ break;
1145+ }
1146+ }
1147+ sizes.push(size);
1148+ }
1149+ }
1150+ // Fixed: no sizes written at all, the frames divide the rest evenly.
1151+ 2 => {
1152+ let rest = block.len - at;
1153+ if rest % count != 0 {
1154+ return Err("a fixed-lace Matroska block that does not divide evenly".into());
1155+ }
1156+ sizes = vec![rest / count; count - 1];
1157+ }
1158+ // EBML: the first size outright, the rest as differences from the one
1159+ // before -- signed vints, which is the same encoding with the middle of
1160+ // its range taken as zero.
1161+ 3 => {
1162+ let mut size = 0i64;
1163+ for i in 1..count {
1164+ let (raw, len) = ebml_vint(head.get(at..).ok_or_else(short)?, true)?;
1165+ at += len;
1166+ size = match i {
1167+ 1 => raw as i64,
1168+ _ => size + raw as i64 - ((1i64 << (7 * len - 1)) - 1),
1169+ };
1170+ sizes.push(usize::try_from(size).map_err(|_| "a negative Matroska lace size")?);
1171+ }
1172+ }
1173+ // The caller reads the same two bits and only comes here for a lace.
1174+ _ => unreachable!("an unlaced block does not reach the lace reader"),
1175+ }
1176+ let end = block.at + block.len as u64;
1177+ let mut frames = Vec::with_capacity(count);
1178+ let mut off = block.at + at as u64;
1179+ for size in sizes {
1180+ let stop = off.checked_add(size as u64).filter(|&s| s <= end).ok_or(
1181+ "a Matroska lace whose frame sizes run past the end of its block",
1182+ )?;
1183+ frames.push((off, size));
1184+ off = stop;
1185+ }
1186+ // The last frame is whatever is left, which is the only length the fixed and
1187+ // Xiph headers write down for it.
1188+ frames.push((off, (end - off) as usize));
1189+ Ok(frames)
1190+}
1191+
932 /// A `SimpleBlock`/`Block` header: track number, timestamp relative to the1192 /// A `SimpleBlock`/`Block` header: track number, timestamp relative to the
933 /// cluster's, flags, and where the frame's own bytes start.1193 /// cluster's, flags, and where the frame's own bytes start.
934 #[derive(Debug, Clone, Copy)]1194 #[derive(Debug, Clone, Copy)]
@@ -1324,6 +1584,12 @@ pub struct MkvSubtitle {
1324 /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks1584 /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks
1325 /// are megabytes of pictures, and nothing here can draw one.1585 /// are megabytes of pictures, and nothing here can draw one.
1326 pub cues: Vec<MkvCue>,1586 pub cues: Vec<MkvCue>,
1587+ /// Why this track's blocks were not read at all: a `ContentEncodings` this
1588+ /// cannot undo. Listed like a bitmap track rather than raised, so a film
1589+ /// with one encrypted subtitle track still opens with the others.
1590+ pub unsupported: Option<String>,
1591+ /// What every block of this track goes back through; see [`Unpack`].
1592+ unpack: Unpack,
1327 }1593 }
1328 1594
1329 /// One subtitle block: when it shows and the bytes it shows.1595 /// One subtitle block: when it shows and the bytes it shows.
@@ -1383,7 +1649,7 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
1383 // The text tracks only: see `MkvSubtitle::cues`.1649 // The text tracks only: see `MkvSubtitle::cues`.
1384 let wanted: Vec<u64> = tracks1650 let wanted: Vec<u64> = tracks
1385 .iter()1651 .iter()
1386- .filter(|t| t.codec.starts_with("S_TEXT"))1652+ .filter(|t| t.codec.starts_with("S_TEXT") && t.unsupported.is_none())
1387 .map(|t| t.number)1653 .map(|t| t.number)
1388 .collect();1654 .collect();
1389 if !wanted.is_empty() {1655 if !wanted.is_empty() {
@@ -1399,10 +1665,12 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Opt
1399 const SUBTITLE: u64 = 0x11;1665 const SUBTITLE: u64 = 0x11;
1400 let (mut number, mut kind, mut codec) = (0, 0, String::new());1666 let (mut number, mut kind, mut codec) = (0, 0, String::new());
1401 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());1667 let (mut language, mut name, mut private) = (String::new(), String::new(), Vec::new());
1668+ let mut unpack = Unpack::None;
1402 let mut at = body;1669 let mut at = body;
1403 while let Some((id, body, stop)) = ebml_element(file, at, end)? {1670 while let Some((id, body, stop)) = ebml_element(file, at, end)? {
1404 match id {1671 match id {
1405 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,1672 TRACK_NUMBER => number = ebml_uint(file, body, stop)?,
1673+ CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?,
1406 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,1674 TRACK_TYPE => kind = ebml_uint(file, body, stop)?,
1407 CODEC_ID => codec = string_of(file, body, stop)?,1675 CODEC_ID => codec = string_of(file, body, stop)?,
1408 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,1676 CODEC_PRIVATE => private = ebml_bytes(file, body, stop)?,
@@ -1424,6 +1692,11 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result<Opt
1424 name,1692 name,
1425 private,1693 private,
1426 cues: Vec::new(),1694 cues: Vec::new(),
1695+ unsupported: match &unpack {
1696+ Unpack::Refused(why) => Some(why.clone()),
1697+ _ => None,
1698+ },
1699+ unpack,
1427 }))1700 }))
1428 }1701 }
1429 1702
@@ -1480,21 +1753,26 @@ fn mkv_subtitle_blocks(
1480 if !wanted.contains(&block.number) {1753 if !wanted.contains(&block.number) {
1481 continue;1754 continue;
1482 }1755 }
1483- // As for a video block: guessing at the boundaries inside a laced
1484- // one is not something to do silently. No muxer laces subtitles.
1485- if block.flags & 0x06 != 0 {
1486- return Err("laced subtitle blocks are not supported".into());
1487- }
1488- // A megabyte of *text* in one cue is a corrupt file, not a subtitle,
1489- // and a crafted length may not reach an allocation through here.
1490- if block.len > 1 << 20 {
1491- return Err("a Matroska subtitle block larger than a megabyte".into());
1492- }
1493- let mut payload = vec![0u8; block.len];
1494- read_exact_at(file, block.at, &mut payload)?;
1495 let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {1756 let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else {
1496 continue;1757 continue;
1497 };1758 };
1759+ // A laced subtitle block is several cues written at one instant. No
1760+ // muxer writes one, but the header is the same one the sound track's
1761+ // blocks carry ([`mkv_lace`]), so reading it costs nothing here.
1762+ let frames = match block.flags & 0x06 {
1763+ 0 => vec![(block.at, block.len)],
1764+ _ => mkv_lace(file, &block)?,
1765+ };
1766+ for (at, len) in frames {
1767+ // A megabyte of *text* in one cue is a corrupt file, not a
1768+ // subtitle, and a crafted length may not reach an allocation
1769+ // through here.
1770+ if len > 1 << 20 {
1771+ return Err("a Matroska subtitle block larger than a megabyte".into());
1772+ }
1773+ let mut payload = vec![0u8; len];
1774+ read_exact_at(file, at, &mut payload)?;
1775+ track.unpack.frame(&mut payload)?;
1498 track.cues.push(MkvCue {1776 track.cues.push(MkvCue {
1499 start_us: us(cluster_ts + i64::from(block.rel)),1777 start_us: us(cluster_ts + i64::from(block.rel)),
1500 duration_us: duration.map(us),1778 duration_us: duration.map(us),
@@ -1502,6 +1780,7 @@ fn mkv_subtitle_blocks(
1502 });1780 });
1503 }1781 }
1504 }1782 }
1783+ }
1505 Ok(())1784 Ok(())
1506 }1785 }
1507 1786
crates/engine/src/subtitle.rsmodified+5 -0
@@ -157,6 +157,11 @@ pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
157 /// makes an embedded track and the standalone file it was muxed from come back157 /// makes an embedded track and the standalone file it was muxed from come back
158 /// as the same cues.158 /// as the same cues.
159 fn cues_of(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {159 fn cues_of(track: &crate::demux::MkvSubtitle) -> Result<Vec<Cue>, String> {
160+ // A track compressed or encrypted with something the demuxer cannot undo is
161+ // refused in those words, like a bitmap one: the row stays, and it says why.
162+ if let Some(why) = &track.unsupported {
163+ return Err(why.clone());
164+ }
160 let cues = match track.codec.as_str() {165 let cues = match track.codec.as_str() {
161 "S_TEXT/UTF8" | "S_TEXT/ASCII" => track166 "S_TEXT/UTF8" | "S_TEXT/ASCII" => track
162 .cues167 .cues
crates/engine/tests/mkv_encodings.rsadded+457 -0
@@ -0,0 +1,457 @@
1+//! The two Matroska features a disc rip and a streaming remux arrive with and
2+//! this project used to refuse: `ContentEncodings` -- header stripping and zlib
3+//! -- and lacing, which packs several frames into one block.
4+//!
5+//! The fixtures are built here byte by byte rather than by `ffmpeg`: this
6+//! project's own muxer laces nothing and encodes nothing, and ffmpeg writes
7+//! neither by default, so the only way to have a file with a lace header in it
8+//! is to write the header. Every one is a real Matroska file the demuxer walks
9+//! with no special path.
10+//!
11+//! ```text
12+//! cargo test -p engine --test mkv_encodings
13+//! ```
14+
15+use std::path::{Path, PathBuf};
16+
17+use engine::demux::{Codec, Demuxer, MkvAudio};
18+
19+// The element ids this writes, as they are written in the file.
20+const EBML_HEADER: u32 = 0x1A45_DFA3;
21+const SEGMENT: u32 = 0x1853_8067;
22+const INFO: u32 = 0x1549_A966;
23+const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
24+const TRACKS: u32 = 0x1654_AE6B;
25+const TRACK_ENTRY: u32 = 0xAE;
26+const TRACK_NUMBER: u32 = 0xD7;
27+const TRACK_TYPE: u32 = 0x83;
28+const CODEC_ID: u32 = 0x86;
29+const CODEC_PRIVATE: u32 = 0x63A2;
30+const DEFAULT_DURATION: u32 = 0x23E383;
31+const VIDEO: u32 = 0xE0;
32+const PIXEL_WIDTH: u32 = 0xB0;
33+const PIXEL_HEIGHT: u32 = 0xBA;
34+const CONTENT_ENCODINGS: u32 = 0x6D80;
35+const CONTENT_ENCODING: u32 = 0x6240;
36+const CONTENT_ENCODING_TYPE: u32 = 0x5033;
37+const CONTENT_COMPRESSION: u32 = 0x5034;
38+const CONTENT_COMP_ALGO: u32 = 0x4254;
39+const CONTENT_COMP_SETTINGS: u32 = 0x4255;
40+const CLUSTER: u32 = 0x1F43_B675;
41+const CLUSTER_TIMESTAMP: u32 = 0xE7;
42+const SIMPLE_BLOCK: u32 = 0xA3;
43+
44+/// A minimal `avcC`: 4-byte NAL length prefixes, one SPS and one PPS of four
45+/// bytes each. The bytes of the parameter sets are never parsed by the demuxer
46+/// -- it copies them ahead of every keyframe -- so four of each is enough to
47+/// see them arrive.
48+const AVCC: [u8; 19] = [
49+ 1, 0x64, 0, 0x1f, 0xff, 0xe1, 0, 4, 0x67, 0x64, 0, 0x1f, 1, 0, 4, 0x68, 0xee, 0x3c, 0x80,
50+];
51+/// The Annex-B the demuxer must put in front of a keyframe, out of `AVCC`.
52+const SETS: [u8; 16] = [
53+ 0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80,
54+];
55+/// `zlib.compress(b"Hello there")` -- a fixture cannot compress for itself: the
56+/// engine keeps the *in*flate half, which is the half a demuxer needs.
57+const ZLIB_HELLO: [u8; 19] = [
58+ 0x78, 0xda, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xc9, 0x48, 0x2d, 0x4a, 0x05, 0x00, 0x18,
59+ 0x66, 0x04, 0x2d,
60+];
61+
62+/// One EBML element: the id as it is written, then the size in the 8-byte long
63+/// form -- legal everywhere and it keeps this builder arithmetic-free.
64+fn el(id: u32, body: &[u8]) -> Vec<u8> {
65+ let mut out: Vec<u8> = id.to_be_bytes()[(id.leading_zeros() / 8) as usize..].to_vec();
66+ out.push(0x01);
67+ out.extend_from_slice(&(body.len() as u64).to_be_bytes()[1..]);
68+ out.extend_from_slice(body);
69+ out
70+}
71+
72+fn uint(id: u32, value: u64) -> Vec<u8> {
73+ el(id, &value.to_be_bytes())
74+}
75+
76+fn cat(parts: &[Vec<u8>]) -> Vec<u8> {
77+ parts.concat()
78+}
79+
80+/// A `SimpleBlock` of `track`, `rel` ticks into its cluster. `flags` carries the
81+/// keyframe bit (0x80) and the lacing bits (0x06).
82+fn block(track: u8, rel: i16, flags: u8, body: &[u8]) -> Vec<u8> {
83+ let mut b = vec![0x80 | track];
84+ b.extend_from_slice(&rel.to_be_bytes());
85+ b.push(flags);
86+ b.extend_from_slice(body);
87+ el(SIMPLE_BLOCK, &b)
88+}
89+
90+/// A `ContentEncodings` element: the compression algorithm and its settings.
91+fn compression(algo: u64, settings: &[u8]) -> Vec<u8> {
92+ let comp = cat(&[
93+ uint(CONTENT_COMP_ALGO, algo),
94+ el(CONTENT_COMP_SETTINGS, settings),
95+ ]);
96+ el(
97+ CONTENT_ENCODINGS,
98+ &el(CONTENT_ENCODING, &el(CONTENT_COMPRESSION, &comp)),
99+ )
100+}
101+
102+/// A whole file: a header, the segment's `TimestampScale` (a millisecond a
103+/// tick), the tracks and the clusters.
104+fn mkv(tracks: &[Vec<u8>], clusters: &[Vec<u8>]) -> Vec<u8> {
105+ let segment = cat(&[
106+ el(INFO, &uint(TIMESTAMP_SCALE, 1_000_000)),
107+ el(TRACKS, &tracks.concat()),
108+ clusters.concat(),
109+ ]);
110+ cat(&[el(EBML_HEADER, &[]), el(SEGMENT, &segment)])
111+}
112+
113+/// An H.264 track entry, `encoding` being its `ContentEncodings` if it has one.
114+fn video_track(encoding: &[u8]) -> Vec<u8> {
115+ let body = cat(&[
116+ uint(TRACK_NUMBER, 1),
117+ uint(TRACK_TYPE, 1),
118+ el(CODEC_ID, b"V_MPEG4/ISO/AVC"),
119+ el(CODEC_PRIVATE, &AVCC),
120+ uint(DEFAULT_DURATION, 33_333_333),
121+ el(
122+ VIDEO,
123+ &cat(&[uint(PIXEL_WIDTH, 64), uint(PIXEL_HEIGHT, 64)]),
124+ ),
125+ encoding.to_vec(),
126+ ]);
127+ el(TRACK_ENTRY, &body)
128+}
129+
130+/// An AC-3 track entry -- the codec id [`MkvAudio`] reads blocks for. Its blocks
131+/// are never decoded here: what is under test is the walk.
132+fn audio_track(encoding: &[u8]) -> Vec<u8> {
133+ let body = cat(&[
134+ uint(TRACK_NUMBER, 2),
135+ uint(TRACK_TYPE, 2),
136+ el(CODEC_ID, b"A_AC3"),
137+ encoding.to_vec(),
138+ ]);
139+ el(TRACK_ENTRY, &body)
140+}
141+
142+fn subtitle_track(codec: &[u8], encoding: &[u8]) -> Vec<u8> {
143+ let body = cat(&[
144+ uint(TRACK_NUMBER, 3),
145+ uint(TRACK_TYPE, 0x11),
146+ el(CODEC_ID, codec),
147+ encoding.to_vec(),
148+ ]);
149+ el(TRACK_ENTRY, &body)
150+}
151+
152+fn cluster(ts: u64, blocks: &[Vec<u8>]) -> Vec<u8> {
153+ el(
154+ CLUSTER,
155+ &cat(&[uint(CLUSTER_TIMESTAMP, ts), blocks.concat()]),
156+ )
157+}
158+
159+/// The lace header and frames of a Xiph-laced block: every size but the last as
160+/// a run of 255s and a remainder.
161+fn xiph(frames: &[&[u8]]) -> Vec<u8> {
162+ let mut out = vec![(frames.len() - 1) as u8];
163+ for f in &frames[..frames.len() - 1] {
164+ let mut left = f.len();
165+ while left >= 255 {
166+ out.push(255);
167+ left -= 255;
168+ }
169+ out.push(left as u8);
170+ }
171+ out.extend(frames.concat());
172+ out
173+}
174+
175+/// Fixed lacing: the count and nothing else, the frames dividing the rest.
176+fn fixed(frames: &[&[u8]]) -> Vec<u8> {
177+ let mut out = vec![(frames.len() - 1) as u8];
178+ out.extend(frames.concat());
179+ out
180+}
181+
182+/// EBML lacing: the first size as an unsigned vint, the rest as signed
183+/// differences from the one before -- one byte each here, so the bias is 63.
184+fn ebml_lace(frames: &[&[u8]]) -> Vec<u8> {
185+ let mut out = vec![(frames.len() - 1) as u8];
186+ out.push(0x80 | frames[0].len() as u8);
187+ for pair in frames[..frames.len() - 1].windows(2) {
188+ let diff = pair[1].len() as i64 - pair[0].len() as i64;
189+ out.push(0x80 | (diff + 63) as u8);
190+ }
191+ out.extend(frames.concat());
192+ out
193+}
194+
195+/// Under the cargo target directory, never `/tmp`: these are build artefacts.
196+fn write(name: &str, bytes: &[u8]) -> PathBuf {
197+ let path = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name);
198+ std::fs::write(&path, bytes).expect("write the fixture");
199+ path
200+}
201+
202+/// Bug A, in one file: a video track whose every block was written with its
203+/// first byte cut off and that byte filed once in `ContentCompSettings`. Read
204+/// without putting it back, the access unit is a NAL length prefix that lies and
205+/// the decoder shows nothing -- which is exactly how a BluRay remux used to open
206+/// here.
207+#[test]
208+fn header_stripping_puts_the_cut_byte_back_on_every_block() {
209+ // One 4-byte-prefixed NAL per block, the leading zero of the prefix stripped
210+ // off by the muxer.
211+ let key: [u8; 9] = [0, 0, 0, 5, 0x65, 0xAA, 0xBB, 0xCC, 0xDD];
212+ let inter: [u8; 9] = [0, 0, 0, 5, 0x41, 1, 2, 3, 4];
213+ let stripped = mkv(
214+ &[video_track(&compression(3, &[0]))],
215+ &[cluster(
216+ 0,
217+ &[
218+ block(1, 0, 0x80, &key[1..]),
219+ block(1, 1, 0x00, &inter[1..]),
220+ ],
221+ )],
222+ );
223+ let path = write("stripped.mkv", &stripped);
224+ let (meta, mut demuxer) = Demuxer::open(&path).expect("open a header-stripped file");
225+ assert_eq!(meta.codec, Codec::H264);
226+ assert_eq!(meta.frame_count, 2);
227+
228+ let first = demuxer.next_access_unit().expect("read").expect("a unit");
229+ let mut want = SETS.to_vec();
230+ want.extend_from_slice(&[0, 0, 0, 1, 0x65, 0xAA, 0xBB, 0xCC, 0xDD]);
231+ assert_eq!(first, want, "the keyframe is the parameter sets and the NAL");
232+ let second = demuxer.next_access_unit().expect("read").expect("a unit");
233+ assert_eq!(second, [0, 0, 0, 1, 0x41, 1, 2, 3, 4]);
234+ assert!(demuxer.next_access_unit().expect("read").is_none());
235+
236+ // The invariant: the same file with nothing stripped and no encoding
237+ // declared reads back byte for byte the same. Nothing about an ordinary
238+ // Matroska file changed.
239+ let plain = mkv(
240+ &[video_track(&[])],
241+ &[cluster(0, &[block(1, 0, 0x80, &key), block(1, 1, 0x00, &inter)])],
242+ );
243+ let path = write("plain.mkv", &plain);
244+ let (_, mut demuxer) = Demuxer::open(&path).expect("open the plain file");
245+ assert_eq!(demuxer.next_access_unit().expect("read").expect("a"), want);
246+}
247+
248+/// Bug B: every audio block of a WEB remux is laced. All three headers the spec
249+/// defines are read, one `Block` per frame -- and the frames of a lace get a
250+/// timestamp each, interpolated across the gap to the block after, because six
251+/// E-AC-3 frames stacked on one instant is a sound track that walks away from
252+/// the picture.
253+#[test]
254+fn the_three_lace_headers_come_back_one_frame_per_block() {
255+ let three: [&[u8]; 3] = [b"aaa", b"bbbb", b"cc"];
256+ let even: [&[u8]; 3] = [b"aaa", b"bbb", b"ccc"];
257+ for (name, flags, first, second, frames) in [
258+ ("xiph", 0x02, xiph(&three), xiph(&three), three),
259+ ("fixed", 0x04, fixed(&even), fixed(&even), even),
260+ ("ebml", 0x06, ebml_lace(&three), ebml_lace(&three), three),
261+ ] {
262+ let file = mkv(
263+ &[audio_track(&[])],
264+ &[cluster(
265+ 0,
266+ &[
267+ block(2, 0, 0x80 | flags, &first),
268+ block(2, 30, 0x80 | flags, &second),
269+ ],
270+ )],
271+ );
272+ let path = write(&format!("lace_{name}.mkv"), &file);
273+ let mut audio = MkvAudio::open(&path)
274+ .expect("walk the blocks")
275+ .expect("an AC-3 track");
276+ assert_eq!(audio.blocks(), 6, "{name}: two blocks of three frames");
277+ for i in 0..6 {
278+ assert_eq!(
279+ audio.frame(i).expect("read").expect("a frame"),
280+ frames[i % 3],
281+ "{name}: frame {i}"
282+ );
283+ }
284+ // 30 ms of block spread over three frames: 10 ms each, and the last
285+ // lace -- which has no block after it to measure against -- keeps the
286+ // step the one before it measured.
287+ for (i, want) in [0.0, 0.010, 0.020, 0.030, 0.040, 0.050].iter().enumerate() {
288+ assert!(
289+ (audio.secs(i) - want).abs() < 1e-9,
290+ "{name}: frame {i} at {} s, wanted {want}",
291+ audio.secs(i)
292+ );
293+ }
294+ // A seek resolves against those per-frame times, which is the whole
295+ // point of interpolating them: the block at 25 ms is the third frame.
296+ assert_eq!(audio.block_at(0.025, 0), 2, "{name}: seek");
297+ }
298+}
299+
300+/// The two features together, which is the file that has both: a stripped and
301+/// laced audio track. The strip is per *frame*, not per block -- the spec
302+/// compresses the frames of a lace one by one.
303+#[test]
304+fn a_stripped_and_laced_track_gets_both_undone() {
305+ let frames: [&[u8]; 2] = [b"\x77\x01\x02", b"\x77\x03\x04"];
306+ let file = mkv(
307+ &[audio_track(&compression(3, &[0x0B]))],
308+ &[cluster(0, &[block(2, 0, 0x84, &fixed(&frames))])],
309+ );
310+ let path = write("stripped_lace.mkv", &file);
311+ let mut audio = MkvAudio::open(&path)
312+ .expect("walk")
313+ .expect("an AC-3 track");
314+ assert_eq!(audio.blocks(), 2);
315+ assert_eq!(audio.frame(0).unwrap().unwrap(), b"\x0B\x77\x01\x02");
316+ assert_eq!(audio.frame(1).unwrap().unwrap(), b"\x0B\x77\x03\x04");
317+}
318+
319+/// zlib is the other encoding a muxer really writes -- mkvmerge compressed
320+/// subtitle tracks with it by default for years -- and it arrives through the
321+/// user's own subtitle door, as text.
322+#[test]
323+fn a_zlib_subtitle_track_inflates_into_cues() {
324+ let file = mkv(
325+ &[subtitle_track(b"S_TEXT/UTF8", &compression(0, &[]))],
326+ &[cluster(0, &[block(3, 0, 0x80, &ZLIB_HELLO)])],
327+ );
328+ let path = write("zlib_subs.mkv", &file);
329+ let tracks = engine::subtitle::of_matroska(&path).expect("read the tracks");
330+ let track = tracks.first().expect("one subtitle track");
331+ assert_eq!(track.refused, None, "a zlib track is readable");
332+ assert_eq!(track.cues.len(), 1);
333+ assert_eq!(track.cues[0].text, "Hello there");
334+}
335+
336+/// Every encoding this cannot undo is refused *by name* -- the defect these
337+/// share is a file that opens and shows nothing, and a reader that guesses is
338+/// how that happens. Where the refusal lands differs by track: a picture refuses
339+/// the file, a sound track refuses the sound, a subtitle track is listed with
340+/// the reason beside it.
341+#[test]
342+fn what_cannot_be_undone_is_refused_by_name() {
343+ for (algo, word) in [(1u64, "bzlib"), (2, "lzo1x"), (7, "algorithm 7")] {
344+ let file = mkv(
345+ &[video_track(&compression(algo, &[]))],
346+ &[cluster(0, &[block(1, 0, 0x80, &[0, 0, 0, 1, 0x65])])],
347+ );
348+ let path = write(&format!("algo_{algo}.mkv"), &file);
349+ let Err(refused) = Demuxer::open(&path) else {
350+ panic!("a picture compressed with {word} must not open");
351+ };
352+ assert!(
353+ refused.to_string().contains(word),
354+ "the refusal names the algorithm: {refused}"
355+ );
356+ }
357+
358+ // An encrypted sound track: the *sound* refuses, and the picture of the same
359+ // file still opens -- one unreadable track is not a file nobody can play.
360+ let encryption = el(
361+ CONTENT_ENCODINGS,
362+ &el(CONTENT_ENCODING, &uint(CONTENT_ENCODING_TYPE, 1)),
363+ );
364+ let file = mkv(
365+ &[video_track(&[]), audio_track(&encryption)],
366+ &[cluster(0, &[block(1, 0, 0x80, &[0, 0, 0, 1, 0x65])])],
367+ );
368+ let path = write("encrypted_audio.mkv", &file);
369+ let Err(refused) = MkvAudio::open(&path) else {
370+ panic!("an encrypted sound track must not be read as if it were plain");
371+ };
372+ assert!(
373+ refused.to_string().contains("encrypted"),
374+ "the refusal says what it is: {refused}"
375+ );
376+ assert!(Demuxer::open(&path).is_ok(), "the picture still opens");
377+
378+ // And a subtitle track is listed with its reason, like a bitmap one: a film
379+ // with one unreadable track opens with the others.
380+ let file = mkv(
381+ &[subtitle_track(b"S_TEXT/UTF8", &compression(2, &[]))],
382+ &[cluster(0, &[block(3, 0, 0x80, b"never read")])],
383+ );
384+ let path = write("lzo_subs.mkv", &file);
385+ let tracks = engine::subtitle::of_matroska(&path).expect("the file still opens");
386+ let why = tracks[0].refused.as_deref().expect("a refused track");
387+ assert!(why.contains("lzo1x"), "the row says why: {why}");
388+}
389+
390+/// The film this slice was cut for: a BluRay remux whose video track is header
391+/// stripped. Existence-gated -- it is 1.3 GB of somebody's disc and lives on one
392+/// machine -- and it goes through the door the window's import makes, so what it
393+/// proves is a picture on the timeline and not a well-shaped byte string.
394+#[test]
395+fn the_stripped_bluray_remux_decodes_a_picture() {
396+ let path = Path::new(
397+ "/path/to/a-real-h264-dual-audio-film.mkv",
398+ );
399+ if !path.exists() {
400+ eprintln!("skipped: {} is not on this machine", path.display());
401+ return;
402+ }
403+ let mut session = engine::PlaybackSession::open(path).expect("open the remux");
404+ assert_eq!(session.meta().codec, Codec::H264);
405+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
406+ let frame = loop {
407+ if let Some(frame) = session.try_frame() {
408+ break frame;
409+ }
410+ assert!(std::time::Instant::now() < deadline, "no frame in 60 s");
411+ std::thread::sleep(std::time::Duration::from_millis(10));
412+ };
413+ // Garbage NALs decode to nothing at all or to one flat colour; a picture is
414+ // the only thing that fails this.
415+ assert!(
416+ frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]),
417+ "the first frame is a single colour -- the stripped headers were not put back"
418+ );
419+ // And it is not a silent film: the sound of this one is AAC, read by
420+ // symphonia, and the timeline opens both halves or neither.
421+ assert!(
422+ engine::AudioSession::open(path)
423+ .expect("open the sound")
424+ .is_some(),
425+ "the remux has an AAC track"
426+ );
427+}
428+
429+/// The other film: 5.1 E-AC-3 whose every block is fixed-laced. The sound is
430+/// what was missing, so the sound is what is asked for -- through
431+/// `AudioSession`, which is what the timeline opens it with.
432+#[test]
433+fn the_laced_eac3_remux_decodes_sound() {
434+ let path = Path::new(
435+ "/path/to/a-real-4k-hdr10-film.mkv",
436+ );
437+ if !path.exists() {
438+ eprintln!("skipped: {} is not on this machine", path.display());
439+ return;
440+ }
441+ let (meta, rx) = engine::AudioSession::open(path)
442+ .expect("open the sound")
443+ .expect("the film has an E-AC-3 track");
444+ // 5.1 comes down to stereo, as it does off an mp4.
445+ assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
446+ let mut samples = Vec::new();
447+ for chunk in rx {
448+ samples.extend_from_slice(&chunk.samples);
449+ if samples.len() > 48_000 * 2 * 20 {
450+ break;
451+ }
452+ }
453+ // A film opens on silence often enough that the first second says nothing;
454+ // twenty of them do not.
455+ let peak = samples.iter().fold(0f32, |a, s| a.max(s.abs()));
456+ assert!(peak > 0.01, "twenty seconds of silence: peak {peak}");
457+}