forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB98eeb6cTahinli3 months ago90 commits

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