forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.5 MiBb0cfde8Tahinli12 hours ago4261 commits

lib.rs1346 lines, 49.1 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| {
319 packets
320 .get(1)
321 .and_then(|p| p.get(7..))
322 .map(tags::from_vorbis_comment)
323 })
324 .unwrap_or_default();
325 let native = (0..demuxer.streams().len() as u64).collect();
326 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
327 }
328 Format::Wav => open_wav(src, end),
329 Format::Avi => open_avi(src),
330 Format::Amr => {
331 let demuxer = ec_amr::container::AmrDemuxer::new(src)?;
332 Ok(Reader::wrap(format, Box::new(demuxer), Tags::default(), vec![0]))
333 }
334 Format::Flac => open_flac(src, &head, end),
335 Format::Mp3 => open_mp3(src, &head, end),
336 Format::Adts => open_adts(src, &head, end),
337 Format::Dts => open_dts(src, end),
338 }
339 }
340
341 fn wrap(format: Format, inner: Box<dyn Demuxer>, tags: Tags, native: Vec<u64>) -> Reader {
342 Reader {
343 format,
344 inner,
345 tags,
346 queue: VecDeque::new(),
347 native,
348 }
349 }
350
351 /// Which format the content turned out to be.
352 pub fn format(&self) -> Format {
353 self.format
354 }
355
356 /// Every stream the container declares, decodable or not.
357 pub fn streams(&self) -> &[StreamInfo] {
358 self.inner.streams()
359 }
360
361 /// The stream of `kind` a caller that just wants "the audio" means: the one
362 /// the container flagged ([`StreamInfo::default`]), and the first of that
363 /// kind where nothing is flagged.
364 ///
365 /// The flag comes first because it is the whole answer to which language a
366 /// dual-audio remux opens in -- a muxer that put the French track second
367 /// and marked it default meant the French one, and file order would play
368 /// the other.
369 pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> {
370 let of_kind = || {
371 self.streams()
372 .iter()
373 .filter(move |s| s.params.codec.media_type() == kind)
374 };
375 of_kind().find(|s| s.default).or_else(|| of_kind().next())
376 }
377
378 /// The container's own id for a stream: a Matroska `TrackNumber`, which is
379 /// how a caller names one language of a dual-audio file.
380 pub fn native_id(&self, stream: u32) -> u64 {
381 self.native
382 .get(stream as usize)
383 .copied()
384 .unwrap_or(u64::from(stream))
385 }
386
387 /// The stream index carrying container-native id `id`.
388 pub fn stream_of_native(&self, id: u64) -> Option<u32> {
389 self.native.iter().position(|&n| n == id).map(|i| i as u32)
390 }
391
392 /// What the file says about itself. Empty for a file with no tags, and for
393 /// the formats [`tags`] does not read.
394 pub fn tags(&self) -> &Tags {
395 &self.tags
396 }
397
398 /// The longest stream's duration, when any stream states or implies one.
399 ///
400 /// What a player would play: [`StreamInfo::initial_padding`] is off it,
401 /// because an MP3's encoder delay is silence the file carries and nobody
402 /// hears.
403 pub fn duration(&self) -> Option<Timestamp> {
404 self.streams()
405 .iter()
406 .filter_map(|s| {
407 s.duration.map(|d| {
408 // `initial_padding` is a sample count, not a `time_base`
409 // tick count — the two only coincide when the stream's
410 // time base happens to be `1/sample_rate`, which a
411 // container's own duration field usually is not.
412 let padding_ticks = s
413 .params
414 .audio()
415 .filter(|a| a.sample_rate > 0 && s.initial_padding > 0)
416 .map(|a| {
417 TimeBase::from_rate(a.sample_rate).rescale(
418 i64::from(s.initial_padding),
419 s.time_base,
420 Rounding::Down,
421 )
422 })
423 .unwrap_or(0);
424 Timestamp::new(d.saturating_sub(padding_ticks), s.time_base)
425 })
426 })
427 .max()
428 }
429
430 /// Every audio stream with no decoder behind it, and why.
431 ///
432 /// Non-audio streams are not listed: this is an audio probe, and a file's
433 /// picture is another crate's business.
434 pub fn unsupported(&self) -> Vec<Unsupported> {
435 self.streams()
436 .iter()
437 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
438 .filter_map(|s| match AudioDecoder::new(&s.params) {
439 Ok(_) => None,
440 Err(e) => Some(Unsupported {
441 stream: s.index,
442 codec: s.params.codec,
443 reason: e.to_string(),
444 }),
445 })
446 .collect()
447 }
448
449 /// A decoder for one stream.
450 pub fn make_decoder(&self, stream: u32) -> Result<AudioDecoder> {
451 let info = self
452 .streams()
453 .iter()
454 .find(|s| s.index == stream)
455 .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
456 AudioDecoder::new(&info.params)
457 }
458
459 /// The next packet in storage order, or [`Error::Eof`].
460 pub fn next_packet(&mut self) -> Result<Packet> {
461 match self.queue.pop_front() {
462 Some(packet) => Ok(packet),
463 None => self.inner.next_packet(),
464 }
465 }
466
467 /// Seek `stream` to `to` and answer where the reader actually landed.
468 ///
469 /// The landing is the next packet's own timestamp, so a caller can tell
470 /// how far ahead of (or behind) its target the container put it — which is
471 /// the number a sample-accurate segment start is trimmed against. Nothing
472 /// is reopened and no packet is dropped: packets of other streams read on
473 /// the way to the landing are queued, not discarded.
474 pub fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<Timestamp> {
475 self.queue.clear();
476 self.inner.seek(stream, to, mode)?;
477 let base = self
478 .streams()
479 .iter()
480 .find(|s| s.index == stream)
481 .map(|s| s.time_base)
482 .unwrap_or(TimeBase::MILLIS);
483 for _ in 0..SEEK_LOOKAHEAD {
484 let packet = match self.inner.next_packet() {
485 Ok(packet) => packet,
486 // Seeking past the end lands at the end; the target is as good
487 // an answer as any and the next read says `Eof`.
488 Err(e) if e.is_eof() => return Ok(to.rescale(base, Rounding::Down)),
489 Err(e) => return Err(e),
490 };
491 let hit = packet.stream == stream;
492 let pts = packet.pts;
493 self.queue.push_back(packet);
494 if hit {
495 return Ok(Timestamp::new(pts.unwrap_or(0), base));
496 }
497 }
498 Ok(to.rescale(base, Rounding::Down))
499 }
500}
501
502impl std::fmt::Debug for Reader {
503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504 f.debug_struct("Reader")
505 .field("format", &self.format.name())
506 .field("streams", &self.streams().len())
507 .finish()
508 }
509}
510
511/// Read until `buf` is full or the source ends; answers how much arrived.
512fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
513 let mut at = 0;
514 while at < buf.len() {
515 match r.read(&mut buf[at..]) {
516 Ok(0) => break,
517 Ok(n) => at += n,
518 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
519 Err(e) => return Err(Error::Io(e)),
520 }
521 }
522 Ok(at)
523}
524
525/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a
526/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the
527/// `0x2001` format tag that says so outright. The chunk walk is the file's
528/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle.
529fn wav_dts_span<R: Read + Seek>(src: &mut R, end: u64) -> Result<Option<(u64, u64)>> {
530 let mut at = 12u64;
531 while at + 8 <= end {
532 src.seek(SeekFrom::Start(at))?;
533 let mut h = [0u8; 8];
534 if read_upto(src, &mut h)? < 8 {
535 break;
536 }
537 let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]]));
538 let body = at + 8;
539 if &h[..4] == b"data" {
540 // A streamed writer's placeholder size means the file is the bound.
541 let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end {
542 end
543 } else {
544 body + size
545 };
546 let mut window = vec![0u8; HEAD.min((stop - body) as usize)];
547 src.seek(SeekFrom::Start(body))?;
548 let got = read_upto(src, &mut window)?;
549 window.truncate(got);
550 return Ok(dts_chains(&window).then_some((body, stop)));
551 }
552 at = body + size + (size & 1);
553 }
554 Ok(None)
555}
556
557fn open_dts_span<R: Read + Seek + Send + 'static>(
558 mut src: R,
559 format: Format,
560 start: u64,
561 end: u64,
562) -> Result<Reader> {
563 let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
564 src.seek(SeekFrom::Start(start))?;
565 let got = read_upto(&mut src, &mut window)?;
566 window.truncate(got);
567 let (core, _) = dts::access_unit(&window)
568 .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?;
569 let total = dts_total(&window, end, start);
570 let demuxer = raw::RawDemuxer::new(
571 src,
572 raw::Kind::Dts,
573 raw::dts_parameters(&core),
574 start,
575 end,
576 total,
577 None,
578 )?;
579 Ok(Reader::wrap(
580 format,
581 Box::new(demuxer),
582 Tags::default(),
583 vec![0],
584 ))
585}
586
587fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
588 if let Some((start, stop)) = wav_dts_span(&mut src, end)? {
589 return open_dts_span(src, Format::Wav, start, stop);
590 }
591 src.rewind()?;
592 let (spec, frames, compressed) = {
593 let reader = ec_riff::WavReader::new(&mut src)?;
594 (reader.spec(), reader.duration(), reader.compressed().cloned())
595 };
596 let start = src.stream_position()?;
597 if let Some(c) = compressed {
598 let (params, kind) = raw::wav_compressed_parameters(spec, &c)?;
599 let bytes_per = match kind {
600 raw::Kind::WavBlocks { block, samples } => (block as u64, samples),
601 _ => (u64::from(spec.channels.max(1)), 1),
602 };
603 let audio_end = frames
604 .map(|n| start + n / bytes_per.1 * bytes_per.0)
605 .unwrap_or(end)
606 .min(end);
607 let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1));
608 let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?;
609 return Ok(Reader::wrap(
610 Format::Wav,
611 Box::new(demuxer),
612 Tags::default(),
613 vec![0],
614 ));
615 }
616 let (params, block_align) = raw::wav_parameters(spec)?;
617 // A `data` size the header did not state (a streamed writer's placeholder)
618 // means the file itself is the bound.
619 let audio_end = frames
620 .map(|n| start + n * block_align as u64)
621 .unwrap_or(end)
622 .min(end);
623 let total = frames.or(Some((audio_end - start) / block_align as u64));
624 let demuxer = raw::RawDemuxer::new(
625 src,
626 raw::Kind::Wav { block_align },
627 params,
628 start,
629 audio_end,
630 total,
631 None,
632 )?;
633 Ok(Reader::wrap(
634 Format::Wav,
635 Box::new(demuxer),
636 Tags::default(),
637 vec![0],
638 ))
639}
640
641fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
642 let base = tags::id3v2_len(head).unwrap_or(0);
643 src.seek(SeekFrom::Start(base))?;
644 let mut magic = [0u8; 4];
645 read_upto(&mut src, &mut magic)?;
646 if &magic != b"fLaC" {
647 return Err(Error::corrupt("FLAC: no stream marker"));
648 }
649 let mut info: Option<ec_flac::StreamInfo> = None;
650 let mut tags = Tags::default();
651 let mut at = base + 4;
652 loop {
653 let mut header = [0u8; 4];
654 if read_upto(&mut src, &mut header)? < 4 {
655 return Err(Error::corrupt("FLAC: metadata ended before any frame"));
656 }
657 let last = header[0] & 0x80 != 0;
658 let kind = header[0] & 0x7f;
659 let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]]))
660 .min(end.saturating_sub(at + 4));
661 let mut body = vec![0u8; len as usize];
662 read_upto(&mut src, &mut body)?;
663 at += 4 + len;
664 match kind {
665 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
666 4 => tags.merge(tags::from_vorbis_comment(&body)),
667 _ => {}
668 }
669 if last {
670 break;
671 }
672 }
673 let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
674 let params = ec_flac::codec_parameters(&info);
675 let total = match info.total_samples {
676 0 => None,
677 n => Some(n),
678 };
679 let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
680 Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
681}
682
683fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
684 let (start, tags) = id3(&mut src, head, end)?;
685 let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
686 src.seek(SeekFrom::Start(start))?;
687 let got = read_upto(&mut src, &mut window)?;
688 window.truncate(got);
689 let at = frame_sync(&window, Format::Mp3)
690 .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
691 let header = ec_mp3::FrameHeader::parse(&window[at..])?;
692 let mut start = start + at as u64;
693 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
694 // A Xing/Info header states the frame count exactly; without one the
695 // duration is the bitrate estimate the oracle also falls back to, which is
696 // right for CBR and approximate for VBR.
697 let per_frame = header.samples_per_frame() as u64;
698 let xing = xing_frames(&window[at..], &header);
699 if xing.is_some() {
700 // The Xing frame carries no audio — it is a header wearing a frame's
701 // clothes, and a decoder handed it emits a granule of silence. Both
702 // the oracle and this reader start after it.
703 start += header.frame_len().unwrap_or(0) as u64;
704 }
705 // Gapless, as the gapless tag states it: a decoder emits the encoder delay
706 // plus its own 529 samples of Layer III synthesis delay before the first
707 // sample that was ever recorded, and the file runs `padding` samples past
708 // the last one. Both are silence a player must not play, and a file with no
709 // tag has neither — its frames are all there is to go on.
710 let (padding, total) = match &xing {
711 Some(x) => (
712 x.delay + MP3_DECODER_DELAY,
713 Some(
714 (x.frames * per_frame)
715 .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))),
716 ),
717 ),
718 None => (
719 0,
720 header
721 .frame_len()
722 .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)),
723 ),
724 };
725 let demuxer = raw::RawDemuxer::new(
726 src,
727 raw::Kind::Mp3,
728 raw::mp3_parameters(&header),
729 start,
730 audio_end,
731 total,
732 None,
733 )?
734 .with_initial_padding(padding);
735 Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
736}
737
738fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
739 let (start, tags) = id3(&mut src, head, end)?;
740 let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
741 src.seek(SeekFrom::Start(start))?;
742 let got = read_upto(&mut src, &mut window)?;
743 window.truncate(got);
744 let at = frame_sync(&window, Format::Adts)
745 .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
746 let header = ec_aac::parse_adts(&window[at..])?;
747 let start = start + at as u64;
748 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
749 // ADTS states no duration anywhere: every frame is 1024 samples, so the
750 // file's size over its *average* frame is the estimate — the same one
751 // the oracle prints "estimating duration from bitrate" about. Averaged rather
752 // than taken off the first frame, which on a real encode is nothing like
753 // the mean (a 3-second fixture came out 5 seconds long that way).
754 let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
755 while count < 512 {
756 let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
757 break;
758 };
759 if h.frame_length == 0 || walk + h.frame_length > window.len() {
760 break;
761 }
762 sum += h.frame_length as u64;
763 count += 1;
764 walk += h.frame_length;
765 }
766 let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
767 let demuxer = raw::RawDemuxer::new(
768 src,
769 raw::Kind::Adts,
770 raw::adts_parameters(&header),
771 start,
772 audio_end,
773 total,
774 None,
775 )?;
776 Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
777}
778
779fn open_dts<R: Read + Seek + Send + 'static>(src: R, end: u64) -> Result<Reader> {
780 open_dts_span(src, Format::Dts, 0, end)
781}
782
783/// Duration estimate in samples: the span's size over the mean access unit
784/// of the head window.
785fn dts_total(window: &[u8], end: u64, start: u64) -> Option<u64> {
786 let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize);
787 while sum < (1 << 20) {
788 let Some((core, len)) = dts::access_unit(window.get(at..)?) else {
789 break;
790 };
791 if at + len > window.len() {
792 break;
793 }
794 sum += len as u64;
795 samples += u64::from(core.samples);
796 at += len;
797 }
798 (sum > 0).then(|| (end - start) * samples / sum)
799}
800
801fn open_avi<R: Read + Seek + Send + 'static>(src: R) -> Result<Reader> {
802 let reader = ec_riff::AviReader::new(src)?;
803 let demuxer = AviDemuxer::new(reader)?;
804 let native = demuxer
805 .stream_numbers
806 .iter()
807 .map(|&n| u64::from(n))
808 .collect();
809 Ok(Reader::wrap(
810 Format::Avi,
811 Box::new(demuxer),
812 Tags::default(),
813 native,
814 ))
815}
816
817struct AviDemuxer<R> {
818 reader: ec_riff::AviReader<R>,
819 streams: Vec<StreamInfo>,
820 stream_numbers: Vec<u32>,
821 samples: Vec<u64>,
822 pending: VecDeque<Packet>,
823 carry: Vec<Vec<u8>>,
824 sync_bias: Vec<u64>,
825 seek_anchor: Vec<Option<(u64, bool)>>,
826}
827
828impl<R: Read + Seek> AviDemuxer<R> {
829 fn new(mut reader: ec_riff::AviReader<R>) -> Result<AviDemuxer<R>> {
830 let mut streams = Vec::new();
831 let mut stream_numbers = Vec::new();
832 for (index, s) in reader.audio_streams().iter().enumerate() {
833 let codec = match s.format_tag {
834 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8,
835 0x0001 => CodecId::PcmS16Le,
836 0x0055 => CodecId::Mp3,
837 0x00ff => CodecId::Aac,
838 0x2000 => CodecId::Ac3,
839 0x0011 | 0x0002 | 0x0006 | 0x0007 => {
840 ec_riff::WavCompressed::codec_of(s.format_tag).unwrap_or(CodecId::PcmAlaw)
841 }
842 tag => {
843 return Err(Error::unsupported(
844 format!("AVI audio format tag {tag:#06x}"),
845 "no decoder for it exists in this family yet",
846 ));
847 }
848 };
849 let mut params = CodecParameters::new(codec);
850 params.media = MediaParameters::Audio(AudioParameters {
851 sample_rate: s.sample_rate,
852 layout: ChannelLayout::from_count(usize::from(s.channels).max(1)),
853 format: match codec {
854 CodecId::PcmU8 => Some(SampleFormat::U8),
855 CodecId::PcmS16Le => Some(SampleFormat::S16),
856 CodecId::ImaAdpcmWav
857 | CodecId::MsAdpcm
858 | CodecId::PcmAlaw
859 | CodecId::PcmMulaw => Some(SampleFormat::S16),
860 _ => None,
861 },
862 bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)),
863 });
864 let extra = reader.audio_extradata(index);
865 if !extra.is_empty() && matches!(codec, CodecId::ImaAdpcmWav | CodecId::MsAdpcm) {
866 params.extradata = Some(Buf::copy_from_slice(extra));
867 }
868 let mut info = StreamInfo::new(
869 index as u32,
870 TimeBase::from_rate(s.sample_rate.max(1)),
871 params,
872 );
873 if s.length > 0 {
874 info.duration = Some(avi_units_to_samples(*s, u64::from(s.length)) as i64);
875 }
876 streams.push(info);
877 stream_numbers.push(s.index);
878 }
879 if streams.is_empty() {
880 return Err(Error::unsupported(
881 "this AVI file",
882 "it declares no audio stream this reader can hand out",
883 ));
884 }
885 let samples = vec![0; streams.len()];
886 let carry = vec![Vec::new(); streams.len()];
887 let seek_anchor = vec![None; streams.len()];
888 let sync_bias = avi_sync_biases(&mut reader, &streams, &stream_numbers)?;
889 reader.rewind();
890 Ok(AviDemuxer {
891 reader,
892 streams,
893 stream_numbers,
894 samples,
895 pending: VecDeque::new(),
896 carry,
897 sync_bias,
898 seek_anchor,
899 })
900 }
901
902 fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> {
903 let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else {
904 return Ok(());
905 };
906 let codec = self.streams[stream].params.codec;
907 match codec {
908 CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac => {
909 self.queue_elementary_chunk(stream, chunk.data, codec)
910 }
911 CodecId::ImaAdpcmWav | CodecId::MsAdpcm => {
912 // One decodable block per packet.
913 let avi = self.reader.audio_streams().get(stream).copied();
914 let (ba, ch) = avi.map_or((0usize, 1u32), |s| {
915 (usize::from(s.block_align), u32::from(s.channels.max(1)))
916 });
917 let spb = ec_riff::WavCompressed::new(
918 avi.map_or(0, |s| s.format_tag),
919 ch as u16,
920 ba as u16,
921 &[],
922 )
923 .map_or(0, |c| u64::from(c.samples_per_block));
924 if ba == 0 || spb == 0 {
925 return Ok(());
926 }
927 for block in chunk.data.chunks(ba).filter(|b| b.len() == ba) {
928 self.push_packet(stream, Buf::copy_from_slice(block), spb);
929 }
930 Ok(())
931 }
932 CodecId::PcmAlaw | CodecId::PcmMulaw => {
933 let ch = self
934 .reader
935 .audio_streams()
936 .get(stream)
937 .map_or(1usize, |s| usize::from(s.channels.max(1)));
938 let frames = (chunk.data.len() / ch) as u64;
939 self.push_packet(stream, Buf::from_vec(chunk.data), frames);
940 Ok(())
941 }
942 _ => {
943 let frames = match codec {
944 CodecId::PcmU8 | CodecId::PcmS16Le => {
945 let block = self
946 .reader
947 .audio_streams()
948 .get(stream)
949 .map_or(1usize, |s| usize::from(s.block_align).max(1));
950 (chunk.data.len() / block) as u64
951 }
952 _ => 0,
953 };
954 self.push_packet(stream, Buf::from_vec(chunk.data), frames);
955 Ok(())
956 }
957 }
958 }
959
960 fn queue_elementary_chunk(
961 &mut self,
962 stream: usize,
963 chunk: Vec<u8>,
964 codec: CodecId,
965 ) -> Result<()> {
966 let avi_stream = self
967 .stream_numbers
968 .get(stream)
969 .and_then(|n| self.reader.audio_streams().iter().find(|s| s.index == *n))
970 .copied();
971 let mut data = std::mem::take(&mut self.carry[stream]);
972 data.extend_from_slice(&chunk);
973 let mut at = 0usize;
974 let mut skipped = 0usize;
975 while at < data.len() {
976 match avi_elementary_frame(codec, &data[at..]) {
977 Ok(Some((size, frames))) if at + size <= data.len() => {
978 if skipped > 0
979 && matches!(codec, CodecId::Ac3 | CodecId::EAc3)
980 && ec_ac3::Ac3Decoder::new()
981 .decode_frame(&data[at..at + size])
982 .is_err()
983 {
984 at += 1;
985 skipped += 1;
986 continue;
987 }
988 if skipped > 0 {
989 if let Some(s) = avi_stream {
990 let skipped_samples = avi_units_to_samples(s, skipped as u64);
991 let initial = self.sync_bias.get(stream).copied().unwrap_or(0);
992 if self.samples[stream] != 0 || skipped_samples > initial {
993 self.samples[stream] =
994 self.samples[stream].saturating_add(skipped_samples);
995 }
996 }
997 skipped = 0;
998 }
999 if let Some((anchor, after)) = self.seek_anchor[stream].take() {
1000 let phase = self.sync_bias.get(stream).copied().unwrap_or(0);
1001 let relative = anchor.saturating_sub(phase);
1002 let steps = if after {
1003 relative.saturating_add(frames.saturating_sub(1)) / frames
1004 } else {
1005 relative / frames
1006 };
1007 self.samples[stream] = phase.saturating_add(steps.saturating_mul(frames));
1008 }
1009 self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames);
1010 at += size;
1011 }
1012 Ok(Some(_)) => break,
1013 Ok(None) => {
1014 at += 1;
1015 skipped += 1;
1016 }
1017 Err(e) if e.is_need_more() => break,
1018 Err(_) => {
1019 at += 1;
1020 skipped += 1;
1021 }
1022 }
1023 }
1024 self.carry[stream].extend_from_slice(&data[at..]);
1025 Ok(())
1026 }
1027
1028 fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) {
1029 let base = self.streams[stream].time_base;
1030 let pts = self.samples[stream];
1031 self.samples[stream] = self.samples[stream].saturating_add(frames);
1032 let mut packet = Packet::new(stream as u32, base, data);
1033 packet.pts = Some(pts as i64);
1034 packet.dts = Some(pts as i64);
1035 packet.duration = Some(frames as i64);
1036 packet.flags = PacketFlags {
1037 keyframe: true,
1038 ..PacketFlags::default()
1039 };
1040 self.pending.push_back(packet);
1041 }
1042}
1043fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result<Option<(usize, u64)>> {
1044 match codec {
1045 CodecId::Ac3 | CodecId::EAc3 => {
1046 if data.len() < 2 {
1047 return Err(Error::NeedMore);
1048 }
1049 if data[0] != 0x0b || data[1] != 0x77 {
1050 return Ok(None);
1051 }
1052 ec_ac3::frame_size(data).map(|size| {
1053 if data.len() >= size + 2 && data[size..size + 2] != [0x0b, 0x77] {
1054 None
1055 } else {
1056 Some((size, 1536))
1057 }
1058 })
1059 }
1060 CodecId::Mp3 => {
1061 if data.len() < 2 {
1062 return Err(Error::NeedMore);
1063 }
1064 if data[0] != 0xff || data[1] & 0xe0 != 0xe0 {
1065 return Ok(None);
1066 }
1067 let header = ec_mp3::FrameHeader::parse(data)?;
1068 if header.layer != 3 {
1069 return Ok(None);
1070 }
1071 Ok(header
1072 .frame_len()
1073 .map(|size| (size, header.samples_per_frame() as u64)))
1074 }
1075 CodecId::Aac => {
1076 if data.len() < 2 {
1077 return Err(Error::NeedMore);
1078 }
1079 if !ec_aac::is_adts(data) {
1080 return Ok(None);
1081 }
1082 let header = ec_aac::parse_adts(data)?;
1083 Ok(Some((header.frame_length, raw::adts_samples(&header))))
1084 }
1085 _ => Ok(None),
1086 }
1087}
1088
1089fn avi_sync_biases<R: Read + Seek>(
1090 reader: &mut ec_riff::AviReader<R>,
1091 streams: &[StreamInfo],
1092 stream_numbers: &[u32],
1093) -> Result<Vec<u64>> {
1094 let mut out = vec![0; streams.len()];
1095 for (i, info) in streams.iter().enumerate() {
1096 if !matches!(
1097 info.params.codec,
1098 CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac
1099 ) {
1100 continue;
1101 }
1102 let Some(&native) = stream_numbers.get(i) else {
1103 continue;
1104 };
1105 let Some(avi_stream) = reader
1106 .audio_streams()
1107 .iter()
1108 .find(|s| s.index == native)
1109 .copied()
1110 else {
1111 continue;
1112 };
1113 reader.seek_to_stream_time(native, 0, false)?;
1114 for _ in 0..16 {
1115 let chunk = match reader.next_packet() {
1116 Ok(chunk) => chunk,
1117 Err(e) if e.is_eof() => break,
1118 Err(e) => return Err(e),
1119 };
1120 if chunk.stream != native {
1121 continue;
1122 }
1123 let skip = avi_elementary_leading_skip(info.params.codec, &chunk.data);
1124 out[i] = avi_units_to_samples(avi_stream, skip as u64);
1125 break;
1126 }
1127 }
1128 Ok(out)
1129}
1130
1131fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize {
1132 for at in 0..data.len() {
1133 match avi_elementary_frame(codec, &data[at..]) {
1134 Ok(Some((size, _))) if at + size <= data.len() => return at,
1135 Ok(Some(_)) | Err(Error::NeedMore) => return at,
1136 Ok(None) | Err(_) => {}
1137 }
1138 }
1139 0
1140}
1141
1142fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64, round_up: bool) -> u64 {
1143 let scale = u128::from(stream.scale.max(1));
1144 let rate = u128::from(stream.rate.max(1));
1145 let sample_rate = u128::from(stream.sample_rate.max(1));
1146 let denominator = scale * sample_rate;
1147 let numerator = u128::from(samples).saturating_mul(rate);
1148 let units = if round_up {
1149 numerator.saturating_add(denominator.saturating_sub(1)) / denominator
1150 } else {
1151 numerator / denominator
1152 };
1153 let units = units.min(u128::from(u64::MAX)) as u64;
1154 match stream.length {
1155 0 => units,
1156 n => units.min(u64::from(n)),
1157 }
1158}
1159fn avi_units_to_samples(stream: ec_riff::AviAudioStream, units: u64) -> u64 {
1160 let n = u128::from(units)
1161 .saturating_mul(u128::from(stream.scale.max(1)))
1162 .saturating_mul(u128::from(stream.sample_rate.max(1)));
1163 (n / u128::from(stream.rate.max(1))).min(u128::from(u64::MAX)) as u64
1164}
1165
1166impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
1167 fn streams(&self) -> &[StreamInfo] {
1168 &self.streams
1169 }
1170
1171 fn next_packet(&mut self) -> Result<Packet> {
1172 loop {
1173 if let Some(packet) = self.pending.pop_front() {
1174 return Ok(packet);
1175 }
1176 match self.reader.next_packet() {
1177 Ok(chunk) => self.queue_chunk(chunk)?,
1178 Err(e) if e.is_eof() => return Err(Error::Eof),
1179 Err(e) => return Err(e),
1180 }
1181 }
1182 }
1183
1184 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
1185 let local = self
1186 .streams
1187 .iter()
1188 .position(|s| s.index == stream)
1189 .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
1190 let avi_stream_no = self.stream_numbers[local];
1191 let avi_stream = *self
1192 .reader
1193 .audio_streams()
1194 .iter()
1195 .find(|s| s.index == avi_stream_no)
1196 .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?;
1197 let base = self.streams[local].time_base;
1198 let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64;
1199 let seek_units = samples_to_avi_units(
1200 avi_stream,
1201 target_samples,
1202 matches!(mode, SeekMode::SyncAfter),
1203 );
1204 let landed_units = self.reader.seek_to_stream_time(
1205 avi_stream_no,
1206 seek_units,
1207 matches!(mode, SeekMode::SyncAfter),
1208 )?;
1209 self.pending.clear();
1210 for carry in &mut self.carry {
1211 carry.clear();
1212 }
1213 self.samples[local] = avi_units_to_samples(avi_stream, landed_units)
1214 .saturating_sub(self.sync_bias.get(local).copied().unwrap_or(0));
1215 self.seek_anchor[local] = Some((
1216 avi_units_to_samples(avi_stream, seek_units),
1217 matches!(mode, SeekMode::SyncAfter),
1218 ));
1219 Ok(())
1220 }
1221}
1222
1223/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
1224fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
1225 let mut tags = Tags::default();
1226 let start = match tags::id3v2_len(head) {
1227 Some(len) => {
1228 let len = len.min(end);
1229 let mut tag = vec![0u8; len as usize];
1230 src.rewind()?;
1231 read_upto(src, &mut tag)?;
1232 tags.merge(tags::from_id3v2(&tag));
1233 len
1234 }
1235 None => 0,
1236 };
1237 // The v1 block at the end fills in what v2 did not say.
1238 if end >= 128 {
1239 src.seek(SeekFrom::Start(end - 128))?;
1240 let mut tail = [0u8; 128];
1241 read_upto(src, &mut tail)?;
1242 tags.merge(tags::from_id3v1(&tail));
1243 }
1244 Ok((start, tags))
1245}
1246
1247/// Bytes of ID3v1 at the end of a stream, which are not audio.
1248fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
1249 if end < 128 {
1250 return Ok(0);
1251 }
1252 src.seek(SeekFrom::Start(end - 128))?;
1253 let mut tail = [0u8; 3];
1254 read_upto(src, &mut tail)?;
1255 Ok(u64::from(&tail == b"TAG") * 128)
1256}
1257
1258/// The frame count a Xing/Info header states, when the first frame carries one.
1259fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> {
1260 let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
1261 let tag = frame.get(at..at + 8)?;
1262 if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
1263 return None;
1264 }
1265 let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
1266 if flags & 1 == 0 {
1267 return None;
1268 }
1269 let n = frame.get(at + 8..at + 12)?;
1270 let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]));
1271 // The gapless extension sits behind whichever optional fields the flags
1272 // claimed -- frame count, byte count, the 100-byte seek table, quality --
1273 // and states the two trims 21 bytes into itself, twelve bits each.
1274 let mut extension_at = at + 12;
1275 extension_at += usize::from(flags & 2 != 0) * 4;
1276 extension_at += usize::from(flags & 4 != 0) * 100;
1277 extension_at += usize::from(flags & 8 != 0) * 4;
1278 let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) {
1279 Some(&[a, b, c]) => (
1280 u32::from(a) << 4 | u32::from(b) >> 4,
1281 (u32::from(b) & 0xF) << 8 | u32::from(c),
1282 ),
1283 _ => (0, 0),
1284 };
1285 Some(Xing {
1286 frames,
1287 delay,
1288 padding,
1289 })
1290}
1291
1292/// What an MP3's Xing/Info header states: how long the file is, and the two
1293/// silences the encoder had to add to make whole frames of it.
1294struct Xing {
1295 /// Audio frames in the file, the header frame itself excluded.
1296 frames: u64,
1297 /// Encoder delay: samples of silence in front of the first real one.
1298 delay: u32,
1299 /// Encoder padding: samples of silence after the last real one.
1300 padding: u32,
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305 use super::*;
1306
1307 #[test]
1308 fn magic_numbers_name_their_formats() {
1309 assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some(Format::Wav));
1310 assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some(Format::Flac));
1311 assert_eq!(sniff(b"OggS\0\x02\0\0"), Some(Format::Ogg));
1312 assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x01\0\0\0"), Some(Format::Matroska));
1313 assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\x02\0"), Some(Format::Mp4));
1314 // MPEG-1 Layer III, 128 kbit/s, 44.1 kHz.
1315 assert_eq!(sniff(b"\xff\xfb\x90\x00\0\0\0\0\0\0"), Some(Format::Mp3));
1316 // ADTS: same sync word, the layer bits MPEG audio reserves.
1317 assert_eq!(
1318 sniff(b"\xff\xf1\x50\x80\x01\x7f\xfc\0\0\0"),
1319 Some(Format::Adts)
1320 );
1321 assert_eq!(sniff(b"not a media file at all"), None);
1322 }
1323
1324 /// `initial_padding` is a *sample* count while a stream's `duration` is in
1325 /// `time_base` ticks -- for a Matroska file whose `TimestampScale` is not
1326 /// `1/sample_rate` (the common case: ticks are milliseconds), subtracting
1327 /// one from the other unconverted lopped a third off an AAC track's
1328 /// stated length (3.021 s of `CodecDelay`-bearing audio reported as 1.997
1329 /// s: `1024` samples read straight off as `1024` one-millisecond ticks).
1330 #[test]
1331 fn duration_converts_initial_padding_out_of_sample_units() {
1332 let reader = Reader::open(ec_testkit::fixture("audio/aac-mka-stereo-48000.mka")).unwrap();
1333 let d = reader.duration().expect("a stated duration").as_secs_f64();
1334 assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s");
1335 }
1336
1337 /// An `.aac` or `.mp3` that opens with a tag is still an `.aac` or `.mp3`.
1338 #[test]
1339 fn an_id3_tag_does_not_hide_the_format() {
1340 let mut file = b"ID3\x03\x00\x00\x00\x00\x00\x0a".to_vec();
1341 file.extend_from_slice(&[0u8; 10]);
1342 file.extend_from_slice(b"\xff\xfb\x90\x00\0\0\0\0\0\0");
1343 assert_eq!(tags::id3v2_len(&file), Some(20));
1344 assert_eq!(sniff(&file), Some(Format::Mp3));
1345 }
1346}