forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2cccf17Tahinli3 months ago136 commits

lib.rs731 lines, 26.8 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`]; there is exactly one EBML parser in this family and it is not
12//! here. What is implemented in [`raw`] is the four formats that are a codec
13//! and nothing else: WAV, 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//! TrueHD track says "TrueHD", 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 raw;
31pub mod tags;
32
33use std::collections::VecDeque;
34use std::fs::File;
35use std::io::{BufReader, Read, Seek, SeekFrom};
36use std::path::Path;
37
38use ec_core::error::{Error, Result};
39use ec_core::packet::Packet;
40use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo};
41use ec_core::timebase::{Rounding, TimeBase, Timestamp};
42
43pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};
44pub use tags::Tags;
45
46/// Bytes read to sniff a format and to find the first frame of a raw stream.
47const HEAD: usize = 64 << 10;
48/// Packets a seek may look past to find one of the stream it was asked about.
49const 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.
53const MP3_DECODER_DELAY: u32 = 529;
54
55/// A container (or the lack of one) this crate can open.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57pub enum Format {
58 /// RIFF/WAVE PCM.
59 Wav,
60 /// Native FLAC.
61 Flac,
62 /// MPEG-1/2/2.5 Layer III, with or without an ID3 tag.
63 Mp3,
64 /// Raw AAC in ADTS framing.
65 Adts,
66 /// Ogg: Vorbis, Opus or FLAC inside it.
67 Ogg,
68 /// ISO base media: mp4, m4a, mov.
69 Mp4,
70 /// Matroska and WebM.
71 Matroska,
72}
73
74impl Format {
75 /// Short lowercase name for logs and capability tables.
76 pub fn name(&self) -> &'static str {
77 match self {
78 Format::Wav => "wav",
79 Format::Flac => "flac",
80 Format::Mp3 => "mp3",
81 Format::Adts => "adts",
82 Format::Ogg => "ogg",
83 Format::Mp4 => "mp4",
84 Format::Matroska => "matroska",
85 }
86 }
87
88 /// Extensions that usually carry this format. Advisory only: the sniff
89 /// decides.
90 pub fn extensions(&self) -> &'static [&'static str] {
91 match self {
92 Format::Wav => &["wav", "wave"],
93 Format::Flac => &["flac"],
94 Format::Mp3 => &["mp3"],
95 Format::Adts => &["aac", "adts"],
96 Format::Ogg => &["ogg", "oga", "opus"],
97 Format::Mp4 => &["mp4", "m4a", "m4v", "mov"],
98 Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"],
99 }
100 }
101}
102
103/// The format `head` opens with, by content.
104///
105/// An ID3v2 tag is skipped first, because `.aac` and `.mp3` files both carry
106/// one and the format is whatever follows it.
107pub fn sniff(head: &[u8]) -> Option<Format> {
108 let at = tags::id3v2_len(head).unwrap_or(0) as usize;
109 let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head);
110 if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WAVE" {
111 return Some(Format::Wav);
112 }
113 if data.starts_with(b"fLaC") {
114 return Some(Format::Flac);
115 }
116 if data.starts_with(b"OggS") {
117 return Some(Format::Ogg);
118 }
119 if ec_matroska::is_matroska(data) {
120 return Some(Format::Matroska);
121 }
122 if ec_mp4::is_mp4(data) {
123 return Some(Format::Mp4);
124 }
125 // Whichever of the two framed formats starts *first*, and only where three
126 // frames chain: AAC payload bytes routinely parse as a lone MPEG audio
127 // header, which is how an `.aac` file came out an `.mp3` once.
128 for at in 0..data.len().saturating_sub(8).min(SYNC_SCAN) {
129 if data[at] != 0xFF {
130 continue;
131 }
132 for format in [Format::Adts, Format::Mp3] {
133 if chains(&data[at..], format) {
134 return Some(format);
135 }
136 }
137 }
138 None
139}
140
141/// Offsets a sync search looks through before giving up.
142const SYNC_SCAN: usize = 8 << 10;
143/// Consecutive frames that must parse for a sync to be believed.
144const SYNC_CHAIN: usize = 3;
145
146/// One frame's length, as its own format states it.
147fn frame_len(data: &[u8], format: Format) -> Option<usize> {
148 match format {
149 Format::Mp3 => ec_mp3::FrameHeader::parse(data).ok()?.frame_len(),
150 Format::Adts => Some(ec_aac::parse_adts(data).ok()?.frame_length),
151 _ => None,
152 }
153}
154
155/// True when [`SYNC_CHAIN`] frames of `format` chain from the head of `data`
156/// (or the data runs out first, which is as much as a head can prove).
157fn chains(data: &[u8], format: Format) -> bool {
158 let mut at = 0;
159 for _ in 0..SYNC_CHAIN {
160 match frame_len(&data[at..], format) {
161 Some(len) if len > 0 => at += len,
162 _ => return false,
163 }
164 if at >= data.len() {
165 return true;
166 }
167 }
168 true
169}
170
171/// The first offset where a frame of `format` really starts.
172fn frame_sync(data: &[u8], format: Format) -> Option<usize> {
173 (0..data.len().saturating_sub(8).min(SYNC_SCAN))
174 .find(|&at| data[at] == 0xFF && chains(&data[at..], format))
175}
176
177/// A stream nothing here decodes, and the reason.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Unsupported {
180 /// Index in [`Reader::streams`].
181 pub stream: u32,
182 /// What the container says it is.
183 pub codec: CodecId,
184 /// Why no decoder was built, in words a user can read.
185 pub reason: String,
186}
187
188/// One open media file: streams in, packets out.
189pub struct Reader {
190 format: Format,
191 inner: Box<dyn Demuxer>,
192 tags: Tags,
193 /// Packets read ahead of the caller by a seek looking for its landing.
194 queue: VecDeque<Packet>,
195 /// Container-native track id per stream index — a Matroska `TrackNumber`,
196 /// an mp4 `track_ID`, or the index itself.
197 native: Vec<u64>,
198}
199
200impl Reader {
201 /// Open `path`, sniffing its content for the format.
202 pub fn open(path: impl AsRef<Path>) -> Result<Reader> {
203 let path = path.as_ref();
204 let hint = path.extension().and_then(|e| e.to_str()).map(str::to_owned);
205 Reader::new(BufReader::new(File::open(path)?), hint.as_deref())
206 }
207
208 /// Open an already-open source. `hint` is an extension, used only when the
209 /// content says nothing.
210 pub fn new<R: Read + Seek + Send + 'static>(mut src: R, hint: Option<&str>) -> Result<Reader> {
211 let end = src.seek(SeekFrom::End(0))?;
212 src.rewind()?;
213 let mut head = vec![0u8; HEAD.min(end as usize)];
214 read_upto(&mut src, &mut head)?;
215 let format = sniff(&head)
216 .or_else(|| {
217 let hint = hint?.to_ascii_lowercase();
218 [
219 Format::Wav,
220 Format::Flac,
221 Format::Mp3,
222 Format::Adts,
223 Format::Ogg,
224 Format::Mp4,
225 Format::Matroska,
226 ]
227 .into_iter()
228 .find(|f| f.extensions().contains(&hint.as_str()))
229 })
230 .ok_or_else(|| {
231 Error::unsupported(
232 "this file",
233 "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, matroska)",
234 )
235 })?;
236 src.rewind()?;
237 match format {
238 Format::Matroska => {
239 let demuxer = ec_matroska::MatroskaDemuxer::new(src)?;
240 let native = demuxer
241 .streams()
242 .iter()
243 .map(|s| demuxer.track_number(s.index).unwrap_or(u64::from(s.index)))
244 .collect();
245 Ok(Reader::wrap(
246 format,
247 Box::new(demuxer),
248 Tags::default(),
249 native,
250 ))
251 }
252 Format::Mp4 => {
253 let demuxer = ec_mp4::Mp4Demuxer::new(src)?;
254 let tags = Tags {
255 title: demuxer.title().map(str::to_owned),
256 ..Tags::default()
257 };
258 let native = (0..demuxer.streams().len() as u64).collect();
259 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
260 }
261 Format::Ogg => {
262 let demuxer = ec_ogg::OggDemuxer::open(src)?;
263 // Vorbis carries its comment packet inside the header triplet
264 // this crate publishes as extradata; Opus does not publish its
265 // tags packet at all, so an `.opus` file reports none.
266 let tags = demuxer
267 .streams()
268 .iter()
269 .find(|s| s.params.codec == CodecId::Vorbis)
270 .and_then(|s| s.params.extradata.as_deref())
271 .and_then(|data| ec_ogg::xiph_unlace(data).ok())
272 .and_then(|packets| packets.get(1).map(|p| tags::from_vorbis_comment(&p[7..])))
273 .unwrap_or_default();
274 let native = (0..demuxer.streams().len() as u64).collect();
275 Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
276 }
277 Format::Wav => open_wav(src, end),
278 Format::Flac => open_flac(src, &head, end),
279 Format::Mp3 => open_mp3(src, &head, end),
280 Format::Adts => open_adts(src, &head, end),
281 }
282 }
283
284 fn wrap(format: Format, inner: Box<dyn Demuxer>, tags: Tags, native: Vec<u64>) -> Reader {
285 Reader {
286 format,
287 inner,
288 tags,
289 queue: VecDeque::new(),
290 native,
291 }
292 }
293
294 /// Which format the content turned out to be.
295 pub fn format(&self) -> Format {
296 self.format
297 }
298
299 /// Every stream the container declares, decodable or not.
300 pub fn streams(&self) -> &[StreamInfo] {
301 self.inner.streams()
302 }
303
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.
312 pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> {
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())
319 }
320
321 /// The container's own id for a stream: a Matroska `TrackNumber`, which is
322 /// how a caller names one language of a dual-audio file.
323 pub fn native_id(&self, stream: u32) -> u64 {
324 self.native
325 .get(stream as usize)
326 .copied()
327 .unwrap_or(u64::from(stream))
328 }
329
330 /// The stream index carrying container-native id `id`.
331 pub fn stream_of_native(&self, id: u64) -> Option<u32> {
332 self.native.iter().position(|&n| n == id).map(|i| i as u32)
333 }
334
335 /// What the file says about itself. Empty for a file with no tags, and for
336 /// the formats [`tags`] does not read.
337 pub fn tags(&self) -> &Tags {
338 &self.tags
339 }
340
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.
346 pub fn duration(&self) -> Option<Timestamp> {
347 self.streams()
348 .iter()
349 .filter_map(|s| {
350 s.duration
351 .map(|d| Timestamp::new(d - i64::from(s.initial_padding), s.time_base))
352 })
353 .max_by(|a, b| {
354 a.as_secs_f64()
355 .partial_cmp(&b.as_secs_f64())
356 .unwrap_or(std::cmp::Ordering::Equal)
357 })
358 }
359
360 /// Every audio stream with no decoder behind it, and why.
361 ///
362 /// Non-audio streams are not listed: this is an audio probe, and a file's
363 /// picture is another crate's business.
364 pub fn unsupported(&self) -> Vec<Unsupported> {
365 self.streams()
366 .iter()
367 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
368 .filter_map(|s| match AudioDecoder::new(&s.params) {
369 Ok(_) => None,
370 Err(e) => Some(Unsupported {
371 stream: s.index,
372 codec: s.params.codec,
373 reason: e.to_string(),
374 }),
375 })
376 .collect()
377 }
378
379 /// A decoder for one stream.
380 pub fn make_decoder(&self, stream: u32) -> Result<AudioDecoder> {
381 let info = self
382 .streams()
383 .iter()
384 .find(|s| s.index == stream)
385 .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
386 AudioDecoder::new(&info.params)
387 }
388
389 /// The next packet in storage order, or [`Error::Eof`].
390 pub fn next_packet(&mut self) -> Result<Packet> {
391 match self.queue.pop_front() {
392 Some(packet) => Ok(packet),
393 None => self.inner.next_packet(),
394 }
395 }
396
397 /// Seek `stream` to `to` and answer where the reader actually landed.
398 ///
399 /// The landing is the next packet's own timestamp, so a caller can tell
400 /// how far ahead of (or behind) its target the container put it — which is
401 /// the number a sample-accurate segment start is trimmed against. Nothing
402 /// is reopened and no packet is dropped: packets of other streams read on
403 /// the way to the landing are queued, not discarded.
404 pub fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<Timestamp> {
405 self.queue.clear();
406 self.inner.seek(stream, to, mode)?;
407 let base = self
408 .streams()
409 .iter()
410 .find(|s| s.index == stream)
411 .map(|s| s.time_base)
412 .unwrap_or(TimeBase::MILLIS);
413 for _ in 0..SEEK_LOOKAHEAD {
414 let packet = match self.inner.next_packet() {
415 Ok(packet) => packet,
416 // Seeking past the end lands at the end; the target is as good
417 // an answer as any and the next read says `Eof`.
418 Err(e) if e.is_eof() => return Ok(to.rescale(base, Rounding::Down)),
419 Err(e) => return Err(e),
420 };
421 let hit = packet.stream == stream;
422 let pts = packet.pts;
423 self.queue.push_back(packet);
424 if hit {
425 return Ok(Timestamp::new(pts.unwrap_or(0), base));
426 }
427 }
428 Ok(to.rescale(base, Rounding::Down))
429 }
430}
431
432impl std::fmt::Debug for Reader {
433 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434 f.debug_struct("Reader")
435 .field("format", &self.format.name())
436 .field("streams", &self.streams().len())
437 .finish()
438 }
439}
440
441/// Read until `buf` is full or the source ends; answers how much arrived.
442fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
443 let mut at = 0;
444 while at < buf.len() {
445 match r.read(&mut buf[at..]) {
446 Ok(0) => break,
447 Ok(n) => at += n,
448 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
449 Err(e) => return Err(Error::Io(e)),
450 }
451 }
452 Ok(at)
453}
454
455fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
456 src.rewind()?;
457 let (spec, frames) = {
458 let reader = ec_riff::WavReader::new(&mut src)?;
459 (reader.spec(), reader.duration())
460 };
461 let start = src.stream_position()?;
462 let (params, block_align) = raw::wav_parameters(spec)?;
463 // A `data` size the header did not state (a streamed writer's placeholder)
464 // means the file itself is the bound.
465 let audio_end = frames
466 .map(|n| start + n * block_align as u64)
467 .unwrap_or(end)
468 .min(end);
469 let total = frames.or(Some((audio_end - start) / block_align as u64));
470 let demuxer = raw::RawDemuxer::new(
471 src,
472 raw::Kind::Wav { block_align },
473 params,
474 start,
475 audio_end,
476 total,
477 None,
478 )?;
479 Ok(Reader::wrap(
480 Format::Wav,
481 Box::new(demuxer),
482 Tags::default(),
483 vec![0],
484 ))
485}
486
487fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
488 let base = tags::id3v2_len(head).unwrap_or(0);
489 src.seek(SeekFrom::Start(base))?;
490 let mut magic = [0u8; 4];
491 read_upto(&mut src, &mut magic)?;
492 if &magic != b"fLaC" {
493 return Err(Error::corrupt("FLAC: no stream marker"));
494 }
495 let mut info: Option<ec_flac::StreamInfo> = None;
496 let mut tags = Tags::default();
497 let mut at = base + 4;
498 loop {
499 let mut header = [0u8; 4];
500 if read_upto(&mut src, &mut header)? < 4 {
501 return Err(Error::corrupt("FLAC: metadata ended before any frame"));
502 }
503 let last = header[0] & 0x80 != 0;
504 let kind = header[0] & 0x7f;
505 let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])).min(1 << 24);
506 let mut body = vec![0u8; len as usize];
507 read_upto(&mut src, &mut body)?;
508 at += 4 + len;
509 match kind {
510 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
511 4 => tags.merge(tags::from_vorbis_comment(&body)),
512 _ => {}
513 }
514 if last {
515 break;
516 }
517 }
518 let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
519 let params = ec_flac::codec_parameters(&info);
520 let total = match info.total_samples {
521 0 => None,
522 n => Some(n),
523 };
524 let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
525 Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
526}
527
528fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
529 let (start, tags) = id3(&mut src, head, end)?;
530 let mut window = vec![0u8; HEAD.min((end - start) as usize)];
531 src.seek(SeekFrom::Start(start))?;
532 let got = read_upto(&mut src, &mut window)?;
533 window.truncate(got);
534 let at = frame_sync(&window, Format::Mp3)
535 .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
536 let header = ec_mp3::FrameHeader::parse(&window[at..])?;
537 let mut start = start + at as u64;
538 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
539 // A Xing/Info header states the frame count exactly; without one the
540 // duration is the bitrate estimate ffmpeg also falls back to, which is
541 // right for CBR and approximate for VBR.
542 let per_frame = header.samples_per_frame() as u64;
543 let xing = xing_frames(&window[at..], &header);
544 if xing.is_some() {
545 // The Xing frame carries no audio — it is a header wearing a frame's
546 // clothes, and a decoder handed it emits a granule of silence. Both
547 // ffmpeg and this reader start after it.
548 start += header.frame_len().unwrap_or(0) as u64;
549 }
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 ),
566 };
567 let demuxer = raw::RawDemuxer::new(
568 src,
569 raw::Kind::Mp3,
570 raw::mp3_parameters(&header),
571 start,
572 audio_end,
573 total,
574 None,
575 )?
576 .with_initial_padding(padding);
577 Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
578}
579
580fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
581 let (start, tags) = id3(&mut src, head, end)?;
582 let mut window = vec![0u8; HEAD.min((end - start) as usize)];
583 src.seek(SeekFrom::Start(start))?;
584 let got = read_upto(&mut src, &mut window)?;
585 window.truncate(got);
586 let at = frame_sync(&window, Format::Adts)
587 .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
588 let header = ec_aac::parse_adts(&window[at..])?;
589 let start = start + at as u64;
590 let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
591 // ADTS states no duration anywhere: every frame is 1024 samples, so the
592 // file's size over its *average* frame is the estimate — the same one
593 // ffmpeg prints "estimating duration from bitrate" about. Averaged rather
594 // than taken off the first frame, which on a real encode is nothing like
595 // the mean (a 3-second fixture came out 5 seconds long that way).
596 let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
597 while count < 512 {
598 let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
599 break;
600 };
601 if h.frame_length == 0 || walk + h.frame_length > window.len() {
602 break;
603 }
604 sum += h.frame_length as u64;
605 count += 1;
606 walk += h.frame_length;
607 }
608 let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
609 let demuxer = raw::RawDemuxer::new(
610 src,
611 raw::Kind::Adts,
612 raw::adts_parameters(&header),
613 start,
614 audio_end,
615 total,
616 None,
617 )?;
618 Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
619}
620
621/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
622fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
623 let mut tags = Tags::default();
624 let start = match tags::id3v2_len(head) {
625 Some(len) => {
626 let len = len.min(end);
627 let mut tag = vec![0u8; len as usize];
628 src.rewind()?;
629 read_upto(src, &mut tag)?;
630 tags.merge(tags::from_id3v2(&tag));
631 len
632 }
633 None => 0,
634 };
635 // The v1 block at the end fills in what v2 did not say.
636 if end >= 128 {
637 src.seek(SeekFrom::Start(end - 128))?;
638 let mut tail = [0u8; 128];
639 read_upto(src, &mut tail)?;
640 tags.merge(tags::from_id3v1(&tail));
641 }
642 Ok((start, tags))
643}
644
645/// Bytes of ID3v1 at the end of a stream, which are not audio.
646fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
647 if end < 128 {
648 return Ok(0);
649 }
650 src.seek(SeekFrom::Start(end - 128))?;
651 let mut tail = [0u8; 3];
652 read_upto(src, &mut tail)?;
653 Ok(u64::from(&tail == b"TAG") * 128)
654}
655
656/// The frame count a Xing/Info header states, when the first frame carries one.
657fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> {
658 let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
659 let tag = frame.get(at..at + 8)?;
660 if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
661 return None;
662 }
663 let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
664 if flags & 1 == 0 {
665 return None;
666 }
667 let n = frame.get(at + 8..at + 12)?;
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.
692struct 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,
699}
700
701#[cfg(test)]
702mod tests {
703 use super::*;
704
705 #[test]
706 fn magic_numbers_name_their_formats() {
707 assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some(Format::Wav));
708 assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some(Format::Flac));
709 assert_eq!(sniff(b"OggS\0\x02\0\0"), Some(Format::Ogg));
710 assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x01\0\0\0"), Some(Format::Matroska));
711 assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\x02\0"), Some(Format::Mp4));
712 // MPEG-1 Layer III, 128 kbit/s, 44.1 kHz.
713 assert_eq!(sniff(b"\xff\xfb\x90\x00\0\0\0\0\0\0"), Some(Format::Mp3));
714 // ADTS: same sync word, the layer bits MPEG audio reserves.
715 assert_eq!(
716 sniff(b"\xff\xf1\x50\x80\x01\x7f\xfc\0\0\0"),
717 Some(Format::Adts)
718 );
719 assert_eq!(sniff(b"not a media file at all"), None);
720 }
721
722 /// An `.aac` or `.mp3` that opens with a tag is still an `.aac` or `.mp3`.
723 #[test]
724 fn an_id3_tag_does_not_hide_the_format() {
725 let mut file = b"ID3\x03\x00\x00\x00\x00\x00\x0a".to_vec();
726 file.extend_from_slice(&[0u8; 10]);
727 file.extend_from_slice(b"\xff\xfb\x90\x00\0\0\0\0\0\0");
728 assert_eq!(tags::id3v2_len(&file), Some(20));
729 assert_eq!(sniff(&file), Some(Format::Mp3));
730 }
731}