diff --git a/crates/ec-core/src/registry.rs b/crates/ec-core/src/registry.rs index 0bbd6355..1a666e2b 100644 --- a/crates/ec-core/src/registry.rs +++ b/crates/ec-core/src/registry.rs @@ -239,10 +239,30 @@ pub struct StreamInfo { pub duration: Option, /// ISO 639-2 language tag, when the container carries one. pub language: Option, + /// Samples the decoder emits before the first audible one: an MP3's LAME + /// encoder delay, an Opus stream's pre-skip. Zero where a stream has none. + /// + /// It is *not* subtracted from [`duration`](Self::duration), because a + /// caller counting decoded samples has to count these too before it can + /// drop them -- audible length is `duration - initial_padding`. Trailing + /// padding is not reported separately: `duration` already ends at the last + /// audible sample. + pub initial_padding: u32, + /// The container **explicitly** marked this stream as the one to play -- + /// Matroska's `FlagDefault`, which is what names the language a dual-audio + /// remux opens in. + /// + /// Explicitly is the whole of it: `FlagDefault` is 1 when the element is + /// absent, so "flagged" and "eligible" are different questions and only the + /// first one picks a track. A file where nobody wrote the element has no + /// flagged stream at all, and its first stream of a kind is its default + /// ([`crate::registry`] callers, `ec_probe::Reader::default_stream`). + pub default: bool, } impl StreamInfo { - /// A stream with no timing hints and no language. + /// A stream with no timing hints, no language, no padding and no default + /// flag. pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo { StreamInfo { index, @@ -251,6 +271,8 @@ impl StreamInfo { start_time: None, duration: None, language: None, + initial_padding: 0, + default: false, } } } diff --git a/crates/ec-matroska/src/demux.rs b/crates/ec-matroska/src/demux.rs index 9950075b..8cb9e6c8 100644 --- a/crates/ec-matroska/src/demux.rs +++ b/crates/ec-matroska/src/demux.rs @@ -674,6 +674,13 @@ impl MatroskaDemuxer { /// Where to start scanning for `target` on `track`: the last indexed /// cluster at or before it, and the first cluster of the file when nothing /// is indexed at all. + /// + /// A target *before* everything indexed starts at the first cluster and not + /// at the first index entry, because an index is allowed to begin late: our + /// own muxer cues the second cluster of an export first, and starting there + /// for a seek to zero swallowed the file's opening block whole -- 20 ms of + /// an Opus export, and 167 ms of a film whose clusters are a second each. + /// The first cluster is at or before every target there is. fn candidate(&self, track: u64, target: i64) -> u64 { // A cue naming this track is worth more than one naming another: only // the track's own cues promise a keyframe at that instant. @@ -681,13 +688,18 @@ impl MatroskaDemuxer { if !own.is_empty() { return match own.iter().rposition(|c| c.time <= target) { Some(i) => own[i].cluster, - None => own[0].cluster, + None => self.first_cluster, }; } if !self.cues.is_empty() { + // Another track's cue names the cluster *its* keyframe is in, which + // at the same instant can start later than ours does: an export + // whose first audio block sits in a cluster of its own has the + // video's `time: 0` cue pointing past it, and starting there loses + // that block. One entry further back is at or before our own packet. return match self.cues.iter().rposition(|c| c.time <= target) { - Some(i) => self.cues[i].cluster, - None => self.cues[0].cluster, + Some(i) if i > 0 => self.cues[i - 1].cluster, + _ => self.first_cluster, }; } match self.clusters.iter().rposition(|(ts, _)| *ts <= target) { @@ -1089,6 +1101,10 @@ fn parse_tracks( 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); + // `FlagDefault`, and only where the file really wrote it: the element's + // absent value is 1, so every track of a file that states none would + // otherwise claim to be the default and none of them would mean it. + let mut flag_default = false; let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default()); // The `Range` element's own code -- 0 for an element that never stated // one, which is not the same claim as "limited" and must not become it. @@ -1111,6 +1127,7 @@ fn parse_tracks( ebml::DEFAULT_DURATION => { default_duration = Some(ebml::uint_of(&buf[child])).filter(|d| *d > 0) } + ebml::FLAG_DEFAULT => flag_default = ebml::uint_of(&buf[child]) != 0, ebml::CONTENT_ENCODINGS => unpack = content_encoding(buf, child), ebml::VIDEO => { let start = child.start; @@ -1207,6 +1224,7 @@ fn parse_tracks( info.duration = duration; info.start_time = Some(0); info.language = Some(language_of(&language, &bcp47)); + info.default = flag_default; streams.push(info); Some(index) } diff --git a/crates/ec-matroska/src/ebml.rs b/crates/ec-matroska/src/ebml.rs index c95460f0..099cce83 100644 --- a/crates/ec-matroska/src/ebml.rs +++ b/crates/ec-matroska/src/ebml.rs @@ -32,6 +32,7 @@ pub const TRACK_NUMBER: u32 = 0xD7; pub const TRACK_UID: u32 = 0x73C5; pub const TRACK_TYPE: u32 = 0x83; pub const FLAG_LACING: u32 = 0x9C; +pub const FLAG_DEFAULT: u32 = 0x88; pub const CODEC_ID: u32 = 0x86; pub const CODEC_PRIVATE: u32 = 0x63A2; pub const CODEC_DELAY: u32 = 0x56AA; diff --git a/crates/ec-matroska/tests/matroska.rs b/crates/ec-matroska/tests/matroska.rs index b669d456..930c15c8 100644 --- a/crates/ec-matroska/tests/matroska.rs +++ b/crates/ec-matroska/tests/matroska.rs @@ -200,6 +200,49 @@ fn remux(src: &Path, dst: &Path) -> usize { packets } +/// Seeking each stream of `path` to its own first packet lands on that packet. +fn a_seek_to_the_beginning_lands_on_the_first_packet(path: &Path) { + let mut demuxer = + MatroskaDemuxer::new(BufReader::new(File::open(path).expect("opens"))).expect("demuxes"); + let streams = demuxer.streams().to_vec(); + for stream in &streams { + let mut first = None; + loop { + match demuxer.next_packet() { + Ok(packet) if packet.stream == stream.index => { + first = packet.pts; + break; + } + Ok(_) => {} + Err(_) => break, + } + } + let Some(first) = first else { continue }; + demuxer + .seek( + stream.index, + Timestamp::new(first, stream.time_base), + SeekMode::SyncBefore, + ) + .expect("seeks to the beginning"); + loop { + let packet = demuxer.next_packet().expect("a packet after the seek"); + if packet.stream != stream.index { + continue; + } + assert_eq!( + packet.pts, + Some(first), + "{}: stream {} restarts at {:?}, not at its first packet {first}", + path.display(), + stream.index, + packet.pts, + ); + break; + } + } +} + /// 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 @@ -301,6 +344,13 @@ fn every_fixture_remuxes_into_a_file_ffprobe_and_ffmpeg_agree_with() { // and refuses the file outright. Checked by resolving every entry. seek_head_points_at_what_it_names(&dst); + // ...and a seek to the beginning really goes there. Our own muxer cues + // the *video* track only, and one of its cue clusters can start after + // the first audio block does, so a seek that trusted the nearest cue + // began past the sound: 20 ms of an export, a whole cluster of a film, + // missing from the start of every playback that seeked to zero. + a_seek_to_the_beginning_lands_on_the_first_packet(&dst); + // ...and it decodes, which is the only claim a field compare cannot make. let decode = Command::new("ffmpeg") .args(["-v", "error", "-i"]) @@ -573,3 +623,91 @@ fn real_library_spot_sweep() { } println!("{}", table.join("\n")); } + +/// A file whose *first* cluster holds only sound: seeking its audio track to +/// the beginning lands on that block, not on the first cue. +/// +/// This muxer opens a new cluster at every video keyframe and cues the video +/// track alone, so an audio block written before the first keyframe ends up in +/// a cluster the cue table never names. A seek that started at the nearest cue +/// began *past* that block -- a whole cluster of sound gone from the start of +/// playback, which is the class of defect this crate exists not to have. +#[test] +fn the_first_cluster_is_reachable_when_no_cue_names_it() { + let src = matroska_fixtures() + .into_iter() + .find(|p| { + MatroskaDemuxer::new(BufReader::new(File::open(p).unwrap())) + .map(|d| { + d.streams() + .iter() + .filter(|s| { + matches!( + s.params.codec.media_type(), + ec_core::registry::MediaType::Audio + | ec_core::registry::MediaType::Video + ) + }) + .count() + > 1 + }) + .unwrap_or(false) + }) + .expect("a fixture with both picture and sound"); + + let mut demuxer = + MatroskaDemuxer::new(BufReader::new(File::open(&src).expect("opens"))).expect("demuxes"); + let streams = demuxer.streams().to_vec(); + let audio = streams + .iter() + .find(|s| s.params.codec.media_type() == ec_core::registry::MediaType::Audio) + .expect("an audio stream") + .index; + let mut packets = Vec::new(); + while let Ok(packet) = demuxer.next_packet() { + packets.push(packet); + if packets.len() > 400 { + break; + } + } + // The one block that has to lead: an audio block, in front of every + // keyframe, so the cluster it opens is one no cue can name. + let first_audio = packets + .iter() + .position(|p| p.stream == audio) + .expect("an audio packet"); + let lead = packets.remove(first_audio); + let want = lead.pts; + packets.insert(0, lead); + + let dst = work().join("cue-blind-first-cluster.mkv"); + let mut muxer = MatroskaMuxer::new(File::create(&dst).expect("output")); + for stream in &streams { + muxer.add_stream(stream.clone()).expect("stream declared"); + } + for packet in &packets { + muxer.write_packet(packet).expect("packet written"); + } + muxer.finish().expect("finished"); + + let mut back = + MatroskaDemuxer::new(BufReader::new(File::open(&dst).expect("opens"))).expect("demuxes"); + back.seek( + audio, + Timestamp::new(want.unwrap_or(0), streams[audio as usize].time_base), + SeekMode::SyncBefore, + ) + .expect("seeks to the beginning"); + loop { + let packet = back.next_packet().expect("a packet after the seek"); + if packet.stream != audio { + continue; + } + assert_eq!( + packet.pts, want, + "the audio restarts at {:?} and not at its first block {want:?}", + packet.pts + ); + break; + } +} diff --git a/crates/ec-mp4/src/demux.rs b/crates/ec-mp4/src/demux.rs index caccb0bc..e06ac7dc 100644 --- a/crates/ec-mp4/src/demux.rs +++ b/crates/ec-mp4/src/demux.rs @@ -441,6 +441,15 @@ impl Mp4Demuxer { start_time: None, duration: (duration > 0).then_some(duration as i64), language, + // ISO-BMFF has no "play this one" flag: `tkhd` says whether + // a track is enabled, not which of two languages was meant, + // so file order is the whole answer here. + default: false, + // An mp4 states its encoder delay in the edit list, which is + // read above as a pure shift of the whole track rather than + // a trim: no sample is dropped, so none is announced as + // padding either. + initial_padding: 0, }); Some(index) } diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 815beed7..04bee1e8 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -47,6 +47,10 @@ pub use tags::Tags; const HEAD: usize = 64 << 10; /// Packets a seek may look past to find one of the stream it was asked about. const SEEK_LOOKAHEAD: usize = 64; +/// Samples of synthesis delay every Layer III decoder carries, on top of +/// whatever delay the encoder wrote into the LAME tag. The number is the format +/// 's, not this implementation's: a LAME tag is written to be read with it. +const MP3_DECODER_DELAY: u32 = 529; /// A container (or the lack of one) this crate can open. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -297,12 +301,21 @@ impl Reader { self.inner.streams() } - /// The first stream of `kind`, which is what a caller that just wants "the - /// audio" means. + /// The stream of `kind` a caller that just wants "the audio" means: the one + /// the container flagged ([`StreamInfo::default`]), and the first of that + /// kind where nothing is flagged. + /// + /// The flag comes first because it is the whole answer to which language a + /// dual-audio remux opens in -- a muxer that put the French track second + /// and marked it default meant the French one, and file order would play + /// the other. pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> { - self.streams() - .iter() - .find(|s| s.params.codec.media_type() == kind) + let of_kind = || { + self.streams() + .iter() + .filter(move |s| s.params.codec.media_type() == kind) + }; + of_kind().find(|s| s.default).or_else(|| of_kind().next()) } /// The container's own id for a stream: a Matroska `TrackNumber`, which is @@ -326,10 +339,17 @@ impl Reader { } /// The longest stream's duration, when any stream states or implies one. + /// + /// What a player would play: [`StreamInfo::initial_padding`] is off it, + /// because an MP3's encoder delay is silence the file carries and nobody + /// hears. pub fn duration(&self) -> Option { self.streams() .iter() - .filter_map(|s| s.duration.map(|d| Timestamp::new(d, s.time_base))) + .filter_map(|s| { + s.duration + .map(|d| Timestamp::new(d - i64::from(s.initial_padding), s.time_base)) + }) .max_by(|a, b| { a.as_secs_f64() .partial_cmp(&b.as_secs_f64()) @@ -527,11 +547,22 @@ fn open_mp3(mut src: R, head: &[u8], end: u64) // ffmpeg and this reader start after it. start += header.frame_len().unwrap_or(0) as u64; } - let total = match xing { - Some(frames) => Some(frames * per_frame), - None => header - .frame_len() - .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), + // Gapless, as the LAME tag states it: a decoder emits the encoder delay + // plus its own 529 samples of Layer III synthesis delay before the first + // sample that was ever recorded, and the file runs `padding` samples past + // the last one. Both are silence a player must not play, and a file with no + // tag has neither — its frames are all there is to go on. + let (padding, total) = match &xing { + Some(x) => ( + x.delay + MP3_DECODER_DELAY, + Some(x.frames * per_frame - u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))), + ), + None => ( + 0, + header + .frame_len() + .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), + ), }; let demuxer = raw::RawDemuxer::new( src, @@ -541,7 +572,8 @@ fn open_mp3(mut src: R, head: &[u8], end: u64) audio_end, total, None, - )?; + )? + .with_initial_padding(padding); Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0])) } @@ -622,7 +654,7 @@ fn id3v1_len(src: &mut R, end: u64) -> Result { } /// The frame count a Xing/Info header states, when the first frame carries one. -fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { +fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { let at = 4 + usize::from(header.crc) * 2 + header.side_info_len(); let tag = frame.get(at..at + 8)?; if &tag[..4] != b"Xing" && &tag[..4] != b"Info" { @@ -633,7 +665,37 @@ fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { return None; } let n = frame.get(at + 8..at + 12)?; - Some(u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]))) + let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])); + // The LAME extension sits behind whichever optional fields the flags + // claimed -- frame count, byte count, the 100-byte seek table, quality -- + // and states the two trims 21 bytes into itself, twelve bits each. + let mut lame = at + 12; + lame += usize::from(flags & 2 != 0) * 4; + lame += usize::from(flags & 4 != 0) * 100; + lame += usize::from(flags & 8 != 0) * 4; + let (delay, padding) = match frame.get(lame + 21..lame + 24) { + Some(&[a, b, c]) => ( + u32::from(a) << 4 | u32::from(b) >> 4, + (u32::from(b) & 0xF) << 8 | u32::from(c), + ), + _ => (0, 0), + }; + Some(Xing { + frames, + delay, + padding, + }) +} + +/// What an MP3's Xing/Info header states: how long the file is, and the two +/// silences the encoder had to add to make whole frames of it. +struct Xing { + /// Audio frames in the file, the header frame itself excluded. + frames: u64, + /// Encoder delay: samples of silence in front of the first real one. + delay: u32, + /// Encoder padding: samples of silence after the last real one. + padding: u32, } #[cfg(test)] diff --git a/crates/ec-probe/src/raw.rs b/crates/ec-probe/src/raw.rs index cd676dba..0af7dd20 100644 --- a/crates/ec-probe/src/raw.rs +++ b/crates/ec-probe/src/raw.rs @@ -104,6 +104,13 @@ impl RawDemuxer { }) } + /// State that this stream opens with `samples` a decoder emits before the + /// first audible one ([`StreamInfo::initial_padding`]). + pub(crate) fn with_initial_padding(mut self, samples: u32) -> RawDemuxer { + self.streams[0].initial_padding = samples; + self + } + /// Samples in a typical frame of this format, for the tail of an estimate. fn frame_samples(&self) -> u64 { match self.kind { diff --git a/crates/ec-probe/tests/matrix.rs b/crates/ec-probe/tests/matrix.rs index db94d9d9..6717bba0 100644 --- a/crates/ec-probe/tests/matrix.rs +++ b/crates/ec-probe/tests/matrix.rs @@ -307,3 +307,69 @@ fn a_mislabelled_file_opens_as_what_it_is() { assert_eq!(reader.format(), Format::Flac); std::fs::remove_file(&liar).ok(); } + +/// The head of a file, where two things are exact rather than approximate: +/// what a gapless MP3's audible length is, and where a seek to zero lands. +/// +/// Both were wrong at once. The LAME tag's encoder delay and padding went +/// unread, so an `.mp3` claimed the silence around its sound as part of it and +/// played 25 ms late against a `.flac` of the same tone; and a seek to zero +/// started at the first *cue*, which in a file whose cues name only the video +/// track sits past the first audio block — 20 ms of an export, a cluster of a +/// film, gone from the start of every playback that seeked to the beginning. +#[test] +fn the_head_of_a_file_is_exact() { + let mut checked = 0; + for &(name, _, codec) in MATRIX { + let path = fixtures().join(name); + if !path.exists() { + continue; + } + let mut reader = Reader::open(&path).expect("open"); + let audio = reader + .default_stream(MediaType::Audio) + .expect("audio") + .clone(); + // Gapless: what the file states it holds, less the silence it states it + // padded with, is exactly what ffmpeg decodes out of it. + if codec == "mp3" { + let padding = u64::from(audio.initial_padding); + assert!( + padding > 0, + "{name}: no encoder delay read out of the LAME tag" + ); + let stated = audio.duration.expect("an mp3 states its length") as u64; + let channels = audio.params.audio().unwrap().layout.channel_count(); + assert_eq!( + stated - padding, + ffmpeg_frames(&path, channels), + "{name}: audible frames" + ); + } + // A seek to the beginning lands on the file's own first packet, never + // past it. Asked for by that packet's own timestamp rather than by + // zero, because an mp4's first AAC packet is at -1024: its priming. + let first = loop { + let packet = reader.next_packet().expect("a first packet"); + if packet.stream == audio.index { + break packet.pts.unwrap_or(0); + } + }; + let landed = reader + .seek( + audio.index, + Timestamp::new(first, audio.time_base), + SeekMode::SyncBefore, + ) + .unwrap_or_else(|e| panic!("{name}: seek to the beginning: {e}")); + assert_eq!( + landed.ticks, first, + "{name}: a seek to the beginning landed past the first packet" + ); + checked += 1; + } + assert!( + checked > 0, + "no fixtures found — run scripts/gen-fixtures.sh" + ); +} diff --git a/shims/symphonia-core/src/formats.rs b/shims/symphonia-core/src/formats.rs index b2d46e72..5e0d0c20 100644 --- a/shims/symphonia-core/src/formats.rs +++ b/shims/symphonia-core/src/formats.rs @@ -30,6 +30,11 @@ pub struct Track { pub num_frames: Option, /// First timestamp. pub start_ts: u64, + /// Samples the decoder emits before the first audible one -- an MP3's LAME + /// encoder delay, an Opus stream's pre-skip. **Not** dropped by the reader: + /// [`num_frames`](Self::num_frames) counts them, so a caller that wants the + /// audible stream skips them and takes `num_frames - delay` samples. + pub delay: Option, /// Codec and setup data. pub codec_params: Option, /// ISO 639 language tag, when the container carries one. diff --git a/shims/symphonia/Cargo.toml b/shims/symphonia/Cargo.toml index 6c4cfff9..f58bf688 100644 --- a/shims/symphonia/Cargo.toml +++ b/shims/symphonia/Cargo.toml @@ -14,3 +14,23 @@ symphonia-core = { path = "../symphonia-core", version = "0.6.0" } [dev-dependencies] symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" } + +# The incumbent's feature names, every one of them a no-op: a caller selects +# codecs and containers there, and here `ec_probe` serves all of them +# unconditionally. They are declared because a feature list is part of the +# surface a `[patch.crates-io]` entry has to answer — a consumer naming +# `features = ["mkv"]` fails to resolve otherwise, which is not a difference +# worth making it edit its manifest for. +[features] +aac = [] +alac = [] +flac = [] +id3v1 = [] +id3v2 = [] +isomp4 = [] +mkv = [] +mp3 = [] +ogg = [] +pcm = [] +vorbis = [] +wav = [] diff --git a/shims/symphonia/src/reader.rs b/shims/symphonia/src/reader.rs index 0b81cad8..30c5a60f 100644 --- a/shims/symphonia/src/reader.rs +++ b/shims/symphonia/src/reader.rs @@ -35,6 +35,7 @@ impl ProbeReader { time_base: Some(TimeBase::from(s.time_base)), num_frames: s.duration.map(|d| d.max(0) as u64), start_ts: s.start_time.unwrap_or(0).max(0) as u64, + delay: Some(u64::from(s.initial_padding)).filter(|d| *d > 0), codec_params: Some(from_ec_parameters(&s.params)), language: s.language.clone(), }) @@ -62,7 +63,16 @@ impl FormatReader for ProbeReader { } fn default_track(&self, kind: TrackType) -> Option<&Track> { - self.tracks.iter().find(|t| t.track_type == kind) + // The container's flagged track, not merely the first one of its kind: + // a dual-audio remux that marked its second track default opens in that + // language, which is what a caller asking for "the audio" means by it. + let media = match kind { + TrackType::Audio => MediaType::Audio, + TrackType::Video => MediaType::Video, + TrackType::Subtitle => MediaType::Subtitle, + }; + let index = self.inner.default_stream(media)?.index; + self.tracks.get(index as usize) } fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result {