diff --git a/crates/ec-matroska/src/demux.rs b/crates/ec-matroska/src/demux.rs index 1ce082ec..b7421bba 100644 --- a/crates/ec-matroska/src/demux.rs +++ b/crates/ec-matroska/src/demux.rs @@ -76,6 +76,16 @@ struct Track { /// Index in [`MatroskaDemuxer::streams`], or [`None`] for a track this /// build has no codec id for — its blocks are walked past, not refused. stream: Option, + /// The file's own `CodecID` string (`A_EAC3`, `S_HDMV/PGS`), which says + /// more than the [`CodecId`] it maps to: `A_AAC/MPEG4/LC/SBR` and `A_AAC` + /// are one codec and two container declarations. + codec_id: String, + /// `TrackName` — "Japanese 5.1", "Signs" — empty where the file has none. + name: String, + /// What `TrackType` said, for the tracks with no `stream` of their own: + /// "MPEG-2 *video* nothing here decodes" is an answer, "no video track" is + /// not. + media: Option, unpack: Unpack, /// `DefaultDuration` in timestamp-scale ticks: what a laced frame steps by /// and what a block with no `BlockDuration` lasts. @@ -361,10 +371,69 @@ impl MatroskaDemuxer { /// file's, and it is what a caller naming one language of a dual-audio /// remux is holding. pub fn track_number(&self, stream: u32) -> Option { + self.track(stream).map(|t| t.number) + } + + /// The file's own `CodecID` for a stream (`A_EAC3`, `S_TEXT/ASS`). + /// + /// [`StreamInfo::params`] names the codec this build decodes it with; this + /// is what the container declared, which is what a remux copies and what a + /// refusal names. + pub fn track_codec_id(&self, stream: u32) -> Option<&str> { + self.track(stream).map(|t| t.codec_id.as_str()) + } + + /// `TrackName`, the title a muxer wrote beside the language ("Commentary", + /// "Signs"); [`None`] where the track has none. + pub fn track_title(&self, stream: u32) -> Option<&str> { + self.track(stream) + .map(|t| t.name.as_str()) + .filter(|n| !n.is_empty()) + } + + /// Why this track's frames cannot be read back — a `ContentEncodings` this + /// crate cannot undo — in the words a caller refuses with; [`None`] for the + /// tracks it can. + /// + /// The same sentence [`Demuxer::next_packet`] raises when it reaches such a + /// frame. Asked *here*, a caller lists one unreadable subtitle track beside + /// the readable ones instead of discovering it a cluster later. + pub fn track_refusal(&self, stream: u32) -> Option<&str> { + match &self.track(stream)?.unpack { + Unpack::Refused(why) => Some(why), + _ => None, + } + } + + /// `(TrackNumber, CodecID, TrackType)` of every `TrackEntry` this crate + /// hands no stream for — a codec it has no id for, walked past rather than + /// refused. + /// + /// What a *caller's* refusal is written from: a file whose only picture is + /// MPEG-2 has a video track, and telling its user it has none is a lie about + /// their file. + pub fn unread_tracks(&self) -> Vec<(u64, &str, Option)> { self.tracks .iter() - .find(|t| t.stream == Some(stream)) - .map(|t| t.number) + .filter(|t| t.stream.is_none()) + .map(|t| (t.number, t.codec_id.as_str(), t.media)) + .collect() + } + + /// Whether this track's frames arrive as the encoder wrote them — no + /// `ContentEncodings` over them at all. + /// + /// What a *remux* asks: a stripped or zlib-compressed frame is put back + /// together here, so it decodes, but the bytes handed over are then no + /// longer the ones the source file holds and copying them into another + /// container is not a copy. + pub fn track_is_plain(&self, stream: u32) -> bool { + self.track(stream) + .is_some_and(|t| t.unpack == Unpack::None) + } + + fn track(&self, stream: u32) -> Option<&Track> { + self.tracks.iter().find(|t| t.stream == Some(stream)) } /// The next cluster into [`MatroskaDemuxer::queue`]; `false` at the end of @@ -1000,6 +1069,7 @@ fn parse_tracks( let start = range.start; let (mut number, mut kind, mut codec) = (0u64, 0u64, String::new()); let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None); + let mut name = String::new(); let (mut default_duration, mut unpack) = (None, Unpack::None); let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default()); let mut display = (0u64, 0u64); @@ -1012,6 +1082,7 @@ fn parse_tracks( ebml::TRACK_TYPE => kind = ebml::uint_of(&buf[child]), ebml::CODEC_ID => codec = ebml::string_of(&buf[child]), ebml::CODEC_PRIVATE => private = Some(Buf::copy_from_slice(&buf[child])), + ebml::TRACK_NAME => name = ebml::string_of(&buf[child]), ebml::TRACK_LANGUAGE => language = ebml::string_of(&buf[child]), // The spec's own precedence: a modern file states its languages // in `LanguageBCP47` and leaves the legacy element out. @@ -1121,6 +1192,9 @@ fn parse_tracks( tracks.push(Track { number, stream, + codec_id: codec, + name, + media, unpack, default_duration: step, }); diff --git a/crates/ec-matroska/src/ebml.rs b/crates/ec-matroska/src/ebml.rs index c09f1fba..c95460f0 100644 --- a/crates/ec-matroska/src/ebml.rs +++ b/crates/ec-matroska/src/ebml.rs @@ -37,6 +37,7 @@ pub const CODEC_PRIVATE: u32 = 0x63A2; pub const CODEC_DELAY: u32 = 0x56AA; pub const SEEK_PRE_ROLL: u32 = 0x56BB; pub const DEFAULT_DURATION: u32 = 0x23E383; +pub const TRACK_NAME: u32 = 0x536E; pub const TRACK_LANGUAGE: u32 = 0x22B59C; pub const TRACK_LANGUAGE_BCP47: u32 = 0x22B59D; diff --git a/crates/ec-matroska/src/mux.rs b/crates/ec-matroska/src/mux.rs index cd87f837..966fbbc0 100644 --- a/crates/ec-matroska/src/mux.rs +++ b/crates/ec-matroska/src/mux.rs @@ -46,6 +46,10 @@ struct MuxTrack { time_base: TimeBase, /// Nanoseconds a frame lasts, where the stream stated a rate. frame_ns: Option, + /// `TrackName`, where a caller named the track. + title: String, + /// `CodecDelay` in nanoseconds, where a caller stated one. + delay_ns: Option, } /// One `CuePoint` waiting for [`Muxer::finish`]. @@ -121,6 +125,47 @@ impl MatroskaMuxer { } } + /// Names a track: `TrackName`, the title a player's menu shows beside the + /// language ("Signs", "Commentary"). Must be set before the first packet, + /// which is when the `Tracks` element is written. + pub fn set_track_title(&mut self, stream: u32, title: &str) -> Result<()> { + let track = self + .tracks + .get_mut(stream as usize) + .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to name")))?; + if self.pos > 0 { + return Err(Error::corrupt( + "Matroska: a track named after the first packet", + )); + } + track.title = title.to_string(); + Ok(()) + } + + /// States a track's encoder delay: `CodecDelay`, nanoseconds of decoded + /// output a player throws away before the audible stream starts. + /// + /// Opus needs no call — its `OpusHead` states the pre-skip and that is read + /// straight off the extradata. AAC does: its delay is one access unit and + /// nothing in the bitstream or the container says so, so an mp4 reader drops + /// it by convention while Matroska has to be told. A track written without + /// it plays ~21 ms early against the picture. + /// + /// Must be set before the first packet, which is when `Tracks` is written. + pub fn set_track_delay(&mut self, stream: u32, delay_ns: u64) -> Result<()> { + if self.pos > 0 { + return Err(Error::corrupt( + "Matroska: a track delayed after the first packet", + )); + } + let track = self + .tracks + .get_mut(stream as usize) + .ok_or_else(|| Error::corrupt(format!("Matroska: no stream {stream} to delay")))?; + track.delay_ns = Some(delay_ns); + Ok(()) + } + fn write(&mut self, bytes: &[u8]) -> Result<()> { self.w.write_all(bytes)?; self.pos += bytes.len() as u64; @@ -187,14 +232,15 @@ impl MatroskaMuxer { self.tracks_at = head.len() as u64; let mut tracks = Vec::new(); for (i, info) in self.streams.clone().iter().enumerate() { - let entry = self.track_entry(info, self.tracks[i].number)?; + let entry = self.track_entry(info, i)?; elem(&mut tracks, ebml::TRACK_ENTRY, &entry); } elem(&mut head, ebml::TRACKS, &tracks); self.write(&head) } - fn track_entry(&self, info: &StreamInfo, number: u64) -> Result> { + fn track_entry(&self, info: &StreamInfo, track: usize) -> Result> { + let number = self.tracks[track].number; let params = &info.params; let codec = matroska_codec_id(params.codec)?; if self.webm @@ -228,6 +274,13 @@ impl MatroskaMuxer { { elem(&mut entry, ebml::CODEC_PRIVATE, extradata); } + if !self.tracks[track].title.is_empty() { + elem( + &mut entry, + ebml::TRACK_NAME, + self.tracks[track].title.as_bytes(), + ); + } // A track that states no language is English by spec, so a track whose // source said nothing says `und` here rather than claiming a language. elem( @@ -320,7 +373,11 @@ impl MatroskaMuxer { // and a track written without it plays 6.5 ms early against the // picture. The pre-roll is the 80 ms the spec asks a seek to // decode and throw away. - if params.codec == CodecId::Opus + // A caller that stated the delay outright is believed first: + // AAC's is one access unit and nothing in the file says so. + if let Some(ns) = self.tracks[track].delay_ns { + uint(&mut entry, ebml::CODEC_DELAY, ns); + } else if params.codec == CodecId::Opus && let Some(head) = ¶ms.extradata && head.len() >= 12 && head.starts_with(b"OpusHead") @@ -456,6 +513,8 @@ impl Muxer for MatroskaMuxer { media: info.params.codec.media_type(), time_base: info.time_base, frame_ns, + title: String::new(), + delay_ns: None, }); let mut info = info; info.index = index; @@ -512,8 +571,12 @@ impl Muxer for MatroskaMuxer { } self.flush()?; - // The index, in the order a seek reads it. - let cues_at = self.pos - self.segment_body; + // The index, in the order a seek reads it. Kept as a file offset like + // the other two: the `SeekHead` below is what makes them all relative, + // and a position taken off the segment twice points at the middle of a + // cluster — where a reader that follows it finds an element that cannot + // be there and gives up on the file. + let cues_at = self.pos; let mut cues = Vec::new(); for cue in std::mem::take(&mut self.cues) { let mut positions = Vec::new(); diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index 2bde0e21..b669d456 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -200,6 +200,78 @@ fn remux(src: &Path, dst: &Path) -> usize { packets } +/// Every `SeekHead` entry of `path` resolves to an element of the id it names. +/// +/// `SeekPosition` is stated from the start of the `Segment`'s payload, and a +/// position taken off that twice lands inside a cluster: the element id read +/// there is whatever byte happened to be at the offset. +fn seek_head_points_at_what_it_names(path: &Path) { + let bytes = std::fs::read(path).expect("the written file"); + // Element headers, by hand: an id is a variable-length integer with its + // marker bit kept, a size is one with the marker stripped. + let elem = |at: usize| -> (u32, usize, u64) { + let len = (bytes[at].leading_zeros() + 1) as usize; + let id = bytes[at..at + len] + .iter() + .fold(0u32, |acc, &b| (acc << 8) | u32::from(b)); + let szn = (bytes[at + len].leading_zeros() + 1) as usize; + let mut size = u64::from(bytes[at + len]) & (0xFFu64 >> szn); + for &b in &bytes[at + len + 1..at + len + szn] { + size = (size << 8) | u64::from(b); + } + (id, at + len + szn, size) + }; + let (_, ebml_body, ebml_size) = elem(0); + let segment_at = ebml_body + ebml_size as usize; + let (id, segment_body, _) = elem(segment_at); + assert_eq!(id, 0x1853_8067, "{}: no Segment", path.display()); + let (id, head_body, head_size) = elem(segment_body); + assert_eq!(id, 0x114D_9B74, "{}: no SeekHead", path.display()); + + let mut found = 0; + let mut at = head_body; + while at < head_body + head_size as usize { + let (id, body, size) = elem(at); + at = body + size as usize; + if id != 0x4DBB { + continue; + } + let (mut want, mut pos) = (None, None); + let mut child = body; + while child < at { + let (id, body, size) = elem(child); + child = body + size as usize; + match id { + 0x53AB => { + want = Some( + bytes[body..body + size as usize] + .iter() + .fold(0u32, |acc, &b| (acc << 8) | u32::from(b)), + ); + } + 0x53AC => { + pos = Some( + bytes[body..body + size as usize] + .iter() + .fold(0u64, |acc, &b| (acc << 8) | u64::from(b)), + ); + } + _ => {} + } + } + let (want, pos) = (want.expect("a SeekID"), pos.expect("a SeekPosition")); + let (id, ..) = elem(segment_body + pos as usize); + assert_eq!( + id, + want, + "{}: SeekHead names {want:#x} at {pos} and finds {id:#x}", + path.display() + ); + found += 1; + } + assert!(found >= 3, "{}: {found} SeekHead entries", path.display()); +} + #[test] fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { let files = matroska_fixtures(); @@ -222,6 +294,13 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { src.display() ); + // ...and the `SeekHead` really names the elements it says it does. A + // demuxer that finds nothing there falls back to a walk and reads the + // file perfectly well, so nothing above this notices — while a stricter + // reader (symphonia's) follows the pointer into the middle of a cluster + // and refuses the file outright. Checked by resolving every entry. + seek_head_points_at_what_it_names(&dst); + // ...and it decodes, which is the only claim a field compare cannot make. let decode = Command::new("ffmpeg") .args(["-v", "error", "-i"])