diff --git a/Cargo.lock b/Cargo.lock index e9357d7..c9e1f02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1640,6 +1640,7 @@ dependencies = [ "hound", "image", "libloading", + "miniz_oxide", "mp4", "oxideav-ac3", "oxideav-ass", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f0f3302..529acd2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -22,6 +22,12 @@ image = { version = "0.25", default-features = false, features = [ "webp", ] } mp4 = "0.14" +# zlib, for the one Matroska `ContentEncodings` scheme that is not a byte off +# the front of every block: mkvmerge compressed subtitle tracks with it for +# years. No new crate tree and nothing new to compile -- `image` above already +# pulls this exact version in through `png`, and it is the pure-Rust inflate the +# rest of the ecosystem is built on. +miniz_oxide = "0.8" rusty_h264 = { version = "0.8", default-features = false } # Both halves of AAC, and the only crate here that is asked for both. The # *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 324c0b0..6b50bc2 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -374,6 +374,9 @@ pub struct MkvDemuxer { /// landing place of its own. scratch: Vec, next: usize, + /// What the track's `ContentEncodings` asks of every block; [`Unpack::None`] + /// for a file that declares none, which is most of them. + unpack: Unpack, } impl MkvDemuxer { @@ -396,6 +399,11 @@ impl MkvDemuxer { .into()); } }; + // A picture nothing here can put back together is a refusal at the door, + // by the name of what the muxer did to it -- not a decode of garbage. + if let Unpack::Refused(why) = &video.unpack { + return Err(why.clone().into()); + } let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; if blocks.is_empty() { return Err(format!( @@ -445,6 +453,7 @@ impl MkvDemuxer { bit_depth: video.bit_depth, scratch: Vec::new(), next: 0, + unpack: video.unpack, }, )) } @@ -458,16 +467,25 @@ impl MkvDemuxer { }; self.next += 1; let head = if block.key { self.config.len() } else { 0 }; + let Self { + file, + scratch, + unpack, + .. + } = self; + scratch.resize(block.len, 0); + read_exact_at(file, block.at, scratch)?; + // What the muxer stripped or compressed, put back before anything reads + // the bytes as a codec's: a stripped block is not a NAL and an inflated + // one is not where it was read from. + unpack.frame(scratch)?; if self.codec == Codec::Av1 { - let mut au = vec![0u8; head + block.len]; - au[..head].copy_from_slice(&self.config[..head]); - read_exact_at(&mut self.file, block.at, &mut au[head..])?; + let mut au = Vec::with_capacity(head + self.scratch.len()); + au.extend_from_slice(&self.config[..head]); + au.extend_from_slice(&self.scratch); return Ok(Some(au)); } - let Self { file, scratch, .. } = self; - scratch.resize(block.len, 0); - read_exact_at(file, block.at, scratch)?; - let mut au = Vec::with_capacity(head + block.len + 16); + let mut au = Vec::with_capacity(head + self.scratch.len() + 16); au.extend_from_slice(&self.config[..head]); append_annex_b(&self.scratch, self.nal_length, &mut au)?; Ok(Some(au)) @@ -497,7 +515,7 @@ pub fn matroska_audio_codec(path: &Path) -> crate::Result> { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec)| codec)) + Ok(mkv_tracks(&mut file, segment)?.1.map(|(_, codec, _)| codec)) } /// The AC-3 / E-AC-3 sound of a Matroska file: every block of its first audio @@ -516,6 +534,8 @@ pub struct MkvAudio { pub codec: &'static str, /// Seconds one `TimestampScale` tick is worth, resolved once at open. secs_per_tick: f64, + /// As [`MkvDemuxer::unpack`], on the sound track. + unpack: Unpack, } impl MkvAudio { @@ -528,7 +548,7 @@ impl MkvAudio { let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; - let Some((number, codec)) = audio else { + let Some((number, codec, unpack)) = audio else { return Ok(None); }; let codec = match codec.as_str() { @@ -536,6 +556,12 @@ impl MkvAudio { "A_EAC3" => "eac3", _ => return Ok(None), }; + // Named here rather than at the walk: a sound track this cannot put back + // together is an error for the *audio* session, and the picture of the + // same file still opens. + if let Unpack::Refused(why) = &unpack { + return Err(why.clone().into()); + } let (blocks, _) = mkv_blocks(&mut file, segment, number)?; if blocks.is_empty() { return Err("the AC-3 track in this Matroska file has no blocks".into()); @@ -545,11 +571,12 @@ impl MkvAudio { blocks, codec, secs_per_tick: timestamp_scale as f64 / 1e9, + unpack, })) } - /// How many blocks the track has; one syncframe each, lacing being refused - /// in [`mkv_blocks`]. + /// How many blocks the track has; one syncframe each, a laced block having + /// been split into one per frame by [`mkv_blocks`]. pub fn blocks(&self) -> usize { self.blocks.len() } @@ -562,6 +589,7 @@ impl MkvAudio { }; let mut bytes = vec![0u8; block.len]; read_exact_at(&mut self.file, block.at, &mut bytes)?; + self.unpack.frame(&mut bytes)?; Ok(Some(bytes)) } @@ -596,6 +624,117 @@ struct MkvVideo { config: Vec, nal_length: usize, bit_depth: u8, + unpack: Unpack, +} + +/// What a track's `ContentEncodings` element did to every one of its frames, +/// undone here on the way back out. [`Unpack::None`] is every file this project +/// writes and most of what it reads; the rest is what a remuxer does on the way +/// to shaving bytes off a disc rip. +#[derive(Debug, Clone, Default, PartialEq)] +enum Unpack { + #[default] + None, + /// Header stripping (`ContentCompAlgo` 3): bytes every frame of the track + /// begins with, cut off by the muxer and written once into + /// `ContentCompSettings`. A decoder handed the rest sees garbage -- one + /// stripped zero byte is the whole difference between a film that plays and + /// a film that does not. + Prepend(Vec), + /// zlib (`ContentCompAlgo` 0), which mkvmerge compressed subtitle tracks + /// with by default for years. + Zlib, + /// A scheme this cannot undo, in the words a caller refuses with. Carried + /// rather than raised where the tracks are walked, so one unreadable *audio* + /// track does not refuse a file whose picture is fine. + Refused(String), +} + +impl Unpack { + /// One frame put back the way the encoder wrote it, in place: a block is a + /// megabyte of keyframe often enough that it is not worth copying whole for + /// the sake of a byte at the front. + fn frame(&self, buf: &mut Vec) -> crate::Result<()> { + match self { + Self::None => {} + Self::Prepend(head) => drop(buf.splice(..0, head.iter().copied())), + Self::Zlib => { + // With a ceiling on the way out: a frame is a megabyte of + // keyframe at worst, and a crafted block must not be able to + // inflate into all the memory there is. + const LIMIT: usize = 64 << 20; + *buf = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(buf, LIMIT) + .map_err(|e| format!("a zlib Matroska block did not inflate: {e}"))?; + } + Self::Refused(why) => return Err(why.clone().into()), + } + Ok(()) + } +} + +/// The `ContentEncodings` of one `TrackEntry`. Anything this cannot undo comes +/// back as [`Unpack::Refused`] with the sentence naming the feature it wanted: a +/// compressed track read as if it were plain decodes into garbage, and that is +/// the one thing this must not do quietly. +fn mkv_content_encoding(file: &mut File, body: u64, end: u64) -> crate::Result { + let mut found: Option = None; + let mut at = body; + while let Some((id, body, stop)) = ebml_element(file, at, end)? { + at = stop; + if id != CONTENT_ENCODING { + continue; + } + // Scope 1 -- every frame of the track -- is the default and the only one + // written in practice; the others encode the `CodecPrivate` or the next + // track, and a `CodecPrivate` this cannot read is a track it cannot open + // either way. + let (mut scope, mut kind, mut algo, mut settings) = (1, 0, None, Vec::new()); + let mut child = body; + while let Some((id, body, stop)) = ebml_element(file, child, stop)? { + match id { + CONTENT_ENCODING_SCOPE => scope = ebml_uint(file, body, stop)?, + CONTENT_ENCODING_TYPE => kind = ebml_uint(file, body, stop)?, + CONTENT_COMPRESSION => { + let mut child = body; + while let Some(e) = ebml_element(file, child, stop)? { + match e.0 { + CONTENT_COMP_ALGO => algo = Some(ebml_uint(file, e.1, e.2)?), + CONTENT_COMP_SETTINGS => settings = ebml_bytes(file, e.1, e.2)?, + _ => {} + } + child = e.2; + } + } + _ => {} + } + child = stop; + } + let refuse = |what: &str| { + Unpack::Refused(format!( + "{what} in a Matroska file are not supported — this track cannot be read back" + )) + }; + let unpack = match (kind, scope, algo.unwrap_or(0)) { + (1, _, _) => refuse("encrypted tracks"), + (_, s, _) if s & 1 == 0 => refuse("tracks whose headers are the compressed part"), + // 3 is header stripping and 0 is zlib; 1 (bzlib) and 2 (lzo1x) are + // named rather than guessed at -- there is no decompressor for + // either here, and nothing has written one in twenty years. + (_, _, 3) => Unpack::Prepend(settings), + (_, _, 0) => Unpack::Zlib, + (_, _, 1) => refuse("bzlib-compressed tracks"), + (_, _, 2) => refuse("lzo1x-compressed tracks"), + (_, _, algo) => refuse(&format!("tracks compressed with algorithm {algo}")), + }; + found = Some(match found { + // Chained encodings -- compressed *and* encrypted, say -- are legal + // and written by nothing. Undoing one of the two is worse than + // saying so. + Some(_) => refuse("chained content encodings"), + None => unpack, + }); + } + Ok(found.unwrap_or_default()) } // Matroska element IDs, written with the leading length marker they carry in @@ -613,6 +752,13 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +const CONTENT_ENCODINGS: u32 = 0x6D80; +const CONTENT_ENCODING: u32 = 0x6240; +const CONTENT_ENCODING_SCOPE: u32 = 0x5032; +const CONTENT_ENCODING_TYPE: u32 = 0x5033; +const CONTENT_COMPRESSION: u32 = 0x5034; +const CONTENT_COMP_ALGO: u32 = 0x4254; +const CONTENT_COMP_SETTINGS: u32 = 0x4255; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; @@ -644,7 +790,12 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { fn mkv_tracks( file: &mut File, segment: (u64, u64), -) -> crate::Result<(Option, Option<(u64, String)>, Option, u64)> { +) -> crate::Result<( + Option, + Option<(u64, String, Unpack)>, + Option, + u64, +)> { let (mut video, mut audio, mut other) = (None, None, None); let mut timestamp_scale = 1_000_000; let mut at = segment.0; @@ -667,8 +818,8 @@ fn mkv_tracks( match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { MkvEntry::Video(track) if video.is_none() => video = Some(track), MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), - MkvEntry::Audio(number, codec) if audio.is_none() => { - audio = Some((number, codec)) + MkvEntry::Audio(number, codec, unpack) if audio.is_none() => { + audio = Some((number, codec, unpack)) } _ => {} } @@ -689,8 +840,9 @@ enum MkvEntry { /// A video track in a codec this does not read, by the name it gives itself. OtherVideo(String), /// An audio track: its track number, which is what [`MkvAudio`] indexes the - /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). - Audio(u64, String), + /// blocks of, its codec id (`A_AAC`, `A_EAC3`, ...), and what its blocks + /// have to be put back through. + Audio(u64, String, Unpack), /// Subtitles, buttons: nobody's here. Other, } @@ -704,10 +856,12 @@ fn mkv_track_entry( ) -> crate::Result { let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); let (mut width, mut height, mut config) = (0, 0, Vec::new()); + let mut unpack = Unpack::None; let mut at = body; while let Some((id, body, stop)) = ebml_element(file, at, end)? { match id { TRACK_NUMBER => number = ebml_uint(file, body, stop)?, + CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, TRACK_TYPE => kind = ebml_uint(file, body, stop)?, DEFAULT_DURATION => { default_duration = Some(ebml_uint(file, body, stop)?).filter(|d| *d > 0) @@ -752,7 +906,7 @@ fn mkv_track_entry( (Codec::H264, nal_length, sets, 8) } (1, _) => return Ok(MkvEntry::OtherVideo(codec)), - (2, _) => return Ok(MkvEntry::Audio(number, codec)), + (2, _) => return Ok(MkvEntry::Audio(number, codec, unpack)), _ => return Ok(MkvEntry::Other), }; Ok(MkvEntry::Video(MkvVideo { @@ -765,6 +919,7 @@ fn mkv_track_entry( config, nal_length, bit_depth, + unpack, })) } @@ -856,7 +1011,9 @@ fn mkv_blocks( number: u64, ) -> crate::Result<(Vec, Option<(i64, i64)>)> { let mut blocks = Vec::new(); - let mut span: Option<(i64, i64)> = None; + // Where each laced block's frames landed, so their timestamps can be spread + // once the block after is known -- see the fixup below. + let mut laced: Vec<(usize, usize)> = Vec::new(); let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { at = stop; @@ -901,34 +1058,137 @@ fn mkv_blocks( if block.number != number { continue; } - // Lacing packs several frames into one block, behind a header of - // frame sizes this does not read. Video muxers write none; an audio - // muxer may, and guessing at frame boundaries inside a laced block - // is not something to do silently. - // - // ponytail: a laced audio track is refused by name rather than - // played. The upgrade path is the three lace headers of the spec - // (Xiph, fixed, EBML) read here into one `Block` per frame; ffmpeg, - // which writes the fixtures and most remuxes, laces nothing. - if block.flags & 0x06 != 0 { - return Err("laced Matroska blocks are not supported".into()); - } let ts = cluster_ts + i64::from(block.rel); - span = Some(match span { - Some((first, last)) => (first.min(ts), last.max(ts)), - None => (ts, ts), - }); - blocks.push(Block { - at: block.at, - len: block.len, - key, - ts, - }); + if block.flags & 0x06 == 0 { + blocks.push(Block { + at: block.at, + len: block.len, + key, + ts, + }); + continue; + } + // A laced block is several frames behind a header of sizes: one + // `Block` each, and only the first of them is a point a decoder can + // be started from -- the rest are inside the same lace. + let start = blocks.len(); + for (i, (at, len)) in mkv_lace(file, &block)?.into_iter().enumerate() { + blocks.push(Block { + at, + len, + key: key && i == 0, + ts, + }); + } + laced.push((start, blocks.len() - start)); } } + // The lace fixup: a laced block writes one timestamp for all its frames, and + // stacking six E-AC-3 frames on one instant is a sound track that drifts a + // fifth of a second away from the picture inside a cluster. The gap to the + // next block of the same track is what the lace really spans, so the frames + // are spread across it; the last lace of a file has no block after it and + // keeps the step the one before it measured. + let mut step = 0.0; + for (start, count) in laced { + let first = blocks[start].ts; + if let Some(next) = blocks + .get(start + count) + .map(|b| b.ts) + .filter(|&next| next > first) + { + step = (next - first) as f64 / count as f64; + } + for i in 1..count { + blocks[start + i].ts = first + (i as f64 * step).round() as i64; + } + } + let span = blocks + .iter() + .map(|b| b.ts) + .min() + .zip(blocks.iter().map(|b| b.ts).max()); Ok((blocks, span)) } +/// The frames inside a laced block: one `(offset, length)` each, in order. +/// +/// Lacing packs several frames -- always whole ones, and only ones nothing else +/// references -- into a single block behind a header of sizes, in one of the +/// three shapes the spec defines. Video muxers write none, but a streaming +/// service's audio is laced by the thousand: every E-AC-3 block of a WEB remux +/// is fixed-laced, and a reader that refuses those is a film that plays silent. +fn mkv_lace(file: &mut File, block: &BlockHeader) -> crate::Result> { + // The frame count is one byte and there are at most 256 frames, each size + // at most 8 bytes of vint (or a run of 0xFF bytes in Xiph, which is bounded + // by the block itself): the header cannot be longer than this. + let head_len = (1 + 256 * 9).min(block.len); + let mut head = vec![0u8; head_len]; + read_exact_at(file, block.at, &mut head)?; + let count = usize::from(*head.first().ok_or("a laced Matroska block with no frames")?) + 1; + let short = || crate::Error::from("a Matroska lace header past the end of its block"); + // The cursor into the lace header, which is where the frames start once the + // sizes have been read. + let mut at = 1usize; + let mut sizes = Vec::with_capacity(count); + match (block.flags >> 1) & 0x03 { + // Xiph: every size but the last as a run of 255s and a remainder. + 1 => { + for _ in 1..count { + let mut size = 0usize; + loop { + let &b = head.get(at).ok_or_else(short)?; + at += 1; + size += usize::from(b); + if b != 255 { + break; + } + } + sizes.push(size); + } + } + // Fixed: no sizes written at all, the frames divide the rest evenly. + 2 => { + let rest = block.len - at; + if rest % count != 0 { + return Err("a fixed-lace Matroska block that does not divide evenly".into()); + } + sizes = vec![rest / count; count - 1]; + } + // EBML: the first size outright, the rest as differences from the one + // before -- signed vints, which is the same encoding with the middle of + // its range taken as zero. + 3 => { + let mut size = 0i64; + for i in 1..count { + let (raw, len) = ebml_vint(head.get(at..).ok_or_else(short)?, true)?; + at += len; + size = match i { + 1 => raw as i64, + _ => size + raw as i64 - ((1i64 << (7 * len - 1)) - 1), + }; + sizes.push(usize::try_from(size).map_err(|_| "a negative Matroska lace size")?); + } + } + // The caller reads the same two bits and only comes here for a lace. + _ => unreachable!("an unlaced block does not reach the lace reader"), + } + let end = block.at + block.len as u64; + let mut frames = Vec::with_capacity(count); + let mut off = block.at + at as u64; + for size in sizes { + let stop = off.checked_add(size as u64).filter(|&s| s <= end).ok_or( + "a Matroska lace whose frame sizes run past the end of its block", + )?; + frames.push((off, size)); + off = stop; + } + // The last frame is whatever is left, which is the only length the fixed and + // Xiph headers write down for it. + frames.push((off, (end - off) as usize)); + Ok(frames) +} + /// A `SimpleBlock`/`Block` header: track number, timestamp relative to the /// cluster's, flags, and where the frame's own bytes start. #[derive(Debug, Clone, Copy)] @@ -1324,6 +1584,12 @@ pub struct MkvSubtitle { /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks /// are megabytes of pictures, and nothing here can draw one. pub cues: Vec, + /// Why this track's blocks were not read at all: a `ContentEncodings` this + /// cannot undo. Listed like a bitmap track rather than raised, so a film + /// with one encrypted subtitle track still opens with the others. + pub unsupported: Option, + /// What every block of this track goes back through; see [`Unpack`]. + unpack: Unpack, } /// One subtitle block: when it shows and the bytes it shows. @@ -1383,7 +1649,7 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result> { // The text tracks only: see `MkvSubtitle::cues`. let wanted: Vec = tracks .iter() - .filter(|t| t.codec.starts_with("S_TEXT")) + .filter(|t| t.codec.starts_with("S_TEXT") && t.unsupported.is_none()) .map(|t| t.number) .collect(); if !wanted.is_empty() { @@ -1399,10 +1665,12 @@ fn mkv_subtitle_entry(file: &mut File, body: u64, end: u64) -> crate::Result number = ebml_uint(file, body, stop)?, + CONTENT_ENCODINGS => unpack = mkv_content_encoding(file, body, stop)?, TRACK_TYPE => kind = ebml_uint(file, body, stop)?, CODEC_ID => codec = string_of(file, body, stop)?, 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 Some(why.clone()), + _ => None, + }, + unpack, })) } @@ -1480,26 +1753,32 @@ fn mkv_subtitle_blocks( if !wanted.contains(&block.number) { continue; } - // As for a video block: guessing at the boundaries inside a laced - // one is not something to do silently. No muxer laces subtitles. - if block.flags & 0x06 != 0 { - return Err("laced subtitle blocks are not supported".into()); - } - // A megabyte of *text* in one cue is a corrupt file, not a subtitle, - // and a crafted length may not reach an allocation through here. - if block.len > 1 << 20 { - return Err("a Matroska subtitle block larger than a megabyte".into()); - } - let mut payload = vec![0u8; block.len]; - read_exact_at(file, block.at, &mut payload)?; let Some(track) = tracks.iter_mut().find(|t| t.number == block.number) else { continue; }; - track.cues.push(MkvCue { - start_us: us(cluster_ts + i64::from(block.rel)), - duration_us: duration.map(us), - payload, - }); + // A laced subtitle block is several cues written at one instant. No + // muxer writes one, but the header is the same one the sound track's + // blocks carry ([`mkv_lace`]), so reading it costs nothing here. + let frames = match block.flags & 0x06 { + 0 => vec![(block.at, block.len)], + _ => mkv_lace(file, &block)?, + }; + for (at, len) in frames { + // A megabyte of *text* in one cue is a corrupt file, not a + // subtitle, and a crafted length may not reach an allocation + // through here. + if len > 1 << 20 { + return Err("a Matroska subtitle block larger than a megabyte".into()); + } + let mut payload = vec![0u8; len]; + read_exact_at(file, at, &mut payload)?; + track.unpack.frame(&mut payload)?; + track.cues.push(MkvCue { + start_us: us(cluster_ts + i64::from(block.rel)), + duration_us: duration.map(us), + payload, + }); + } } } Ok(()) diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index 27d1f20..9cc49eb 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -157,6 +157,11 @@ pub fn of_matroska(path: &Path) -> crate::Result> { /// makes an embedded track and the standalone file it was muxed from come back /// as the same cues. fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { + // A track compressed or encrypted with something the demuxer cannot undo is + // refused in those words, like a bitmap one: the row stays, and it says why. + if let Some(why) = &track.unsupported { + return Err(why.clone()); + } let cues = match track.codec.as_str() { "S_TEXT/UTF8" | "S_TEXT/ASCII" => track .cues diff --git a/crates/engine/tests/mkv_encodings.rs b/crates/engine/tests/mkv_encodings.rs new file mode 100644 index 0000000..3e8cbf9 --- /dev/null +++ b/crates/engine/tests/mkv_encodings.rs @@ -0,0 +1,457 @@ +//! The two Matroska features a disc rip and a streaming remux arrive with and +//! this project used to refuse: `ContentEncodings` -- header stripping and zlib +//! -- and lacing, which packs several frames into one block. +//! +//! The fixtures are built here byte by byte rather than by `ffmpeg`: this +//! project's own muxer laces nothing and encodes nothing, and ffmpeg writes +//! neither by default, so the only way to have a file with a lace header in it +//! is to write the header. Every one is a real Matroska file the demuxer walks +//! with no special path. +//! +//! ```text +//! cargo test -p engine --test mkv_encodings +//! ``` + +use std::path::{Path, PathBuf}; + +use engine::demux::{Codec, Demuxer, MkvAudio}; + +// The element ids this writes, as they are written in the file. +const EBML_HEADER: u32 = 0x1A45_DFA3; +const SEGMENT: u32 = 0x1853_8067; +const INFO: u32 = 0x1549_A966; +const TIMESTAMP_SCALE: u32 = 0x2AD7B1; +const TRACKS: u32 = 0x1654_AE6B; +const TRACK_ENTRY: u32 = 0xAE; +const TRACK_NUMBER: u32 = 0xD7; +const TRACK_TYPE: u32 = 0x83; +const CODEC_ID: u32 = 0x86; +const CODEC_PRIVATE: u32 = 0x63A2; +const DEFAULT_DURATION: u32 = 0x23E383; +const VIDEO: u32 = 0xE0; +const PIXEL_WIDTH: u32 = 0xB0; +const PIXEL_HEIGHT: u32 = 0xBA; +const CONTENT_ENCODINGS: u32 = 0x6D80; +const CONTENT_ENCODING: u32 = 0x6240; +const CONTENT_ENCODING_TYPE: u32 = 0x5033; +const CONTENT_COMPRESSION: u32 = 0x5034; +const CONTENT_COMP_ALGO: u32 = 0x4254; +const CONTENT_COMP_SETTINGS: u32 = 0x4255; +const CLUSTER: u32 = 0x1F43_B675; +const CLUSTER_TIMESTAMP: u32 = 0xE7; +const SIMPLE_BLOCK: u32 = 0xA3; + +/// A minimal `avcC`: 4-byte NAL length prefixes, one SPS and one PPS of four +/// bytes each. The bytes of the parameter sets are never parsed by the demuxer +/// -- it copies them ahead of every keyframe -- so four of each is enough to +/// see them arrive. +const AVCC: [u8; 19] = [ + 1, 0x64, 0, 0x1f, 0xff, 0xe1, 0, 4, 0x67, 0x64, 0, 0x1f, 1, 0, 4, 0x68, 0xee, 0x3c, 0x80, +]; +/// The Annex-B the demuxer must put in front of a keyframe, out of `AVCC`. +const SETS: [u8; 16] = [ + 0, 0, 0, 1, 0x67, 0x64, 0, 0x1f, 0, 0, 0, 1, 0x68, 0xee, 0x3c, 0x80, +]; +/// `zlib.compress(b"Hello there")` -- a fixture cannot compress for itself: the +/// engine keeps the *in*flate half, which is the half a demuxer needs. +const ZLIB_HELLO: [u8; 19] = [ + 0x78, 0xda, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xc9, 0x48, 0x2d, 0x4a, 0x05, 0x00, 0x18, + 0x66, 0x04, 0x2d, +]; + +/// One EBML element: the id as it is written, then the size in the 8-byte long +/// form -- legal everywhere and it keeps this builder arithmetic-free. +fn el(id: u32, body: &[u8]) -> Vec { + let mut out: Vec = id.to_be_bytes()[(id.leading_zeros() / 8) as usize..].to_vec(); + out.push(0x01); + out.extend_from_slice(&(body.len() as u64).to_be_bytes()[1..]); + out.extend_from_slice(body); + out +} + +fn uint(id: u32, value: u64) -> Vec { + el(id, &value.to_be_bytes()) +} + +fn cat(parts: &[Vec]) -> Vec { + parts.concat() +} + +/// A `SimpleBlock` of `track`, `rel` ticks into its cluster. `flags` carries the +/// keyframe bit (0x80) and the lacing bits (0x06). +fn block(track: u8, rel: i16, flags: u8, body: &[u8]) -> Vec { + let mut b = vec![0x80 | track]; + b.extend_from_slice(&rel.to_be_bytes()); + b.push(flags); + b.extend_from_slice(body); + el(SIMPLE_BLOCK, &b) +} + +/// A `ContentEncodings` element: the compression algorithm and its settings. +fn compression(algo: u64, settings: &[u8]) -> Vec { + let comp = cat(&[ + uint(CONTENT_COMP_ALGO, algo), + el(CONTENT_COMP_SETTINGS, settings), + ]); + el( + CONTENT_ENCODINGS, + &el(CONTENT_ENCODING, &el(CONTENT_COMPRESSION, &comp)), + ) +} + +/// A whole file: a header, the segment's `TimestampScale` (a millisecond a +/// tick), the tracks and the clusters. +fn mkv(tracks: &[Vec], clusters: &[Vec]) -> Vec { + let segment = cat(&[ + el(INFO, &uint(TIMESTAMP_SCALE, 1_000_000)), + el(TRACKS, &tracks.concat()), + clusters.concat(), + ]); + cat(&[el(EBML_HEADER, &[]), el(SEGMENT, &segment)]) +} + +/// An H.264 track entry, `encoding` being its `ContentEncodings` if it has one. +fn video_track(encoding: &[u8]) -> Vec { + let body = cat(&[ + uint(TRACK_NUMBER, 1), + uint(TRACK_TYPE, 1), + el(CODEC_ID, b"V_MPEG4/ISO/AVC"), + el(CODEC_PRIVATE, &AVCC), + uint(DEFAULT_DURATION, 33_333_333), + el( + VIDEO, + &cat(&[uint(PIXEL_WIDTH, 64), uint(PIXEL_HEIGHT, 64)]), + ), + encoding.to_vec(), + ]); + el(TRACK_ENTRY, &body) +} + +/// An AC-3 track entry -- the codec id [`MkvAudio`] reads blocks for. Its blocks +/// are never decoded here: what is under test is the walk. +fn audio_track(encoding: &[u8]) -> Vec { + let body = cat(&[ + uint(TRACK_NUMBER, 2), + uint(TRACK_TYPE, 2), + el(CODEC_ID, b"A_AC3"), + encoding.to_vec(), + ]); + el(TRACK_ENTRY, &body) +} + +fn subtitle_track(codec: &[u8], encoding: &[u8]) -> Vec { + let body = cat(&[ + uint(TRACK_NUMBER, 3), + uint(TRACK_TYPE, 0x11), + el(CODEC_ID, codec), + encoding.to_vec(), + ]); + el(TRACK_ENTRY, &body) +} + +fn cluster(ts: u64, blocks: &[Vec]) -> Vec { + el( + CLUSTER, + &cat(&[uint(CLUSTER_TIMESTAMP, ts), blocks.concat()]), + ) +} + +/// The lace header and frames of a Xiph-laced block: every size but the last as +/// a run of 255s and a remainder. +fn xiph(frames: &[&[u8]]) -> Vec { + let mut out = vec![(frames.len() - 1) as u8]; + for f in &frames[..frames.len() - 1] { + let mut left = f.len(); + while left >= 255 { + out.push(255); + left -= 255; + } + out.push(left as u8); + } + out.extend(frames.concat()); + out +} + +/// Fixed lacing: the count and nothing else, the frames dividing the rest. +fn fixed(frames: &[&[u8]]) -> Vec { + let mut out = vec![(frames.len() - 1) as u8]; + out.extend(frames.concat()); + out +} + +/// EBML lacing: the first size as an unsigned vint, the rest as signed +/// differences from the one before -- one byte each here, so the bias is 63. +fn ebml_lace(frames: &[&[u8]]) -> Vec { + let mut out = vec![(frames.len() - 1) as u8]; + out.push(0x80 | frames[0].len() as u8); + for pair in frames[..frames.len() - 1].windows(2) { + let diff = pair[1].len() as i64 - pair[0].len() as i64; + out.push(0x80 | (diff + 63) as u8); + } + out.extend(frames.concat()); + out +} + +/// Under the cargo target directory, never `/tmp`: these are build artefacts. +fn write(name: &str, bytes: &[u8]) -> PathBuf { + let path = Path::new(env!("CARGO_TARGET_TMPDIR")).join(name); + std::fs::write(&path, bytes).expect("write the fixture"); + path +} + +/// Bug A, in one file: a video track whose every block was written with its +/// first byte cut off and that byte filed once in `ContentCompSettings`. Read +/// without putting it back, the access unit is a NAL length prefix that lies and +/// the decoder shows nothing -- which is exactly how a BluRay remux used to open +/// here. +#[test] +fn header_stripping_puts_the_cut_byte_back_on_every_block() { + // One 4-byte-prefixed NAL per block, the leading zero of the prefix stripped + // off by the muxer. + let key: [u8; 9] = [0, 0, 0, 5, 0x65, 0xAA, 0xBB, 0xCC, 0xDD]; + let inter: [u8; 9] = [0, 0, 0, 5, 0x41, 1, 2, 3, 4]; + let stripped = mkv( + &[video_track(&compression(3, &[0]))], + &[cluster( + 0, + &[ + block(1, 0, 0x80, &key[1..]), + block(1, 1, 0x00, &inter[1..]), + ], + )], + ); + let path = write("stripped.mkv", &stripped); + let (meta, mut demuxer) = Demuxer::open(&path).expect("open a header-stripped file"); + assert_eq!(meta.codec, Codec::H264); + assert_eq!(meta.frame_count, 2); + + let first = demuxer.next_access_unit().expect("read").expect("a unit"); + let mut want = SETS.to_vec(); + want.extend_from_slice(&[0, 0, 0, 1, 0x65, 0xAA, 0xBB, 0xCC, 0xDD]); + assert_eq!(first, want, "the keyframe is the parameter sets and the NAL"); + let second = demuxer.next_access_unit().expect("read").expect("a unit"); + assert_eq!(second, [0, 0, 0, 1, 0x41, 1, 2, 3, 4]); + assert!(demuxer.next_access_unit().expect("read").is_none()); + + // The invariant: the same file with nothing stripped and no encoding + // declared reads back byte for byte the same. Nothing about an ordinary + // Matroska file changed. + let plain = mkv( + &[video_track(&[])], + &[cluster(0, &[block(1, 0, 0x80, &key), block(1, 1, 0x00, &inter)])], + ); + let path = write("plain.mkv", &plain); + let (_, mut demuxer) = Demuxer::open(&path).expect("open the plain file"); + assert_eq!(demuxer.next_access_unit().expect("read").expect("a"), want); +} + +/// Bug B: every audio block of a WEB remux is laced. All three headers the spec +/// defines are read, one `Block` per frame -- and 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. +#[test] +fn the_three_lace_headers_come_back_one_frame_per_block() { + let three: [&[u8]; 3] = [b"aaa", b"bbbb", b"cc"]; + let even: [&[u8]; 3] = [b"aaa", b"bbb", b"ccc"]; + for (name, flags, first, second, frames) in [ + ("xiph", 0x02, xiph(&three), xiph(&three), three), + ("fixed", 0x04, fixed(&even), fixed(&even), even), + ("ebml", 0x06, ebml_lace(&three), ebml_lace(&three), three), + ] { + let file = mkv( + &[audio_track(&[])], + &[cluster( + 0, + &[ + block(2, 0, 0x80 | flags, &first), + block(2, 30, 0x80 | flags, &second), + ], + )], + ); + let path = write(&format!("lace_{name}.mkv"), &file); + let mut audio = MkvAudio::open(&path) + .expect("walk the blocks") + .expect("an AC-3 track"); + assert_eq!(audio.blocks(), 6, "{name}: two blocks of three frames"); + for i in 0..6 { + assert_eq!( + audio.frame(i).expect("read").expect("a frame"), + frames[i % 3], + "{name}: frame {i}" + ); + } + // 30 ms of block spread over three frames: 10 ms each, and the last + // lace -- which has no block after it to measure against -- keeps the + // step the one before it measured. + for (i, want) in [0.0, 0.010, 0.020, 0.030, 0.040, 0.050].iter().enumerate() { + assert!( + (audio.secs(i) - want).abs() < 1e-9, + "{name}: frame {i} at {} s, wanted {want}", + audio.secs(i) + ); + } + // A seek resolves against those per-frame times, which is the whole + // point of interpolating them: the block at 25 ms is the third frame. + assert_eq!(audio.block_at(0.025, 0), 2, "{name}: seek"); + } +} + +/// The two features together, which is the file that has both: a stripped and +/// laced audio track. The strip is per *frame*, not per block -- the spec +/// compresses the frames of a lace one by one. +#[test] +fn a_stripped_and_laced_track_gets_both_undone() { + let frames: [&[u8]; 2] = [b"\x77\x01\x02", b"\x77\x03\x04"]; + let file = mkv( + &[audio_track(&compression(3, &[0x0B]))], + &[cluster(0, &[block(2, 0, 0x84, &fixed(&frames))])], + ); + let path = write("stripped_lace.mkv", &file); + let mut audio = MkvAudio::open(&path) + .expect("walk") + .expect("an AC-3 track"); + assert_eq!(audio.blocks(), 2); + assert_eq!(audio.frame(0).unwrap().unwrap(), b"\x0B\x77\x01\x02"); + assert_eq!(audio.frame(1).unwrap().unwrap(), b"\x0B\x77\x03\x04"); +} + +/// zlib is the other encoding a muxer really writes -- mkvmerge compressed +/// subtitle tracks with it by default for years -- and it arrives through the +/// user's own subtitle door, as text. +#[test] +fn a_zlib_subtitle_track_inflates_into_cues() { + let file = mkv( + &[subtitle_track(b"S_TEXT/UTF8", &compression(0, &[]))], + &[cluster(0, &[block(3, 0, 0x80, &ZLIB_HELLO)])], + ); + let path = write("zlib_subs.mkv", &file); + let tracks = engine::subtitle::of_matroska(&path).expect("read the tracks"); + let track = tracks.first().expect("one subtitle track"); + assert_eq!(track.refused, None, "a zlib track is readable"); + assert_eq!(track.cues.len(), 1); + assert_eq!(track.cues[0].text, "Hello there"); +} + +/// Every encoding this cannot undo is refused *by name* -- the defect these +/// share is a file that opens and shows nothing, and a reader that guesses is +/// how that happens. Where the refusal lands differs by track: a picture refuses +/// the file, a sound track refuses the sound, a subtitle track is listed with +/// the reason beside it. +#[test] +fn what_cannot_be_undone_is_refused_by_name() { + for (algo, word) in [(1u64, "bzlib"), (2, "lzo1x"), (7, "algorithm 7")] { + let file = mkv( + &[video_track(&compression(algo, &[]))], + &[cluster(0, &[block(1, 0, 0x80, &[0, 0, 0, 1, 0x65])])], + ); + let path = write(&format!("algo_{algo}.mkv"), &file); + let Err(refused) = Demuxer::open(&path) else { + panic!("a picture compressed with {word} must not open"); + }; + assert!( + refused.to_string().contains(word), + "the refusal names the algorithm: {refused}" + ); + } + + // An encrypted sound track: the *sound* refuses, and the picture of the same + // file still opens -- one unreadable track is not a file nobody can play. + let encryption = el( + CONTENT_ENCODINGS, + &el(CONTENT_ENCODING, &uint(CONTENT_ENCODING_TYPE, 1)), + ); + let file = mkv( + &[video_track(&[]), audio_track(&encryption)], + &[cluster(0, &[block(1, 0, 0x80, &[0, 0, 0, 1, 0x65])])], + ); + let path = write("encrypted_audio.mkv", &file); + let Err(refused) = MkvAudio::open(&path) else { + panic!("an encrypted sound track must not be read as if it were plain"); + }; + assert!( + refused.to_string().contains("encrypted"), + "the refusal says what it is: {refused}" + ); + assert!(Demuxer::open(&path).is_ok(), "the picture still opens"); + + // And a subtitle track is listed with its reason, like a bitmap one: a film + // with one unreadable track opens with the others. + let file = mkv( + &[subtitle_track(b"S_TEXT/UTF8", &compression(2, &[]))], + &[cluster(0, &[block(3, 0, 0x80, b"never read")])], + ); + let path = write("lzo_subs.mkv", &file); + let tracks = engine::subtitle::of_matroska(&path).expect("the file still opens"); + let why = tracks[0].refused.as_deref().expect("a refused track"); + assert!(why.contains("lzo1x"), "the row says why: {why}"); +} + +/// The film this slice was cut for: a BluRay remux whose video track is header +/// stripped. Existence-gated -- it is 1.3 GB of somebody's disc and lives on one +/// machine -- and it goes through the door the window's import makes, so what it +/// proves is a picture on the timeline and not a well-shaped byte string. +#[test] +fn the_stripped_bluray_remux_decodes_a_picture() { + let path = Path::new( + "/path/to/a-real-h264-dual-audio-film.mkv", + ); + if !path.exists() { + eprintln!("skipped: {} is not on this machine", path.display()); + return; + } + let mut session = engine::PlaybackSession::open(path).expect("open the remux"); + assert_eq!(session.meta().codec, Codec::H264); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(std::time::Instant::now() < deadline, "no frame in 60 s"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + // Garbage NALs decode to nothing at all or to one flat colour; a picture is + // the only thing that fails this. + assert!( + frame.bgra.chunks_exact(4).any(|px| px != &frame.bgra[..4]), + "the first frame is a single colour -- the stripped headers were not put back" + ); + // And it is not a silent film: the sound of this one is AAC, read by + // symphonia, and the timeline opens both halves or neither. + assert!( + engine::AudioSession::open(path) + .expect("open the sound") + .is_some(), + "the remux has an AAC track" + ); +} + +/// The other film: 5.1 E-AC-3 whose every block is fixed-laced. The sound is +/// what was missing, so the sound is what is asked for -- through +/// `AudioSession`, which is what the timeline opens it with. +#[test] +fn the_laced_eac3_remux_decodes_sound() { + let path = Path::new( + "/path/to/a-real-4k-hdr10-film.mkv", + ); + if !path.exists() { + eprintln!("skipped: {} is not on this machine", path.display()); + return; + } + let (meta, rx) = engine::AudioSession::open(path) + .expect("open the sound") + .expect("the film has an E-AC-3 track"); + // 5.1 comes down to stereo, as it does off an mp4. + assert_eq!((meta.sample_rate, meta.channels), (48_000, 2)); + let mut samples = Vec::new(); + for chunk in rx { + samples.extend_from_slice(&chunk.samples); + if samples.len() > 48_000 * 2 * 20 { + break; + } + } + // A film opens on silence often enough that the first second says nothing; + // twenty of them do not. + let peak = samples.iter().fold(0f32, |a, s| a.max(s.abs())); + assert!(peak > 0.01, "twenty seconds of silence: peak {peak}"); +}