The head of a file is exact, and a default track is the flagged one
Browse files at this commitc665d19c5e4511aa51322c4492dbb9bd8fd9cf5dParent: 4cab1f0- fix
- the head of a file is exact, and a default track is the flagged one
11 changed files +377 -19
- crates/ec-core/src/registry.rs +23 -1
- crates/ec-matroska/src/demux.rs +21 -3
- crates/ec-matroska/src/ebml.rs +1 -0
- crates/ec-matroska/tests/matroska.rs +138 -0
- crates/ec-mp4/src/demux.rs +9 -0
- crates/ec-probe/src/lib.rs +76 -14
- crates/ec-probe/src/raw.rs +7 -0
- crates/ec-probe/tests/matrix.rs +66 -0
- shims/symphonia-core/src/formats.rs +5 -0
- shims/symphonia/Cargo.toml +20 -0
- shims/symphonia/src/reader.rs +11 -1
crates/ec-core/src/registry.rsmodified+23 -1
| @@ -239,10 +239,30 @@ pub struct StreamInfo { | ||
| 239 | 239 | pub duration: Option<i64>, |
| 240 | 240 | /// ISO 639-2 language tag, when the container carries one. |
| 241 | 241 | pub language: Option<String>, |
| 242 | + /// Samples the decoder emits before the first audible one: an MP3's LAME | |
| 243 | + /// encoder delay, an Opus stream's pre-skip. Zero where a stream has none. | |
| 244 | + /// | |
| 245 | + /// It is *not* subtracted from [`duration`](Self::duration), because a | |
| 246 | + /// caller counting decoded samples has to count these too before it can | |
| 247 | + /// drop them -- audible length is `duration - initial_padding`. Trailing | |
| 248 | + /// padding is not reported separately: `duration` already ends at the last | |
| 249 | + /// audible sample. | |
| 250 | + pub initial_padding: u32, | |
| 251 | + /// The container **explicitly** marked this stream as the one to play -- | |
| 252 | + /// Matroska's `FlagDefault`, which is what names the language a dual-audio | |
| 253 | + /// remux opens in. | |
| 254 | + /// | |
| 255 | + /// Explicitly is the whole of it: `FlagDefault` is 1 when the element is | |
| 256 | + /// absent, so "flagged" and "eligible" are different questions and only the | |
| 257 | + /// first one picks a track. A file where nobody wrote the element has no | |
| 258 | + /// flagged stream at all, and its first stream of a kind is its default | |
| 259 | + /// ([`crate::registry`] callers, `ec_probe::Reader::default_stream`). | |
| 260 | + pub default: bool, | |
| 242 | 261 | } |
| 243 | 262 | |
| 244 | 263 | impl StreamInfo { |
| 245 | - /// A stream with no timing hints and no language. | |
| 264 | + /// A stream with no timing hints, no language, no padding and no default | |
| 265 | + /// flag. | |
| 246 | 266 | pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo { |
| 247 | 267 | StreamInfo { |
| 248 | 268 | index, |
| @@ -251,6 +271,8 @@ impl StreamInfo { | ||
| 251 | 271 | start_time: None, |
| 252 | 272 | duration: None, |
| 253 | 273 | language: None, |
| 274 | + initial_padding: 0, | |
| 275 | + default: false, | |
| 254 | 276 | } |
| 255 | 277 | } |
| 256 | 278 | } |
crates/ec-matroska/src/demux.rsmodified+21 -3
| @@ -674,6 +674,13 @@ impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 674 | 674 | /// Where to start scanning for `target` on `track`: the last indexed |
| 675 | 675 | /// cluster at or before it, and the first cluster of the file when nothing |
| 676 | 676 | /// is indexed at all. |
| 677 | + /// | |
| 678 | + /// A target *before* everything indexed starts at the first cluster and not | |
| 679 | + /// at the first index entry, because an index is allowed to begin late: our | |
| 680 | + /// own muxer cues the second cluster of an export first, and starting there | |
| 681 | + /// for a seek to zero swallowed the file's opening block whole -- 20 ms of | |
| 682 | + /// an Opus export, and 167 ms of a film whose clusters are a second each. | |
| 683 | + /// The first cluster is at or before every target there is. | |
| 677 | 684 | fn candidate(&self, track: u64, target: i64) -> u64 { |
| 678 | 685 | // A cue naming this track is worth more than one naming another: only |
| 679 | 686 | // the track's own cues promise a keyframe at that instant. |
| @@ -681,13 +688,18 @@ impl<R: Read + Seek> MatroskaDemuxer<R> { | ||
| 681 | 688 | if !own.is_empty() { |
| 682 | 689 | return match own.iter().rposition(|c| c.time <= target) { |
| 683 | 690 | Some(i) => own[i].cluster, |
| 684 | - None => own[0].cluster, | |
| 691 | + None => self.first_cluster, | |
| 685 | 692 | }; |
| 686 | 693 | } |
| 687 | 694 | if !self.cues.is_empty() { |
| 695 | + // Another track's cue names the cluster *its* keyframe is in, which | |
| 696 | + // at the same instant can start later than ours does: an export | |
| 697 | + // whose first audio block sits in a cluster of its own has the | |
| 698 | + // video's `time: 0` cue pointing past it, and starting there loses | |
| 699 | + // that block. One entry further back is at or before our own packet. | |
| 688 | 700 | return match self.cues.iter().rposition(|c| c.time <= target) { |
| 689 | - Some(i) => self.cues[i].cluster, | |
| 690 | - None => self.cues[0].cluster, | |
| 701 | + Some(i) if i > 0 => self.cues[i - 1].cluster, | |
| 702 | + _ => self.first_cluster, | |
| 691 | 703 | }; |
| 692 | 704 | } |
| 693 | 705 | match self.clusters.iter().rposition(|(ts, _)| *ts <= target) { |
| @@ -1089,6 +1101,10 @@ fn parse_tracks( | ||
| 1089 | 1101 | let (mut language, mut bcp47, mut private) = (String::new(), String::new(), None); |
| 1090 | 1102 | let mut name = String::new(); |
| 1091 | 1103 | let (mut default_duration, mut unpack) = (None, Unpack::None); |
| 1104 | + // `FlagDefault`, and only where the file really wrote it: the element's | |
| 1105 | + // absent value is 1, so every track of a file that states none would | |
| 1106 | + // otherwise claim to be the default and none of them would mean it. | |
| 1107 | + let mut flag_default = false; | |
| 1092 | 1108 | let (mut width, mut height, mut color) = (0u32, 0u32, ColorInfo::default()); |
| 1093 | 1109 | // The `Range` element's own code -- 0 for an element that never stated |
| 1094 | 1110 | // one, which is not the same claim as "limited" and must not become it. |
| @@ -1111,6 +1127,7 @@ fn parse_tracks( | ||
| 1111 | 1127 | ebml::DEFAULT_DURATION => { |
| 1112 | 1128 | default_duration = Some(ebml::uint_of(&buf[child])).filter(|d| *d > 0) |
| 1113 | 1129 | } |
| 1130 | + ebml::FLAG_DEFAULT => flag_default = ebml::uint_of(&buf[child]) != 0, | |
| 1114 | 1131 | ebml::CONTENT_ENCODINGS => unpack = content_encoding(buf, child), |
| 1115 | 1132 | ebml::VIDEO => { |
| 1116 | 1133 | let start = child.start; |
| @@ -1207,6 +1224,7 @@ fn parse_tracks( | ||
| 1207 | 1224 | info.duration = duration; |
| 1208 | 1225 | info.start_time = Some(0); |
| 1209 | 1226 | info.language = Some(language_of(&language, &bcp47)); |
| 1227 | + info.default = flag_default; | |
| 1210 | 1228 | streams.push(info); |
| 1211 | 1229 | Some(index) |
| 1212 | 1230 | } |
crates/ec-matroska/src/ebml.rsmodified+1 -0
| @@ -32,6 +32,7 @@ pub const TRACK_NUMBER: u32 = 0xD7; | ||
| 32 | 32 | pub const TRACK_UID: u32 = 0x73C5; |
| 33 | 33 | pub const TRACK_TYPE: u32 = 0x83; |
| 34 | 34 | pub const FLAG_LACING: u32 = 0x9C; |
| 35 | +pub const FLAG_DEFAULT: u32 = 0x88; | |
| 35 | 36 | pub const CODEC_ID: u32 = 0x86; |
| 36 | 37 | pub const CODEC_PRIVATE: u32 = 0x63A2; |
| 37 | 38 | pub const CODEC_DELAY: u32 = 0x56AA; |
crates/ec-matroska/tests/matroska.rsmodified+138 -0
| @@ -200,6 +200,49 @@ fn remux(src: &Path, dst: &Path) -> usize { | ||
| 200 | 200 | packets |
| 201 | 201 | } |
| 202 | 202 | |
| 203 | +/// Seeking each stream of `path` to its own first packet lands on that packet. | |
| 204 | +fn a_seek_to_the_beginning_lands_on_the_first_packet(path: &Path) { | |
| 205 | + let mut demuxer = | |
| 206 | + MatroskaDemuxer::new(BufReader::new(File::open(path).expect("opens"))).expect("demuxes"); | |
| 207 | + let streams = demuxer.streams().to_vec(); | |
| 208 | + for stream in &streams { | |
| 209 | + let mut first = None; | |
| 210 | + loop { | |
| 211 | + match demuxer.next_packet() { | |
| 212 | + Ok(packet) if packet.stream == stream.index => { | |
| 213 | + first = packet.pts; | |
| 214 | + break; | |
| 215 | + } | |
| 216 | + Ok(_) => {} | |
| 217 | + Err(_) => break, | |
| 218 | + } | |
| 219 | + } | |
| 220 | + let Some(first) = first else { continue }; | |
| 221 | + demuxer | |
| 222 | + .seek( | |
| 223 | + stream.index, | |
| 224 | + Timestamp::new(first, stream.time_base), | |
| 225 | + SeekMode::SyncBefore, | |
| 226 | + ) | |
| 227 | + .expect("seeks to the beginning"); | |
| 228 | + loop { | |
| 229 | + let packet = demuxer.next_packet().expect("a packet after the seek"); | |
| 230 | + if packet.stream != stream.index { | |
| 231 | + continue; | |
| 232 | + } | |
| 233 | + assert_eq!( | |
| 234 | + packet.pts, | |
| 235 | + Some(first), | |
| 236 | + "{}: stream {} restarts at {:?}, not at its first packet {first}", | |
| 237 | + path.display(), | |
| 238 | + stream.index, | |
| 239 | + packet.pts, | |
| 240 | + ); | |
| 241 | + break; | |
| 242 | + } | |
| 243 | + } | |
| 244 | +} | |
| 245 | + | |
| 203 | 246 | /// Every `SeekHead` entry of `path` resolves to an element of the id it names. |
| 204 | 247 | /// |
| 205 | 248 | /// `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() { | ||
| 301 | 344 | // and refuses the file outright. Checked by resolving every entry. |
| 302 | 345 | seek_head_points_at_what_it_names(&dst); |
| 303 | 346 | |
| 347 | + // ...and a seek to the beginning really goes there. Our own muxer cues | |
| 348 | + // the *video* track only, and one of its cue clusters can start after | |
| 349 | + // the first audio block does, so a seek that trusted the nearest cue | |
| 350 | + // began past the sound: 20 ms of an export, a whole cluster of a film, | |
| 351 | + // missing from the start of every playback that seeked to zero. | |
| 352 | + a_seek_to_the_beginning_lands_on_the_first_packet(&dst); | |
| 353 | + | |
| 304 | 354 | // ...and it decodes, which is the only claim a field compare cannot make. |
| 305 | 355 | let decode = Command::new("ffmpeg") |
| 306 | 356 | .args(["-v", "error", "-i"]) |
| @@ -573,3 +623,91 @@ fn real_library_spot_sweep() { | ||
| 573 | 623 | } |
| 574 | 624 | println!("{}", table.join("\n")); |
| 575 | 625 | } |
| 626 | + | |
| 627 | +/// A file whose *first* cluster holds only sound: seeking its audio track to | |
| 628 | +/// the beginning lands on that block, not on the first cue. | |
| 629 | +/// | |
| 630 | +/// This muxer opens a new cluster at every video keyframe and cues the video | |
| 631 | +/// track alone, so an audio block written before the first keyframe ends up in | |
| 632 | +/// a cluster the cue table never names. A seek that started at the nearest cue | |
| 633 | +/// began *past* that block -- a whole cluster of sound gone from the start of | |
| 634 | +/// playback, which is the class of defect this crate exists not to have. | |
| 635 | +#[test] | |
| 636 | +fn the_first_cluster_is_reachable_when_no_cue_names_it() { | |
| 637 | + let src = matroska_fixtures() | |
| 638 | + .into_iter() | |
| 639 | + .find(|p| { | |
| 640 | + MatroskaDemuxer::new(BufReader::new(File::open(p).unwrap())) | |
| 641 | + .map(|d| { | |
| 642 | + d.streams() | |
| 643 | + .iter() | |
| 644 | + .filter(|s| { | |
| 645 | + matches!( | |
| 646 | + s.params.codec.media_type(), | |
| 647 | + ec_core::registry::MediaType::Audio | |
| 648 | + | ec_core::registry::MediaType::Video | |
| 649 | + ) | |
| 650 | + }) | |
| 651 | + .count() | |
| 652 | + > 1 | |
| 653 | + }) | |
| 654 | + .unwrap_or(false) | |
| 655 | + }) | |
| 656 | + .expect("a fixture with both picture and sound"); | |
| 657 | + | |
| 658 | + let mut demuxer = | |
| 659 | + MatroskaDemuxer::new(BufReader::new(File::open(&src).expect("opens"))).expect("demuxes"); | |
| 660 | + let streams = demuxer.streams().to_vec(); | |
| 661 | + let audio = streams | |
| 662 | + .iter() | |
| 663 | + .find(|s| s.params.codec.media_type() == ec_core::registry::MediaType::Audio) | |
| 664 | + .expect("an audio stream") | |
| 665 | + .index; | |
| 666 | + let mut packets = Vec::new(); | |
| 667 | + while let Ok(packet) = demuxer.next_packet() { | |
| 668 | + packets.push(packet); | |
| 669 | + if packets.len() > 400 { | |
| 670 | + break; | |
| 671 | + } | |
| 672 | + } | |
| 673 | + // The one block that has to lead: an audio block, in front of every | |
| 674 | + // keyframe, so the cluster it opens is one no cue can name. | |
| 675 | + let first_audio = packets | |
| 676 | + .iter() | |
| 677 | + .position(|p| p.stream == audio) | |
| 678 | + .expect("an audio packet"); | |
| 679 | + let lead = packets.remove(first_audio); | |
| 680 | + let want = lead.pts; | |
| 681 | + packets.insert(0, lead); | |
| 682 | + | |
| 683 | + let dst = work().join("cue-blind-first-cluster.mkv"); | |
| 684 | + let mut muxer = MatroskaMuxer::new(File::create(&dst).expect("output")); | |
| 685 | + for stream in &streams { | |
| 686 | + muxer.add_stream(stream.clone()).expect("stream declared"); | |
| 687 | + } | |
| 688 | + for packet in &packets { | |
| 689 | + muxer.write_packet(packet).expect("packet written"); | |
| 690 | + } | |
| 691 | + muxer.finish().expect("finished"); | |
| 692 | + | |
| 693 | + let mut back = | |
| 694 | + MatroskaDemuxer::new(BufReader::new(File::open(&dst).expect("opens"))).expect("demuxes"); | |
| 695 | + back.seek( | |
| 696 | + audio, | |
| 697 | + Timestamp::new(want.unwrap_or(0), streams[audio as usize].time_base), | |
| 698 | + SeekMode::SyncBefore, | |
| 699 | + ) | |
| 700 | + .expect("seeks to the beginning"); | |
| 701 | + loop { | |
| 702 | + let packet = back.next_packet().expect("a packet after the seek"); | |
| 703 | + if packet.stream != audio { | |
| 704 | + continue; | |
| 705 | + } | |
| 706 | + assert_eq!( | |
| 707 | + packet.pts, want, | |
| 708 | + "the audio restarts at {:?} and not at its first block {want:?}", | |
| 709 | + packet.pts | |
| 710 | + ); | |
| 711 | + break; | |
| 712 | + } | |
| 713 | +} |
crates/ec-mp4/src/demux.rsmodified+9 -0
| @@ -441,6 +441,15 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 441 | 441 | start_time: None, |
| 442 | 442 | duration: (duration > 0).then_some(duration as i64), |
| 443 | 443 | language, |
| 444 | + // ISO-BMFF has no "play this one" flag: `tkhd` says whether | |
| 445 | + // a track is enabled, not which of two languages was meant, | |
| 446 | + // so file order is the whole answer here. | |
| 447 | + default: false, | |
| 448 | + // An mp4 states its encoder delay in the edit list, which is | |
| 449 | + // read above as a pure shift of the whole track rather than | |
| 450 | + // a trim: no sample is dropped, so none is announced as | |
| 451 | + // padding either. | |
| 452 | + initial_padding: 0, | |
| 444 | 453 | }); |
| 445 | 454 | Some(index) |
| 446 | 455 | } |
crates/ec-probe/src/lib.rsmodified+76 -14
| @@ -47,6 +47,10 @@ pub use tags::Tags; | ||
| 47 | 47 | const HEAD: usize = 64 << 10; |
| 48 | 48 | /// Packets a seek may look past to find one of the stream it was asked about. |
| 49 | 49 | const SEEK_LOOKAHEAD: usize = 64; |
| 50 | +/// Samples of synthesis delay every Layer III decoder carries, on top of | |
| 51 | +/// whatever delay the encoder wrote into the LAME tag. The number is the format | |
| 52 | +/// 's, not this implementation's: a LAME tag is written to be read with it. | |
| 53 | +const MP3_DECODER_DELAY: u32 = 529; | |
| 50 | 54 | |
| 51 | 55 | /// A container (or the lack of one) this crate can open. |
| 52 | 56 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| @@ -297,12 +301,21 @@ impl Reader { | ||
| 297 | 301 | self.inner.streams() |
| 298 | 302 | } |
| 299 | 303 | |
| 300 | - /// The first stream of `kind`, which is what a caller that just wants "the | |
| 301 | - /// audio" means. | |
| 304 | + /// The stream of `kind` a caller that just wants "the audio" means: the one | |
| 305 | + /// the container flagged ([`StreamInfo::default`]), and the first of that | |
| 306 | + /// kind where nothing is flagged. | |
| 307 | + /// | |
| 308 | + /// The flag comes first because it is the whole answer to which language a | |
| 309 | + /// dual-audio remux opens in -- a muxer that put the French track second | |
| 310 | + /// and marked it default meant the French one, and file order would play | |
| 311 | + /// the other. | |
| 302 | 312 | pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> { |
| 303 | - self.streams() | |
| 304 | - .iter() | |
| 305 | - .find(|s| s.params.codec.media_type() == kind) | |
| 313 | + let of_kind = || { | |
| 314 | + self.streams() | |
| 315 | + .iter() | |
| 316 | + .filter(move |s| s.params.codec.media_type() == kind) | |
| 317 | + }; | |
| 318 | + of_kind().find(|s| s.default).or_else(|| of_kind().next()) | |
| 306 | 319 | } |
| 307 | 320 | |
| 308 | 321 | /// The container's own id for a stream: a Matroska `TrackNumber`, which is |
| @@ -326,10 +339,17 @@ impl Reader { | ||
| 326 | 339 | } |
| 327 | 340 | |
| 328 | 341 | /// The longest stream's duration, when any stream states or implies one. |
| 342 | + /// | |
| 343 | + /// What a player would play: [`StreamInfo::initial_padding`] is off it, | |
| 344 | + /// because an MP3's encoder delay is silence the file carries and nobody | |
| 345 | + /// hears. | |
| 329 | 346 | pub fn duration(&self) -> Option<Timestamp> { |
| 330 | 347 | self.streams() |
| 331 | 348 | .iter() |
| 332 | - .filter_map(|s| s.duration.map(|d| Timestamp::new(d, s.time_base))) | |
| 349 | + .filter_map(|s| { | |
| 350 | + s.duration | |
| 351 | + .map(|d| Timestamp::new(d - i64::from(s.initial_padding), s.time_base)) | |
| 352 | + }) | |
| 333 | 353 | .max_by(|a, b| { |
| 334 | 354 | a.as_secs_f64() |
| 335 | 355 | .partial_cmp(&b.as_secs_f64()) |
| @@ -527,11 +547,22 @@ fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) | ||
| 527 | 547 | // ffmpeg and this reader start after it. |
| 528 | 548 | start += header.frame_len().unwrap_or(0) as u64; |
| 529 | 549 | } |
| 530 | - let total = match xing { | |
| 531 | - Some(frames) => Some(frames * per_frame), | |
| 532 | - None => header | |
| 533 | - .frame_len() | |
| 534 | - .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), | |
| 550 | + // Gapless, as the LAME tag states it: a decoder emits the encoder delay | |
| 551 | + // plus its own 529 samples of Layer III synthesis delay before the first | |
| 552 | + // sample that was ever recorded, and the file runs `padding` samples past | |
| 553 | + // the last one. Both are silence a player must not play, and a file with no | |
| 554 | + // tag has neither — its frames are all there is to go on. | |
| 555 | + let (padding, total) = match &xing { | |
| 556 | + Some(x) => ( | |
| 557 | + x.delay + MP3_DECODER_DELAY, | |
| 558 | + Some(x.frames * per_frame - u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))), | |
| 559 | + ), | |
| 560 | + None => ( | |
| 561 | + 0, | |
| 562 | + header | |
| 563 | + .frame_len() | |
| 564 | + .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), | |
| 565 | + ), | |
| 535 | 566 | }; |
| 536 | 567 | let demuxer = raw::RawDemuxer::new( |
| 537 | 568 | src, |
| @@ -541,7 +572,8 @@ fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) | ||
| 541 | 572 | audio_end, |
| 542 | 573 | total, |
| 543 | 574 | None, |
| 544 | - )?; | |
| 575 | + )? | |
| 576 | + .with_initial_padding(padding); | |
| 545 | 577 | Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0])) |
| 546 | 578 | } |
| 547 | 579 | |
| @@ -622,7 +654,7 @@ fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> { | ||
| 622 | 654 | } |
| 623 | 655 | |
| 624 | 656 | /// The frame count a Xing/Info header states, when the first frame carries one. |
| 625 | -fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<u64> { | |
| 657 | +fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> { | |
| 626 | 658 | let at = 4 + usize::from(header.crc) * 2 + header.side_info_len(); |
| 627 | 659 | let tag = frame.get(at..at + 8)?; |
| 628 | 660 | if &tag[..4] != b"Xing" && &tag[..4] != b"Info" { |
| @@ -633,7 +665,37 @@ fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<u64> { | ||
| 633 | 665 | return None; |
| 634 | 666 | } |
| 635 | 667 | let n = frame.get(at + 8..at + 12)?; |
| 636 | - Some(u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]))) | |
| 668 | + let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])); | |
| 669 | + // The LAME extension sits behind whichever optional fields the flags | |
| 670 | + // claimed -- frame count, byte count, the 100-byte seek table, quality -- | |
| 671 | + // and states the two trims 21 bytes into itself, twelve bits each. | |
| 672 | + let mut lame = at + 12; | |
| 673 | + lame += usize::from(flags & 2 != 0) * 4; | |
| 674 | + lame += usize::from(flags & 4 != 0) * 100; | |
| 675 | + lame += usize::from(flags & 8 != 0) * 4; | |
| 676 | + let (delay, padding) = match frame.get(lame + 21..lame + 24) { | |
| 677 | + Some(&[a, b, c]) => ( | |
| 678 | + u32::from(a) << 4 | u32::from(b) >> 4, | |
| 679 | + (u32::from(b) & 0xF) << 8 | u32::from(c), | |
| 680 | + ), | |
| 681 | + _ => (0, 0), | |
| 682 | + }; | |
| 683 | + Some(Xing { | |
| 684 | + frames, | |
| 685 | + delay, | |
| 686 | + padding, | |
| 687 | + }) | |
| 688 | +} | |
| 689 | + | |
| 690 | +/// What an MP3's Xing/Info header states: how long the file is, and the two | |
| 691 | +/// silences the encoder had to add to make whole frames of it. | |
| 692 | +struct Xing { | |
| 693 | + /// Audio frames in the file, the header frame itself excluded. | |
| 694 | + frames: u64, | |
| 695 | + /// Encoder delay: samples of silence in front of the first real one. | |
| 696 | + delay: u32, | |
| 697 | + /// Encoder padding: samples of silence after the last real one. | |
| 698 | + padding: u32, | |
| 637 | 699 | } |
| 638 | 700 | |
| 639 | 701 | #[cfg(test)] |
crates/ec-probe/src/raw.rsmodified+7 -0
| @@ -104,6 +104,13 @@ impl<R: Read + Seek> RawDemuxer<R> { | ||
| 104 | 104 | }) |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | + /// State that this stream opens with `samples` a decoder emits before the | |
| 108 | + /// first audible one ([`StreamInfo::initial_padding`]). | |
| 109 | + pub(crate) fn with_initial_padding(mut self, samples: u32) -> RawDemuxer<R> { | |
| 110 | + self.streams[0].initial_padding = samples; | |
| 111 | + self | |
| 112 | + } | |
| 113 | + | |
| 107 | 114 | /// Samples in a typical frame of this format, for the tail of an estimate. |
| 108 | 115 | fn frame_samples(&self) -> u64 { |
| 109 | 116 | match self.kind { |
crates/ec-probe/tests/matrix.rsmodified+66 -0
| @@ -307,3 +307,69 @@ fn a_mislabelled_file_opens_as_what_it_is() { | ||
| 307 | 307 | assert_eq!(reader.format(), Format::Flac); |
| 308 | 308 | std::fs::remove_file(&liar).ok(); |
| 309 | 309 | } |
| 310 | + | |
| 311 | +/// The head of a file, where two things are exact rather than approximate: | |
| 312 | +/// what a gapless MP3's audible length is, and where a seek to zero lands. | |
| 313 | +/// | |
| 314 | +/// Both were wrong at once. The LAME tag's encoder delay and padding went | |
| 315 | +/// unread, so an `.mp3` claimed the silence around its sound as part of it and | |
| 316 | +/// played 25 ms late against a `.flac` of the same tone; and a seek to zero | |
| 317 | +/// started at the first *cue*, which in a file whose cues name only the video | |
| 318 | +/// track sits past the first audio block — 20 ms of an export, a cluster of a | |
| 319 | +/// film, gone from the start of every playback that seeked to the beginning. | |
| 320 | +#[test] | |
| 321 | +fn the_head_of_a_file_is_exact() { | |
| 322 | + let mut checked = 0; | |
| 323 | + for &(name, _, codec) in MATRIX { | |
| 324 | + let path = fixtures().join(name); | |
| 325 | + if !path.exists() { | |
| 326 | + continue; | |
| 327 | + } | |
| 328 | + let mut reader = Reader::open(&path).expect("open"); | |
| 329 | + let audio = reader | |
| 330 | + .default_stream(MediaType::Audio) | |
| 331 | + .expect("audio") | |
| 332 | + .clone(); | |
| 333 | + // Gapless: what the file states it holds, less the silence it states it | |
| 334 | + // padded with, is exactly what ffmpeg decodes out of it. | |
| 335 | + if codec == "mp3" { | |
| 336 | + let padding = u64::from(audio.initial_padding); | |
| 337 | + assert!( | |
| 338 | + padding > 0, | |
| 339 | + "{name}: no encoder delay read out of the LAME tag" | |
| 340 | + ); | |
| 341 | + let stated = audio.duration.expect("an mp3 states its length") as u64; | |
| 342 | + let channels = audio.params.audio().unwrap().layout.channel_count(); | |
| 343 | + assert_eq!( | |
| 344 | + stated - padding, | |
| 345 | + ffmpeg_frames(&path, channels), | |
| 346 | + "{name}: audible frames" | |
| 347 | + ); | |
| 348 | + } | |
| 349 | + // A seek to the beginning lands on the file's own first packet, never | |
| 350 | + // past it. Asked for by that packet's own timestamp rather than by | |
| 351 | + // zero, because an mp4's first AAC packet is at -1024: its priming. | |
| 352 | + let first = loop { | |
| 353 | + let packet = reader.next_packet().expect("a first packet"); | |
| 354 | + if packet.stream == audio.index { | |
| 355 | + break packet.pts.unwrap_or(0); | |
| 356 | + } | |
| 357 | + }; | |
| 358 | + let landed = reader | |
| 359 | + .seek( | |
| 360 | + audio.index, | |
| 361 | + Timestamp::new(first, audio.time_base), | |
| 362 | + SeekMode::SyncBefore, | |
| 363 | + ) | |
| 364 | + .unwrap_or_else(|e| panic!("{name}: seek to the beginning: {e}")); | |
| 365 | + assert_eq!( | |
| 366 | + landed.ticks, first, | |
| 367 | + "{name}: a seek to the beginning landed past the first packet" | |
| 368 | + ); | |
| 369 | + checked += 1; | |
| 370 | + } | |
| 371 | + assert!( | |
| 372 | + checked > 0, | |
| 373 | + "no fixtures found — run scripts/gen-fixtures.sh" | |
| 374 | + ); | |
| 375 | +} |
shims/symphonia-core/src/formats.rsmodified+5 -0
| @@ -30,6 +30,11 @@ pub struct Track { | ||
| 30 | 30 | pub num_frames: Option<u64>, |
| 31 | 31 | /// First timestamp. |
| 32 | 32 | pub start_ts: u64, |
| 33 | + /// Samples the decoder emits before the first audible one -- an MP3's LAME | |
| 34 | + /// encoder delay, an Opus stream's pre-skip. **Not** dropped by the reader: | |
| 35 | + /// [`num_frames`](Self::num_frames) counts them, so a caller that wants the | |
| 36 | + /// audible stream skips them and takes `num_frames - delay` samples. | |
| 37 | + pub delay: Option<u64>, | |
| 33 | 38 | /// Codec and setup data. |
| 34 | 39 | pub codec_params: Option<CodecParameters>, |
| 35 | 40 | /// ISO 639 language tag, when the container carries one. |
shims/symphonia/Cargo.tomlmodified+20 -0
| @@ -14,3 +14,23 @@ symphonia-core = { path = "../symphonia-core", version = "0.6.0" } | ||
| 14 | 14 | |
| 15 | 15 | [dev-dependencies] |
| 16 | 16 | symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" } |
| 17 | + | |
| 18 | +# The incumbent's feature names, every one of them a no-op: a caller selects | |
| 19 | +# codecs and containers there, and here `ec_probe` serves all of them | |
| 20 | +# unconditionally. They are declared because a feature list is part of the | |
| 21 | +# surface a `[patch.crates-io]` entry has to answer — a consumer naming | |
| 22 | +# `features = ["mkv"]` fails to resolve otherwise, which is not a difference | |
| 23 | +# worth making it edit its manifest for. | |
| 24 | +[features] | |
| 25 | +aac = [] | |
| 26 | +alac = [] | |
| 27 | +flac = [] | |
| 28 | +id3v1 = [] | |
| 29 | +id3v2 = [] | |
| 30 | +isomp4 = [] | |
| 31 | +mkv = [] | |
| 32 | +mp3 = [] | |
| 33 | +ogg = [] | |
| 34 | +pcm = [] | |
| 35 | +vorbis = [] | |
| 36 | +wav = [] |
shims/symphonia/src/reader.rsmodified+11 -1
| @@ -35,6 +35,7 @@ impl ProbeReader { | ||
| 35 | 35 | time_base: Some(TimeBase::from(s.time_base)), |
| 36 | 36 | num_frames: s.duration.map(|d| d.max(0) as u64), |
| 37 | 37 | start_ts: s.start_time.unwrap_or(0).max(0) as u64, |
| 38 | + delay: Some(u64::from(s.initial_padding)).filter(|d| *d > 0), | |
| 38 | 39 | codec_params: Some(from_ec_parameters(&s.params)), |
| 39 | 40 | language: s.language.clone(), |
| 40 | 41 | }) |
| @@ -62,7 +63,16 @@ impl FormatReader for ProbeReader { | ||
| 62 | 63 | } |
| 63 | 64 | |
| 64 | 65 | fn default_track(&self, kind: TrackType) -> Option<&Track> { |
| 65 | - self.tracks.iter().find(|t| t.track_type == kind) | |
| 66 | + // The container's flagged track, not merely the first one of its kind: | |
| 67 | + // a dual-audio remux that marked its second track default opens in that | |
| 68 | + // language, which is what a caller asking for "the audio" means by it. | |
| 69 | + let media = match kind { | |
| 70 | + TrackType::Audio => MediaType::Audio, | |
| 71 | + TrackType::Video => MediaType::Video, | |
| 72 | + TrackType::Subtitle => MediaType::Subtitle, | |
| 73 | + }; | |
| 74 | + let index = self.inner.default_stream(media)?.index; | |
| 75 | + self.tracks.get(index as usize) | |
| 66 | 76 | } |
| 67 | 77 | |
| 68 | 78 | fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result<SeekedTo> { |