forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

lib.rs1349 lines, 49.2 KiBHistoryRawDownload
1//! Format detection and one reader for every audio file edith opens.
2//!
3//! [`Reader`] sniffs the content (never the extension — a mislabelled file is
4//! still a file), builds the right demuxer, and hands out packets with rational
5//! timestamps plus a sample-accurate [`Reader::seek`] that reports where it
6//! actually landed. [`AudioDecoder`] is the registry half: one seat for every
7//! audio codec the family carries.
8//!
9//! What this crate does *not* do is parse containers a sibling crate already
10//! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to
11//! [`ec_ogg`], and RIFF/WAVE/AVI to [`ec_riff`]; there is exactly one parser
12//! for each container family. What is implemented in [`raw`] is the three
13//! formats that are a codec and nothing else: MP3, FLAC and ADTS.
14//!
15//! Two contracts worth knowing:
16//!
17//! - **One reader, always.** Opening takes a `Read + Seek` source and never
18//! reopens it, whatever a seek does. Seeking a Matroska file a hundred times
19//! costs one file handle and one cue table.
20//! - **A track this cannot decode is listed, not hidden.** [`Reader::streams`]
21//! reports every stream the container declares and
22//! [`Reader::unsupported`] names the ones with no decoder *and why* — a
23//! DTS track says "DTS", not silence. Cover art is not a video track
24//! and never appears as one.
25
26#![forbid(unsafe_code)]
27#![warn(missing_docs)]
28
29pub mod decoder;
30mod dts;
31mod raw;
32pub mod tags;
33
34use std::collections::VecDeque;
35use std::fs::File;
36use std::io::{BufReader, Read, Seek, SeekFrom};
37use std::path::Path;
38
39use ec_core::error::{Error, Result};
40use ec_core::packet::{Buf, Packet, PacketFlags};
41use ec_core::registry::{
42 AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, SeekMode,
43 StreamInfo,
44};
45use ec_core::timebase::{Rounding, TimeBase, Timestamp};
46use ec_core::{ChannelLayout, SampleFormat};
47
48pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};
49pub use tags::Tags;
50
51/// Bytes read to sniff a format and to find the first frame of a raw stream.
52const HEAD: usize = 64 << 10;
53/// Packets a seek may look past to find one of the stream it was asked about.
54const SEEK_LOOKAHEAD: usize = 64;
55/// Samples of synthesis delay every Layer III decoder carries, on top of
56/// whatever delay the encoder wrote into the gapless tag. The number is the format
57/// 's, not this implementation's: a gapless tag is written to be read with it.
58const MP3_DECODER_DELAY: u32 = 529;
59
60/// A container (or the lack of one) this crate can open.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum Format {
63 /// RIFF/WAVE PCM.
64 Wav,
65 /// Native FLAC.
66 Flac,
67 /// MPEG-1/2/2.5 Layer III, with or without an ID3 tag.
68 Mp3,
69 /// Raw AAC in ADTS framing.
70 Adts,
71 /// Ogg: Vorbis, Opus or FLAC inside it.
72 Ogg,
73 /// Raw DTS core (with or without DTS-HD extension substreams).
74 Dts,
75 /// ISO base media: mp4, m4a, mov.
76 Mp4,
77 /// RIFF/AVI.
78 Avi,
79 /// Matroska and WebM.
80 Matroska,
81 /// Raw AMR storage format (`.amr` / `.awb`).
82 Amr,
83}
84
85impl Format {
86 /// Short lowercase name for logs and capability tables.
87 pub fn name(&self) -> &'static str {
88 match self {
89 Format::Wav => "wav",
90 Format::Flac => "flac",
91 Format::Mp3 => "mp3",
92 Format::Adts => "adts",
93 Format::Dts => "dts",
94 Format::Ogg => "ogg",
95 Format::Mp4 => "mp4",
96 Format::Matroska => "matroska",
97 Format::Avi => "avi",
98 Format::Amr => "amr",
99 }
100 }
101
102 /// Extensions that usually carry this format. Advisory only: the sniff
103 /// decides.
104 pub fn extensions(&self) -> &'static [&'static str] {
105 match self {
106 Format::Wav => &["wav", "wave"],
107 Format::Flac => &["flac"],
108 Format::Mp3 => &["mp3"],
109 Format::Adts => &["aac", "adts"],
110 Format::Dts => &["dts", "dtshd"],
111 Format::Ogg => &["ogg", "oga", "opus"],
112 Format::Mp4 => &["mp4", "m4a", "m4v", "mov"],
113 Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"],
114 Format::Avi => &["avi"],
115 Format::Amr => &["amr", "awb"],
116 }
117 }
118}
119
120/// The format `head` opens with, by content.
121///
122/// An ID3v2 tag is skipped first, because `.aac` and `.mp3` files both carry
123/// one and the format is whatever follows it.
124pub fn sniff(head: &[u8]) -> Option<Format> {
125 let at = tags::id3v2_len(head).unwrap_or(0) as usize;
126 let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head);
127 if data.len() >= 12 && &data[..4] == b"RIFF" {
128 match &data[8..12] {
129 b"WAVE" => return Some(Format::Wav),
130 b"AVI " => return Some(Format::Avi),
131 _ => {}
132 }
133 }
134 if ec_amr::container::probe(data).is_some() {
135 return Some(Format::Amr);
136 }
137 if data.starts_with(b"fLaC") {
138 return Some(Format::Flac);
139 }
140 if data.starts_with(b"OggS") {
141 return Some(Format::Ogg);
142 }
143 if ec_matroska::is_matroska(data) {
144 return Some(Format::Matroska);
145 }
146 if ec_mp4::is_mp4(data) {
147 return Some(Format::Mp4);
148 }
149 if dts_chains(data) {
150 return Some(Format::Dts);
151 }
152 // Whichever of the two framed formats starts *first*, and only where three
153 // frames chain: AAC payload bytes routinely parse as a lone MPEG audio
154 // header, which is how an `.aac` file came out an `.mp3` once.
155 for at in 0..data.len().saturating_sub(8).min(SYNC_SCAN) {
156 if data[at] != 0xFF {
157 continue;
158 }
159 for format in [Format::Adts, Format::Mp3] {
160 if chains(&data[at..], format) {
161 return Some(format);
162 }
163 }
164 }
165 None
166}
167
168/// True when `data` opens with DTS access units that chain (or run out of
169/// data first).
170fn dts_chains(data: &[u8]) -> bool {
171 let mut at = 0;
172 for _ in 0..SYNC_CHAIN {
173 match dts::access_unit(&data[at..]) {
174 Some((_, len)) => at += len,
175 None => return false,
176 }
177 if at >= data.len() {
178 return true;
179 }
180 }
181 true
182}
183
184/// Offsets a sync search looks through before giving up.
185const SYNC_SCAN: usize = 8 << 10;
186/// Consecutive frames that must parse for a sync to be believed.
187const SYNC_CHAIN: usize = 3;
188
189/// One frame's length, as its own format states it.
190fn frame_len(data: &[u8], format: Format) -> Option<usize> {
191 match format {
192 Format::Mp3 => ec_mp3::FrameHeader::parse(data).ok()?.frame_len(),
193 Format::Adts => Some(ec_aac::parse_adts(data).ok()?.frame_length),
194 _ => None,
195 }
196}
197
198/// True when [`SYNC_CHAIN`] frames of `format` chain from the head of `data`
199/// (or the data runs out first, which is as much as a head can prove).
200fn chains(data: &[u8], format: Format) -> bool {
201 let mut at = 0;
202 for _ in 0..SYNC_CHAIN {
203 match frame_len(&data[at..], format) {
204 Some(len) if len > 0 => at += len,
205 _ => return false,
206 }
207 if at >= data.len() {
208 return true;
209 }
210 }
211 true
212}
213
214/// The first offset where a frame of `format` really starts.
215fn frame_sync(data: &[u8], format: Format) -> Option<usize> {
216 (0..data.len().saturating_sub(8).min(SYNC_SCAN))
217 .find(|&at| data[at] == 0xFF && chains(&data[at..], format))
218}
219
220/// A stream nothing here decodes, and the reason.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct Unsupported {
223 /// Index in [`Reader::streams`].
224 pub stream: u32,
225 /// What the container says it is.
226 pub codec: CodecId,
227 /// Why no decoder was built, in words a user can read.
228 pub reason: String,
229}
230
231/// One open media file: streams in, packets out.
232pub struct Reader {
233 format: Format,
234 inner: Box<dyn Demuxer>,
235 tags: Tags,
236 /// Packets read ahead of the caller by a seek looking for its landing.
237 queue: VecDeque<Packet>,
238 /// Container-native track id per stream index — a Matroska `TrackNumber`,
239 /// an mp4 `track_ID`, or the index itself.
240 native: Vec<u64>,
241}
242
243impl Reader {
244 /// Open `path`, sniffing its content for the format.
245 pub fn open(path: impl AsRef<Path>) -> Result<Reader> {
246 let path = path.as_ref();
247 let hint = path.extension().and_then(|e| e.to_str()).map(str::to_owned);
248 Reader::new(BufReader::new(File::open(path)?), hint.as_deref())
249 }
250
251 /// Open an already-open source. `hint` is an extension, used only when the
252 /// content says nothing.
253 pub fn new<R: Read + Seek + Send + 'static>(mut src: R, hint: Option<&str>) -> Result<Reader> {
254 let end = src.seek(SeekFrom::End(0))?;
255 src.rewind()?;
256 let mut head = vec![0u8; HEAD.min(end as usize)];
257 read_upto(&mut src, &mut head)?;
258 let format = sniff(&head)
259 .or_else(|| {
260 let hint = hint?.to_ascii_lowercase();
261 [
262 Format::Wav,
263 Format::Flac,
264 Format::Mp3,
265 Format::Adts,
266 Format::Dts,
267 Format::Ogg,
268 Format::Mp4,
269 Format::Matroska,
270 Format::Avi,
271 Format::Amr,
272 ]
273 .into_iter()
274 .find(|f| f.extensions().contains(&hint.as_str()))
275 })
276 .ok_or_else(|| {
277 Error::unsupported(
278 "this file",
279 "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, avi, matroska, amr)",
280 )
281 })?;
282 src.rewind()?;
283 match format {
284 Format::Matroska => {
285 let demuxer = ec_matroska::MatroskaDemuxer::new(src)?;
286 let native = demuxer
287 .streams()
288 .iter()
289 .map(|s| demuxer.track_number(s.index).unwrap_or(u64::from(s.index)))
290 .collect();
291 Ok(Reader::wrap(
292 format,
293 Box::new(demuxer),
294 Tags::default(),
295 native,
296 ))
297 }
298 Format::Mp4 => {
299 let demuxer = ec_mp4::Mp4Demuxer::new(src)?;
300 let tags = Tags {
301 title: demuxer.title().map(str::to_owned),
302 ..Tags::default()
303 };
304 let native = (0..demuxer.streams().len() as u64).collect();
305 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
306 }
307 Format::Ogg => {
308 let demuxer = ec_ogg::OggDemuxer::open(src)?;
309 // Vorbis carries its comment packet inside the header triplet
310 // this crate publishes as extradata; Opus does not publish its
311 // tags packet at all, so an `.opus` file reports none.
312 let tags = demuxer
313 .streams()
314 .iter()
315 .find(|s| s.params.codec == CodecId::Vorbis)
316 .and_then(|s| s.params.extradata.as_deref())
317 .and_then(|data| ec_ogg::xiph_unlace(data).ok())
318 .and_then(|packets| packets.get(1).map(|p| tags::from_vorbis_comment(&p[7..])))
319 .unwrap_or_default();
320 let native = (0..demuxer.streams().len() as u64).collect();
321 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
322 }
323 Format::Wav => open_wav(src, end),
324 Format::Avi => open_avi(src),
325 Format::Amr => {
326 let demuxer = ec_amr::container::AmrDemuxer::new(src)?;
327 Ok(Reader::wrap(format, Box::new(demuxer), Tags::default(), vec![0]))
328 }
329 Format::Flac => open_flac(src, &head, end),
330 Format::Mp3 => open_mp3(src, &head, end),
331 Format::Adts => open_adts(src, &head, end),
332 Format::Dts => open_dts(src, end),
333 }
334 }
335
336 fn wrap(format: Format, inner: Box<dyn Demuxer>, tags: Tags, native: Vec<u64>) -> Reader {
337 Reader {
338 format,
339 inner,
340 tags,
341 queue: VecDeque::new(),
342 native,
343 }
344 }
345
346 /// Which format the content turned out to be.
347 pub fn format(&self) -> Format {
348 self.format
349 }
350
351 /// Every stream the container declares, decodable or not.
352 pub fn streams(&self) -> &[StreamInfo] {
353 self.inner.streams()
354 }
355
356 /// The stream of `kind` a caller that just wants "the audio" means: the one
357 /// the container flagged ([`StreamInfo::default`]), and the first of that
358 /// kind where nothing is flagged.
359 ///
360 /// The flag comes first because it is the whole answer to which language a
361 /// dual-audio remux opens in -- a muxer that put the French track second
362 /// and marked it default meant the French one, and file order would play
363 /// the other.
364 pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> {
365 let of_kind = || {
366 self.streams()
367 .iter()
368 .filter(move |s| s.params.codec.media_type() == kind)
369 };
370 of_kind().find(|s| s.default).or_else(|| of_kind().next())
371 }
372
373 /// The container's own id for a stream: a Matroska `TrackNumber`, which is
374 /// how a caller names one language of a dual-audio file.
375 pub fn native_id(&self, stream: u32) -> u64 {
376 self.native
377 .get(stream as usize)
378 .copied()
379 .unwrap_or(u64::from(stream))
380 }
381
382 /// The stream index carrying container-native id `id`.
383 pub fn stream_of_native(&self, id: u64) -> Option<u32> {
384 self.native.iter().position(|&n| n == id).map(|i| i as u32)
385 }
386
387 /// What the file says about itself. Empty for a file with no tags, and for
388 /// the formats [`tags`] does not read.
389 pub fn tags(&self) -> &Tags {
390 &self.tags
391 }
392
393 /// The longest stream's duration, when any stream states or implies one.
394 ///
395 /// What a player would play: [`StreamInfo::initial_padding`] is off it,
396 /// because an MP3's encoder delay is silence the file carries and nobody
397 /// hears.
398 pub fn duration(&self) -> Option<Timestamp> {
399 self.streams()
400 .iter()
401 .filter_map(|s| {
402 s.duration.map(|d| {
403 // `initial_padding` is a sample count, not a `time_base`
404 // tick count — the two only coincide when the stream's
405 // time base happens to be `1/sample_rate`, which a
406 // container's own duration field usually is not.
407 let padding_ticks = s
408 .params
409 .audio()
410 .filter(|_| s.initial_padding > 0)
411 .map(|a| {
412 TimeBase::from_rate(a.sample_rate).rescale(
413 i64::from(s.initial_padding),
414 s.time_base,
415 Rounding::Down,
416 )
417 })
418 .unwrap_or(0);
419 Timestamp::new(d - padding_ticks, s.time_base)
420 })
421 })
422 .max_by(|a, b| {
423 a.as_secs_f64()
424 .partial_cmp(&b.as_secs_f64())
425 .unwrap_or(std::cmp::Ordering::Equal)
426 })
427 }
428
429 /// Every audio stream with no decoder behind it, and why.
430 ///
431 /// Non-audio streams are not listed: this is an audio probe, and a file's
432 /// picture is another crate's business.
433 pub fn unsupported(&self) -> Vec<Unsupported> {
434 self.streams()
435 .iter()
436 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
437 .filter_map(|s| match AudioDecoder::new(&s.params) {
438 Ok(_) => None,
439 Err(e) => Some(Unsupported {
440 stream: s.index,
441 codec: s.params.codec,
442 reason: e.to_string(),
443 }),
444 })
445 .collect()
446 }
447
448 /// A decoder for one stream.
449 pub fn make_decoder(&self, stream: u32) -> Result<AudioDecoder> {
450 let info = self
451 .streams()
452 .iter()
453 .find(|s| s.index == stream)
454 .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
455 AudioDecoder::new(&info.params)
456 }
457
458 /// The next packet in storage order, or [`Error::Eof`].
459 pub fn next_packet(&mut self) -> Result<Packet> {
460 match self.queue.pop_front() {
461 Some(packet) => Ok(packet),
462 None => self.inner.next_packet(),
463 }
464 }
465
466 /// Seek `stream` to `to` and answer where the reader actually landed.
467 ///
468 /// The landing is the next packet's own timestamp, so a caller can tell
469 /// how far ahead of (or behind) its target the container put it — which is
470 /// the number a sample-accurate segment start is trimmed against. Nothing
471 /// is reopened and no packet is dropped: packets of other streams read on
472 /// the way to the landing are queued, not discarded.
473 pub fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<Timestamp> {
474 self.queue.clear();
475 self.inner.seek(stream, to, mode)?;
476 let base = self
477 .streams()
478 .iter()
479 .find(|s| s.index == stream)
480 .map(|s| s.time_base)
481 .unwrap_or(TimeBase::MILLIS);
482 for _ in 0..SEEK_LOOKAHEAD {
483 let packet = match self.inner.next_packet() {
484 Ok(packet) => packet,
485 // Seeking past the end lands at the end; the target is as good
486 // an answer as any and the next read says `Eof`.
487 Err(e) if e.is_eof() => return Ok(to.rescale(base, Rounding::Down)),
488 Err(e) => return Err(e),
489 };
490 let hit = packet.stream == stream;
491 let pts = packet.pts;
492 self.queue.push_back(packet);
493 if hit {
494 return Ok(Timestamp::new(pts.unwrap_or(0), base));
495 }
496 }
497 Ok(to.rescale(base, Rounding::Down))
498 }
499}
500
501impl std::fmt::Debug for Reader {
502 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
503 f.debug_struct("Reader")
504 .field("format", &self.format.name())
505 .field("streams", &self.streams().len())
506 .finish()
507 }
508}
509
510/// Read until `buf` is full or the source ends; answers how much arrived.
511fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
512 let mut at = 0;
513 while at < buf.len() {
514 match r.read(&mut buf[at..]) {
515 Ok(0) => break,
516 Ok(n) => at += n,
517 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
518 Err(e) => return Err(Error::Io(e)),
519 }
520 }
521 Ok(at)
522}
523
524/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a
525/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the
526/// `0x2001` format tag that says so outright. The chunk walk is the file's
527/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle.
528fn wav_dts_span<R: Read + Seek>(src: &mut R, end: u64) -> Result<Option<(u64, u64)>> {
529 let mut at = 12u64;
530 while at + 8 <= end {
531 src.seek(SeekFrom::Start(at))?;
532 let mut h = [0u8; 8];
533 if read_upto(src, &mut h)? < 8 {
534 break;
535 }
536 let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]]));
537 let body = at + 8;
538 if &h[..4] == b"data" {
539 // A streamed writer's placeholder size means the file is the bound.
540 let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end {
541 end
542 } else {
543 body + size
544 };
545 let mut window = vec![0u8; HEAD.min((stop - body) as usize)];
546 src.seek(SeekFrom::Start(body))?;
547 let got = read_upto(src, &mut window)?;
548 window.truncate(got);
549 return Ok(dts_chains(&window).then_some((body, stop)));
550 }
551 at = body + size + (size & 1);
552 }
553 Ok(None)
554}
555
556fn open_dts_span<R: Read + Seek + Send + 'static>(
557 mut src: R,
558 format: Format,
559 start: u64,
560 end: u64,
561) -> Result<Reader> {
562 let mut window = vec![0u8; HEAD.min((end - start) as usize)];
563 src.seek(SeekFrom::Start(start))?;
564 let got = read_upto(&mut src, &mut window)?;
565 window.truncate(got);
566 let (core, _) = dts::access_unit(&window)
567 .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?;
568 let total = dts_total(&window, end, start);
569 let demuxer = raw::RawDemuxer::new(
570 src,
571 raw::Kind::Dts,
572 raw::dts_parameters(&core),
573 start,
574 end,
575 total,
576 None,
577 )?;
578 Ok(Reader::wrap(
579 format,
580 Box::new(demuxer),
581 Tags::default(),
582 vec![0],
583 ))
584}
585
586fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
587 if let Some((start, stop)) = wav_dts_span(&mut src, end)? {
588 return open_dts_span(src, Format::Wav, start, stop);
589 }
590 src.rewind()?;
591 let (spec, frames, compressed) = {
592 let reader = ec_riff::WavReader::new(&mut src)?;
593 (reader.spec(), reader.duration(), reader.compressed().cloned())
594 };
595 let start = src.stream_position()?;
596 if let Some(c) = compressed {
597 let (params, kind) = raw::wav_compressed_parameters(spec, &c)?;
598 let bytes_per = match kind {
599 raw::Kind::WavBlocks { block, samples } => (block as u64, samples),
600 _ => (u64::from(spec.channels.max(1)), 1),
601 };
602 let audio_end = frames
603 .map(|n| start + n / bytes_per.1 * bytes_per.0)
604 .unwrap_or(end)
605 .min(end);
606 let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1));
607 let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?;
608 return Ok(Reader::wrap(
609 Format::Wav,
610 Box::new(demuxer),
611 Tags::default(),
612 vec![0],
613 ));
614 }
615 let (params, block_align) = raw::wav_parameters(spec)?;
616 // A `data` size the header did not state (a streamed writer's placeholder)
617 // means the file itself is the bound.
618 let audio_end = frames
619 .map(|n| start + n * block_align as u64)
620 .unwrap_or(end)
621 .min(end);
622 let total = frames.or(Some((audio_end - start) / block_align as u64));
623 let demuxer = raw::RawDemuxer::new(
624 src,
625 raw::Kind::Wav { block_align },
626 params,
627 start,
628 audio_end,
629 total,
630 None,
631 )?;
632 Ok(Reader::wrap(
633 Format::Wav,
634 Box::new(demuxer),
635 Tags::default(),
636 vec![0],
637 ))
638}
639
640fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
641 let base = tags::id3v2_len(head).unwrap_or(0);
642 src.seek(SeekFrom::Start(base))?;
643 let mut magic = [0u8; 4];
644 read_upto(&mut src, &mut magic)?;
645 if &magic != b"fLaC" {
646 return Err(Error::corrupt("FLAC: no stream marker"));
647 }
648 let mut info: Option<ec_flac::StreamInfo> = None;
649 let mut tags = Tags::default();
650 let mut at = base + 4;
651 loop {
652 let mut header = [0u8; 4];
653 if read_upto(&mut src, &mut header)? < 4 {
654 return Err(Error::corrupt("FLAC: metadata ended before any frame"));
655 }
656 let last = header[0] & 0x80 != 0;
657 let kind = header[0] & 0x7f;
658 let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])).min(1 << 24);
659 let mut body = vec![0u8; len as usize];
660 read_upto(&mut src, &mut body)?;
661 at += 4 + len;
662 match kind {
663 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
664 4 => tags.merge(tags::from_vorbis_comment(&body)),
665 _ => {}
666 }
667 if last {
668 break;
669 }
670 }
671 let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
672 let params = ec_flac::codec_parameters(&info);
673 let total = match info.total_samples {
674 0 => None,
675 n => Some(n),
676 };
677 let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
678 Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
679}
680
681fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
682 let (start, tags) = id3(&mut src, head, end)?;
683 let mut window = vec![0u8; HEAD.min((end - start) as usize)];
684 src.seek(SeekFrom::Start(start))?;
685 let got = read_upto(&mut src, &mut window)?;
686 window.truncate(got);
687 let at = frame_sync(&window, Format::Mp3)
688 .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
689 let header = ec_mp3::FrameHeader::parse(&window[at..])?;
690 let mut start = start + at as u64;
691 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
692 // A Xing/Info header states the frame count exactly; without one the
693 // duration is the bitrate estimate the oracle also falls back to, which is
694 // right for CBR and approximate for VBR.
695 let per_frame = header.samples_per_frame() as u64;
696 let xing = xing_frames(&window[at..], &header);
697 if xing.is_some() {
698 // The Xing frame carries no audio — it is a header wearing a frame's
699 // clothes, and a decoder handed it emits a granule of silence. Both
700 // the oracle and this reader start after it.
701 start += header.frame_len().unwrap_or(0) as u64;
702 }
703 // Gapless, as the gapless tag states it: a decoder emits the encoder delay
704 // plus its own 529 samples of Layer III synthesis delay before the first
705 // sample that was ever recorded, and the file runs `padding` samples past
706 // the last one. Both are silence a player must not play, and a file with no
707 // tag has neither — its frames are all there is to go on.
708 let (padding, total) = match &xing {
709 Some(x) => (
710 x.delay + MP3_DECODER_DELAY,
711 Some(x.frames * per_frame - u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))),
712 ),
713 None => (
714 0,
715 header
716 .frame_len()
717 .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)),
718 ),
719 };
720 let demuxer = raw::RawDemuxer::new(
721 src,
722 raw::Kind::Mp3,
723 raw::mp3_parameters(&header),
724 start,
725 audio_end,
726 total,
727 None,
728 )?
729 .with_initial_padding(padding);
730 Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
731}
732
733fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
734 let (start, tags) = id3(&mut src, head, end)?;
735 let mut window = vec![0u8; HEAD.min((end - start) as usize)];
736 src.seek(SeekFrom::Start(start))?;
737 let got = read_upto(&mut src, &mut window)?;
738 window.truncate(got);
739 let at = frame_sync(&window, Format::Adts)
740 .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
741 let header = ec_aac::parse_adts(&window[at..])?;
742 let start = start + at as u64;
743 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
744 // ADTS states no duration anywhere: every frame is 1024 samples, so the
745 // file's size over its *average* frame is the estimate — the same one
746 // the oracle prints "estimating duration from bitrate" about. Averaged rather
747 // than taken off the first frame, which on a real encode is nothing like
748 // the mean (a 3-second fixture came out 5 seconds long that way).
749 let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
750 while count < 512 {
751 let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
752 break;
753 };
754 if h.frame_length == 0 || walk + h.frame_length > window.len() {
755 break;
756 }
757 sum += h.frame_length as u64;
758 count += 1;
759 walk += h.frame_length;
760 }
761 let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
762 let demuxer = raw::RawDemuxer::new(
763 src,
764 raw::Kind::Adts,
765 raw::adts_parameters(&header),
766 start,
767 audio_end,
768 total,
769 None,
770 )?;
771 Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
772}
773
774fn open_dts<R: Read + Seek + Send + 'static>(src: R, end: u64) -> Result<Reader> {
775 open_dts_span(src, Format::Dts, 0, end)
776}
777
778/// Duration estimate in samples: the span's size over the mean access unit
779/// of the head window.
780fn dts_total(window: &[u8], end: u64, start: u64) -> Option<u64> {
781 let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize);
782 while sum < (1 << 20) {
783 let Some((core, len)) = dts::access_unit(window.get(at..)?) else {
784 break;
785 };
786 if at + len > window.len() {
787 break;
788 }
789 sum += len as u64;
790 samples += u64::from(core.samples);
791 at += len;
792 }
793 (sum > 0).then(|| (end - start) * samples / sum)
794}
795
796fn open_avi<R: Read + Seek + Send + 'static>(src: R) -> Result<Reader> {
797 let reader = ec_riff::AviReader::new(src)?;
798 let demuxer = AviDemuxer::new(reader)?;
799 let native = demuxer
800 .stream_numbers
801 .iter()
802 .map(|&n| u64::from(n))
803 .collect();
804 Ok(Reader::wrap(
805 Format::Avi,
806 Box::new(demuxer),
807 Tags::default(),
808 native,
809 ))
810}
811
812struct AviDemuxer<R> {
813 reader: ec_riff::AviReader<R>,
814 streams: Vec<StreamInfo>,
815 stream_numbers: Vec<u32>,
816 samples: Vec<u64>,
817 pending: VecDeque<Packet>,
818 carry: Vec<Vec<u8>>,
819 sync_bias: Vec<u64>,
820 seek_anchor: Vec<Option<(u64, bool)>>,
821}
822
823impl<R: Read + Seek> AviDemuxer<R> {
824 fn new(mut reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> {
825 let mut streams = Vec::new();
826 let mut stream_numbers = Vec::new();
827 for (index, s) in reader.audio_streams().iter().enumerate() {
828 let codec = match s.format_tag {
829 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8,
830 0x0001 => CodecId::PcmS16Le,
831 0x0055 => CodecId::Mp3,
832 0x00ff => CodecId::Aac,
833 0x2000 => CodecId::Ac3,
834 0x0011 | 0x0002 | 0x0006 | 0x0007 => {
835 ec_riff::WavCompressed::codec_of(s.format_tag).unwrap_or(CodecId::PcmAlaw)
836 }
837 tag => {
838 return Err(Error::unsupported(
839 format!("AVI audio format tag {tag:#06x}"),
840 "no decoder for it exists in this family yet",
841 ));
842 }
843 };
844 let mut params = CodecParameters::new(codec);
845 params.media = MediaParameters::Audio(AudioParameters {
846 sample_rate: s.sample_rate,
847 layout: ChannelLayout::from_count(usize::from(s.channels).max(1)),
848 format: match codec {
849 CodecId::PcmU8 => Some(SampleFormat::U8),
850 CodecId::PcmS16Le => Some(SampleFormat::S16),
851 CodecId::ImaAdpcmWav
852 | CodecId::MsAdpcm
853 | CodecId::PcmAlaw
854 | CodecId::PcmMulaw => Some(SampleFormat::S16),
855 _ => None,
856 },
857 bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)),
858 });
859 let extra = reader.audio_extradata(index);
860 if !extra.is_empty() && matches!(codec, CodecId::ImaAdpcmWav | CodecId::MsAdpcm) {
861 params.extradata = Some(Buf::copy_from_slice(extra));
862 }
863 let mut info = StreamInfo::new(
864 index as u32,
865 TimeBase::from_rate(s.sample_rate.max(1)),
866 params,
867 );
868 if s.length > 0 {
869 info.duration = Some(avi_units_to_samples(*s, u64::from(s.length)) as i64);
870 }
871 streams.push(info);
872 stream_numbers.push(s.index);
873 }
874 if streams.is_empty() {
875 return Err(Error::unsupported(
876 "this AVI file",
877 "it declares no audio stream this reader can hand out",
878 ));
879 }
880 let samples = vec![0; streams.len()];
881 let carry = vec![Vec::new(); streams.len()];
882 let seek_anchor = vec![None; streams.len()];
883 let sync_bias = avi_sync_biases(&mut reader, &streams, &stream_numbers)?;
884 reader.rewind();
885 Ok(AviDemuxer {
886 reader,
887 streams,
888 stream_numbers,
889 samples,
890 pending: VecDeque::new(),
891 carry,
892 sync_bias,
893 seek_anchor,
894 })
895 }
896
897 fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> {
898 let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else {
899 return Ok(());
900 };
901 let codec = self.streams[stream].params.codec;
902 match codec {
903 CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac => {
904 self.queue_elementary_chunk(stream, chunk.data, codec)
905 }
906 CodecId::ImaAdpcmWav | CodecId::MsAdpcm => {
907 // One decodable block per packet.
908 let avi = self.reader.audio_streams().get(stream).copied();
909 let (ba, ch) = avi.map_or((0usize, 1u32), |s| {
910 (usize::from(s.block_align), u32::from(s.channels.max(1)))
911 });
912 let spb = ec_riff::WavCompressed::new(
913 avi.map_or(0, |s| s.format_tag),
914 ch as u16,
915 ba as u16,
916 &[],
917 )
918 .map_or(0, |c| u64::from(c.samples_per_block));
919 if ba == 0 || spb == 0 {
920 return Ok(());
921 }
922 for block in chunk.data.chunks(ba).filter(|b| b.len() == ba) {
923 self.push_packet(stream, Buf::copy_from_slice(block), spb);
924 }
925 Ok(())
926 }
927 CodecId::PcmAlaw | CodecId::PcmMulaw => {
928 let ch = self
929 .reader
930 .audio_streams()
931 .get(stream)
932 .map_or(1usize, |s| usize::from(s.channels.max(1)));
933 let frames = (chunk.data.len() / ch) as u64;
934 self.push_packet(stream, Buf::from_vec(chunk.data), frames);
935 Ok(())
936 }
937 _ => {
938 let frames = match codec {
939 CodecId::PcmU8 | CodecId::PcmS16Le => {
940 let block = self
941 .reader
942 .audio_streams()
943 .get(stream)
944 .map_or(1usize, |s| usize::from(s.block_align).max(1));
945 (chunk.data.len() / block) as u64
946 }
947 _ => 0,
948 };
949 self.push_packet(stream, Buf::from_vec(chunk.data), frames);
950 Ok(())
951 }
952 }
953 }
954
955 fn queue_elementary_chunk(
956 &mut self,
957 stream: usize,
958 chunk: Vec<u8>,
959 codec: CodecId,
960 ) -> Result<()> {
961 let avi_stream = self
962 .stream_numbers
963 .get(stream)
964 .and_then(|n| self.reader.audio_streams().iter().find(|s| s.index == *n))
965 .copied();
966 let mut data = std::mem::take(&mut self.carry[stream]);
967 data.extend_from_slice(&chunk);
968 let mut at = 0usize;
969 let mut skipped = 0usize;
970 while at < data.len() {
971 match avi_elementary_frame(codec, &data[at..]) {
972 Ok(Some((size, frames))) if at + size <= data.len() => {
973 if skipped > 0
974 && matches!(codec, CodecId::Ac3 | CodecId::EAc3)
975 && ec_ac3::Ac3Decoder::new()
976 .decode_frame(&data[at..at + size])
977 .is_err()
978 {
979 at += 1;
980 skipped += 1;
981 continue;
982 }
983 if skipped > 0 {
984 if let Some(s) = avi_stream {
985 let skipped_samples = avi_units_to_samples(s, skipped as u64);
986 let initial = self.sync_bias.get(stream).copied().unwrap_or(0);
987 if self.samples[stream] != 0 || skipped_samples > initial {
988 self.samples[stream] =
989 self.samples[stream].saturating_add(skipped_samples);
990 }
991 }
992 skipped = 0;
993 }
994 if let Some((anchor, after)) = self.seek_anchor[stream].take() {
995 let phase = self.sync_bias.get(stream).copied().unwrap_or(0);
996 let relative = anchor.saturating_sub(phase);
997 let steps = if after {
998 relative.saturating_add(frames.saturating_sub(1)) / frames
999 } else {
1000 relative / frames
1001 };
1002 self.samples[stream] = phase.saturating_add(steps.saturating_mul(frames));
1003 }
1004 self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames);
1005 at += size;
1006 }
1007 Ok(Some(_)) => break,
1008 Ok(None) => {
1009 at += 1;
1010 skipped += 1;
1011 }
1012 Err(e) if e.is_need_more() => break,
1013 Err(_) => {
1014 at += 1;
1015 skipped += 1;
1016 }
1017 }
1018 }
1019 self.carry[stream].extend_from_slice(&data[at..]);
1020 Ok(())
1021 }
1022
1023 fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) {
1024 let base = self.streams[stream].time_base;
1025 let pts = self.samples[stream];
1026 self.samples[stream] = self.samples[stream].saturating_add(frames);
1027 let mut packet = Packet::new(stream as u32, base, data);
1028 packet.pts = Some(pts as i64);
1029 packet.dts = Some(pts as i64);
1030 packet.duration = Some(frames as i64);
1031 packet.flags = PacketFlags {
1032 keyframe: true,
1033 ..PacketFlags::default()
1034 };
1035 self.pending.push_back(packet);
1036 }
1037}
1038fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result<Option<(usize, u64)>> {
1039 match codec {
1040 CodecId::Ac3 | CodecId::EAc3 => {
1041 if data.len() < 2 {
1042 return Err(Error::NeedMore);
1043 }
1044 if data[0] != 0x0b || data[1] != 0x77 {
1045 return Ok(None);
1046 }
1047 ec_ac3::frame_size(data).map(|size| {
1048 if data.len() >= size + 2 && data[size..size + 2] != [0x0b, 0x77] {
1049 None
1050 } else {
1051 Some((size, 1536))
1052 }
1053 })
1054 }
1055 CodecId::Mp3 => {
1056 if data.len() < 2 {
1057 return Err(Error::NeedMore);
1058 }
1059 if data[0] != 0xff || data[1] & 0xe0 != 0xe0 {
1060 return Ok(None);
1061 }
1062 let header = ec_mp3::FrameHeader::parse(data)?;
1063 if header.layer != 3 {
1064 return Ok(None);
1065 }
1066 Ok(header
1067 .frame_len()
1068 .map(|size| (size, header.samples_per_frame() as u64)))
1069 }
1070 CodecId::Aac => {
1071 if data.len() < 2 {
1072 return Err(Error::NeedMore);
1073 }
1074 if !ec_aac::is_adts(data) {
1075 return Ok(None);
1076 }
1077 let header = ec_aac::parse_adts(data)?;
1078 Ok(Some((
1079 header.frame_length,
1080 (u64::from(header.raw_blocks) + 1) * ec_aac::FRAME_LEN as u64,
1081 )))
1082 }
1083 _ => Ok(None),
1084 }
1085}
1086
1087fn avi_sync_biases<R: Read + Seek>(
1088 reader: &mut ec_riff::AviReader<R>,
1089 streams: &[StreamInfo],
1090 stream_numbers: &[u32],
1091) -> Result<Vec<u64>> {
1092 let mut out = vec![0; streams.len()];
1093 for (i, info) in streams.iter().enumerate() {
1094 if !matches!(
1095 info.params.codec,
1096 CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac
1097 ) {
1098 continue;
1099 }
1100 let Some(&native) = stream_numbers.get(i) else {
1101 continue;
1102 };
1103 let Some(avi_stream) = reader
1104 .audio_streams()
1105 .iter()
1106 .find(|s| s.index == native)
1107 .copied()
1108 else {
1109 continue;
1110 };
1111 reader.seek_to_stream_time(native, 0, false)?;
1112 for _ in 0..16 {
1113 let chunk = match reader.next_packet() {
1114 Ok(chunk) => chunk,
1115 Err(e) if e.is_eof() => break,
1116 Err(e) => return Err(e),
1117 };
1118 if chunk.stream != native {
1119 continue;
1120 }
1121 let skip = avi_elementary_leading_skip(info.params.codec, &chunk.data);
1122 out[i] = avi_units_to_samples(avi_stream, skip as u64);
1123 break;
1124 }
1125 }
1126 Ok(out)
1127}
1128
1129fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize {
1130 for at in 0..data.len() {
1131 match avi_elementary_frame(codec, &data[at..]) {
1132 Ok(Some((size, _))) if at + size <= data.len() => return at,
1133 Ok(Some(_)) | Err(Error::NeedMore) => return at,
1134 Ok(None) | Err(_) => {}
1135 }
1136 }
1137 0
1138}
1139
1140fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64, round_up: bool) -> u64 {
1141 let scale = u128::from(stream.scale.max(1));
1142 let rate = u128::from(stream.rate.max(1));
1143 let sample_rate = u128::from(stream.sample_rate.max(1));
1144 let denominator = scale * sample_rate;
1145 let numerator = u128::from(samples).saturating_mul(rate);
1146 let units = if round_up {
1147 numerator.saturating_add(denominator.saturating_sub(1)) / denominator
1148 } else {
1149 numerator / denominator
1150 };
1151 let units = units.min(u128::from(u64::MAX)) as u64;
1152 match stream.length {
1153 0 => units,
1154 n => units.min(u64::from(n)),
1155 }
1156}
1157fn avi_units_to_samples(stream: ec_riff::AviAudioStream, units: u64) -> u64 {
1158 let n = u128::from(units)
1159 .saturating_mul(u128::from(stream.scale.max(1)))
1160 .saturating_mul(u128::from(stream.sample_rate.max(1)));
1161 (n / u128::from(stream.rate.max(1))).min(u128::from(u64::MAX)) as u64
1162}
1163
1164impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
1165 fn streams(&self) -> &[StreamInfo] {
1166 &self.streams
1167 }
1168
1169 fn next_packet(&mut self) -> Result<Packet> {
1170 loop {
1171 if let Some(packet) = self.pending.pop_front() {
1172 return Ok(packet);
1173 }
1174 match self.reader.next_packet() {
1175 Ok(chunk) => self.queue_chunk(chunk)?,
1176 Err(e) if e.is_eof() => return Err(Error::Eof),
1177 Err(e) => return Err(e),
1178 }
1179 }
1180 }
1181
1182 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1183 let local = self
1184 .streams
1185 .iter()
1186 .position(|s| s.index == stream)
1187 .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
1188 let avi_stream_no = self.stream_numbers[local];
1189 let avi_stream = *self
1190 .reader
1191 .audio_streams()
1192 .iter()
1193 .find(|s| s.index == avi_stream_no)
1194 .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?;
1195 let base = self.streams[local].time_base;
1196 let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64;
1197 let seek_units = samples_to_avi_units(
1198 avi_stream,
1199 target_samples,
1200 matches!(mode, SeekMode::SyncAfter),
1201 );
1202 let landed_units = self.reader.seek_to_stream_time(
1203 avi_stream_no,
1204 seek_units,
1205 matches!(mode, SeekMode::SyncAfter),
1206 )?;
1207 self.pending.clear();
1208 for carry in &mut self.carry {
1209 carry.clear();
1210 }
1211 self.samples[local] = avi_units_to_samples(avi_stream, landed_units)
1212 .saturating_sub(self.sync_bias.get(local).copied().unwrap_or(0));
1213 self.seek_anchor[local] = Some((
1214 avi_units_to_samples(avi_stream, seek_units),
1215 matches!(mode, SeekMode::SyncAfter),
1216 ));
1217 Ok(())
1218 }
1219}
1220
1221/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
1222fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
1223 let mut tags = Tags::default();
1224 let start = match tags::id3v2_len(head) {
1225 Some(len) => {
1226 let len = len.min(end);
1227 let mut tag = vec![0u8; len as usize];
1228 src.rewind()?;
1229 read_upto(src, &mut tag)?;
1230 tags.merge(tags::from_id3v2(&tag));
1231 len
1232 }
1233 None => 0,
1234 };
1235 // The v1 block at the end fills in what v2 did not say.
1236 if end >= 128 {
1237 src.seek(SeekFrom::Start(end - 128))?;
1238 let mut tail = [0u8; 128];
1239 read_upto(src, &mut tail)?;
1240 tags.merge(tags::from_id3v1(&tail));
1241 }
1242 Ok((start, tags))
1243}
1244
1245/// Bytes of ID3v1 at the end of a stream, which are not audio.
1246fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
1247 if end < 128 {
1248 return Ok(0);
1249 }
1250 src.seek(SeekFrom::Start(end - 128))?;
1251 let mut tail = [0u8; 3];
1252 read_upto(src, &mut tail)?;
1253 Ok(u64::from(&tail == b"TAG") * 128)
1254}
1255
1256/// The frame count a Xing/Info header states, when the first frame carries one.
1257fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> {
1258 let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
1259 let tag = frame.get(at..at + 8)?;
1260 if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
1261 return None;
1262 }
1263 let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
1264 if flags & 1 == 0 {
1265 return None;
1266 }
1267 let n = frame.get(at + 8..at + 12)?;
1268 let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]));
1269 // The gapless extension sits behind whichever optional fields the flags
1270 // claimed -- frame count, byte count, the 100-byte seek table, quality --
1271 // and states the two trims 21 bytes into itself, twelve bits each.
1272 let mut extension_at = at + 12;
1273 extension_at += usize::from(flags & 2 != 0) * 4;
1274 extension_at += usize::from(flags & 4 != 0) * 100;
1275 extension_at += usize::from(flags & 8 != 0) * 4;
1276 let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) {
1277 Some(&[a, b, c]) => (
1278 u32::from(a) << 4 | u32::from(b) >> 4,
1279 (u32::from(b) & 0xF) << 8 | u32::from(c),
1280 ),
1281 _ => (0, 0),
1282 };
1283 Some(Xing {
1284 frames,
1285 delay,
1286 padding,
1287 })
1288}
1289
1290/// What an MP3's Xing/Info header states: how long the file is, and the two
1291/// silences the encoder had to add to make whole frames of it.
1292struct Xing {
1293 /// Audio frames in the file, the header frame itself excluded.
1294 frames: u64,
1295 /// Encoder delay: samples of silence in front of the first real one.
1296 delay: u32,
1297 /// Encoder padding: samples of silence after the last real one.
1298 padding: u32,
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303 use super::*;
1304
1305 #[test]
1306 fn magic_numbers_name_their_formats() {
1307 assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some(Format::Wav));
1308 assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some(Format::Flac));
1309 assert_eq!(sniff(b"OggS\0\x02\0\0"), Some(Format::Ogg));
1310 assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x01\0\0\0"), Some(Format::Matroska));
1311 assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\x02\0"), Some(Format::Mp4));
1312 // MPEG-1 Layer III, 128 kbit/s, 44.1 kHz.
1313 assert_eq!(sniff(b"\xff\xfb\x90\x00\0\0\0\0\0\0"), Some(Format::Mp3));
1314 // ADTS: same sync word, the layer bits MPEG audio reserves.
1315 assert_eq!(
1316 sniff(b"\xff\xf1\x50\x80\x01\x7f\xfc\0\0\0"),
1317 Some(Format::Adts)
1318 );
1319 assert_eq!(sniff(b"not a media file at all"), None);
1320 }
1321
1322 /// `initial_padding` is a *sample* count while a stream's `duration` is in
1323 /// `time_base` ticks -- for a Matroska file whose `TimestampScale` is not
1324 /// `1/sample_rate` (the common case: ticks are milliseconds), subtracting
1325 /// one from the other unconverted lopped a third off an AAC track's
1326 /// stated length (3.021 s of `CodecDelay`-bearing audio reported as 1.997
1327 /// s: `1024` samples read straight off as `1024` one-millisecond ticks).
1328 #[test]
1329 fn duration_converts_initial_padding_out_of_sample_units() {
1330 let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1331 .join("../../fixtures/audio/aac-mka-stereo-48000.mka");
1332 if !path.exists() {
1333 return; // fixtures are generated, not checked in
1334 }
1335 let reader = Reader::open(&path).unwrap();
1336 let d = reader.duration().expect("a stated duration").as_secs_f64();
1337 assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s");
1338 }
1339
1340 /// An `.aac` or `.mp3` that opens with a tag is still an `.aac` or `.mp3`.
1341 #[test]
1342 fn an_id3_tag_does_not_hide_the_format() {
1343 let mut file = b"ID3\x03\x00\x00\x00\x00\x00\x0a".to_vec();
1344 file.extend_from_slice(&[0u8; 10]);
1345 file.extend_from_slice(b"\xff\xfb\x90\x00\0\0\0\0\0\0");
1346 assert_eq!(tags::id3v2_len(&file), Some(20));
1347 assert_eq!(sniff(&file), Some(Format::Mp3));
1348 }
1349}