forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBe18142dTahinli8 hours ago4543 commits

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