forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB339d121Tahinli2 months ago3332 commits

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