//! Format detection and one reader for every audio file edith opens. //! //! [`Reader`] sniffs the content (never the extension — a mislabelled file is //! still a file), builds the right demuxer, and hands out packets with rational //! timestamps plus a sample-accurate [`Reader::seek`] that reports where it //! actually landed. [`AudioDecoder`] is the registry half: one seat for every //! audio codec the family carries. //! //! What this crate does *not* do is parse containers a sibling crate already //! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to //! [`ec_ogg`], and RIFF/WAVE/AVI to [`ec_riff`]; there is exactly one parser //! for each container family. What is implemented in [`raw`] is the three //! formats that are a codec and nothing else: MP3, FLAC and ADTS. //! //! Two contracts worth knowing: //! //! - **One reader, always.** Opening takes a `Read + Seek` source and never //! reopens it, whatever a seek does. Seeking a Matroska file a hundred times //! costs one file handle and one cue table. //! - **A track this cannot decode is listed, not hidden.** [`Reader::streams`] //! reports every stream the container declares and //! [`Reader::unsupported`] names the ones with no decoder *and why* — a //! DTS track says "DTS", not silence. Cover art is not a video track //! and never appears as one. #![forbid(unsafe_code)] #![warn(missing_docs)] pub mod decoder; mod dts; mod raw; pub mod tags; use std::collections::VecDeque; use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::Path; use ec_core::error::{Error, Result}; use ec_core::packet::{Buf, Packet, PacketFlags}; use ec_core::registry::{ AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, MediaType, SeekMode, StreamInfo, }; use ec_core::timebase::{Rounding, TimeBase, Timestamp}; use ec_core::{ChannelLayout, SampleFormat}; pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip}; pub use tags::Tags; /// Bytes read to sniff a format and to find the first frame of a raw stream. const HEAD: usize = 64 << 10; /// Packets a seek may look past to find one of the stream it was asked about. const SEEK_LOOKAHEAD: usize = 64; /// Samples of synthesis delay every Layer III decoder carries, on top of /// whatever delay the encoder wrote into the gapless tag. The number is the format /// 's, not this implementation's: a gapless tag is written to be read with it. const MP3_DECODER_DELAY: u32 = 529; /// A container (or the lack of one) this crate can open. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Format { /// RIFF/WAVE PCM. Wav, /// Native FLAC. Flac, /// MPEG-1/2/2.5 Layer III, with or without an ID3 tag. Mp3, /// Raw AAC in ADTS framing. Adts, /// Ogg: Vorbis, Opus or FLAC inside it. Ogg, /// Raw DTS core (with or without DTS-HD extension substreams). Dts, /// ISO base media: mp4, m4a, mov. Mp4, /// RIFF/AVI. Avi, /// Matroska and WebM. Matroska, /// Raw AMR storage format (`.amr` / `.awb`). Amr, } impl Format { /// Short lowercase name for logs and capability tables. pub fn name(&self) -> &'static str { match self { Format::Wav => "wav", Format::Flac => "flac", Format::Mp3 => "mp3", Format::Adts => "adts", Format::Dts => "dts", Format::Ogg => "ogg", Format::Mp4 => "mp4", Format::Matroska => "matroska", Format::Avi => "avi", Format::Amr => "amr", } } /// Extensions that usually carry this format. Advisory only: the sniff /// decides. pub fn extensions(&self) -> &'static [&'static str] { match self { Format::Wav => &["wav", "wave"], Format::Flac => &["flac"], Format::Mp3 => &["mp3"], Format::Adts => &["aac", "adts"], Format::Dts => &["dts", "dtshd"], Format::Ogg => &["ogg", "oga", "opus"], Format::Mp4 => &["mp4", "m4a", "m4v", "mov"], Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"], Format::Avi => &["avi"], Format::Amr => &["amr", "awb"], } } } /// The format `head` opens with, by content. /// /// An ID3v2 tag is skipped first, because `.aac` and `.mp3` files both carry /// one and the format is whatever follows it. pub fn sniff(head: &[u8]) -> Option { let at = tags::id3v2_len(head).unwrap_or(0) as usize; let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head); if data.len() >= 12 && &data[..4] == b"RIFF" { match &data[8..12] { b"WAVE" => return Some(Format::Wav), b"AVI " => return Some(Format::Avi), _ => {} } } if ec_amr::container::probe(data).is_some() { return Some(Format::Amr); } if data.starts_with(b"fLaC") { return Some(Format::Flac); } if data.starts_with(b"OggS") { return Some(Format::Ogg); } if ec_matroska::is_matroska(data) { return Some(Format::Matroska); } if ec_mp4::is_mp4(data) { return Some(Format::Mp4); } if dts_chains(data) { return Some(Format::Dts); } // Whichever of the two framed formats starts *first*, and only where three // frames chain: AAC payload bytes routinely parse as a lone MPEG audio // header, which is how an `.aac` file came out an `.mp3` once. for at in 0..data.len().saturating_sub(8).min(SYNC_SCAN) { if data[at] != 0xFF { continue; } for format in [Format::Adts, Format::Mp3] { if chains(&data[at..], format) { return Some(format); } } } None } /// True when `data` opens with DTS access units that chain (or run out of /// data first). fn dts_chains(data: &[u8]) -> bool { let mut at = 0; for _ in 0..SYNC_CHAIN { match dts::access_unit(&data[at..]) { Some((_, len)) => at += len, None => return false, } if at >= data.len() { return true; } } true } /// Offsets a sync search looks through before giving up. const SYNC_SCAN: usize = 8 << 10; /// Consecutive frames that must parse for a sync to be believed. const SYNC_CHAIN: usize = 3; /// One frame's length, as its own format states it. fn frame_len(data: &[u8], format: Format) -> Option { match format { Format::Mp3 => ec_mp3::FrameHeader::parse(data).ok()?.frame_len(), Format::Adts => Some(ec_aac::parse_adts(data).ok()?.frame_length), _ => None, } } /// True when [`SYNC_CHAIN`] frames of `format` chain from the head of `data` /// (or the data runs out first, which is as much as a head can prove). fn chains(data: &[u8], format: Format) -> bool { let mut at = 0; for _ in 0..SYNC_CHAIN { match frame_len(&data[at..], format) { Some(len) if len > 0 => at += len, _ => return false, } if at >= data.len() { return true; } } true } /// The first offset where a frame of `format` really starts. fn frame_sync(data: &[u8], format: Format) -> Option { (0..data.len().saturating_sub(8).min(SYNC_SCAN)) .find(|&at| data[at] == 0xFF && chains(&data[at..], format)) } /// A stream nothing here decodes, and the reason. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Unsupported { /// Index in [`Reader::streams`]. pub stream: u32, /// What the container says it is. pub codec: CodecId, /// Why no decoder was built, in words a user can read. pub reason: String, } /// One open media file: streams in, packets out. pub struct Reader { format: Format, inner: Box, tags: Tags, /// Packets read ahead of the caller by a seek looking for its landing. queue: VecDeque, /// Container-native track id per stream index — a Matroska `TrackNumber`, /// an mp4 `track_ID`, or the index itself. native: Vec, } impl Reader { /// Open `path`, sniffing its content for the format. pub fn open(path: impl AsRef) -> Result { let path = path.as_ref(); let hint = path.extension().and_then(|e| e.to_str()).map(str::to_owned); Reader::new(BufReader::new(File::open(path)?), hint.as_deref()) } /// Open an already-open source. `hint` is an extension, used only when the /// content says nothing. pub fn new(mut src: R, hint: Option<&str>) -> Result { let end = src.seek(SeekFrom::End(0))?; src.rewind()?; let mut head = vec![0u8; HEAD.min(end as usize)]; read_upto(&mut src, &mut head)?; let format = sniff(&head) .or_else(|| { let hint = hint?.to_ascii_lowercase(); [ Format::Wav, Format::Flac, Format::Mp3, Format::Adts, Format::Dts, Format::Ogg, Format::Mp4, Format::Matroska, Format::Avi, Format::Amr, ] .into_iter() .find(|f| f.extensions().contains(&hint.as_str())) }) .ok_or_else(|| { Error::unsupported( "this file", "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, avi, matroska, amr)", ) })?; src.rewind()?; match format { Format::Matroska => { let demuxer = ec_matroska::MatroskaDemuxer::new(src)?; let native = demuxer .streams() .iter() .map(|s| demuxer.track_number(s.index).unwrap_or(u64::from(s.index))) .collect(); Ok(Reader::wrap( format, Box::new(demuxer), Tags::default(), native, )) } Format::Mp4 => { let demuxer = ec_mp4::Mp4Demuxer::new(src)?; let tags = Tags { title: demuxer.title().map(str::to_owned), ..Tags::default() }; let native = (0..demuxer.streams().len() as u64).collect(); Ok(Reader::wrap(format, Box::new(demuxer), tags, native)) } Format::Ogg => { let demuxer = ec_ogg::OggDemuxer::open(src)?; // Vorbis carries its comment packet inside the header triplet // this crate publishes as extradata; Opus does not publish its // tags packet at all, so an `.opus` file reports none. let tags = demuxer .streams() .iter() .find(|s| s.params.codec == CodecId::Vorbis) .and_then(|s| s.params.extradata.as_deref()) .and_then(|data| ec_ogg::xiph_unlace(data).ok()) .and_then(|packets| { packets .get(1) .and_then(|p| p.get(7..)) .map(tags::from_vorbis_comment) }) .unwrap_or_default(); let native = (0..demuxer.streams().len() as u64).collect(); Ok(Reader::wrap(format, Box::new(demuxer), tags, native)) } Format::Wav => open_wav(src, end), Format::Avi => open_avi(src), Format::Amr => { let demuxer = ec_amr::container::AmrDemuxer::new(src)?; Ok(Reader::wrap(format, Box::new(demuxer), Tags::default(), vec![0])) } Format::Flac => open_flac(src, &head, end), Format::Mp3 => open_mp3(src, &head, end), Format::Adts => open_adts(src, &head, end), Format::Dts => open_dts(src, end), } } fn wrap(format: Format, inner: Box, tags: Tags, native: Vec) -> Reader { Reader { format, inner, tags, queue: VecDeque::new(), native, } } /// Which format the content turned out to be. pub fn format(&self) -> Format { self.format } /// Every stream the container declares, decodable or not. pub fn streams(&self) -> &[StreamInfo] { self.inner.streams() } /// The stream of `kind` a caller that just wants "the audio" means: the one /// the container flagged ([`StreamInfo::default`]), and the first of that /// kind where nothing is flagged. /// /// The flag comes first because it is the whole answer to which language a /// dual-audio remux opens in -- a muxer that put the French track second /// and marked it default meant the French one, and file order would play /// the other. pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> { let of_kind = || { self.streams() .iter() .filter(move |s| s.params.codec.media_type() == kind) }; of_kind().find(|s| s.default).or_else(|| of_kind().next()) } /// The container's own id for a stream: a Matroska `TrackNumber`, which is /// how a caller names one language of a dual-audio file. pub fn native_id(&self, stream: u32) -> u64 { self.native .get(stream as usize) .copied() .unwrap_or(u64::from(stream)) } /// The stream index carrying container-native id `id`. pub fn stream_of_native(&self, id: u64) -> Option { self.native.iter().position(|&n| n == id).map(|i| i as u32) } /// What the file says about itself. Empty for a file with no tags, and for /// the formats [`tags`] does not read. pub fn tags(&self) -> &Tags { &self.tags } /// The longest stream's duration, when any stream states or implies one. /// /// What a player would play: [`StreamInfo::initial_padding`] is off it, /// because an MP3's encoder delay is silence the file carries and nobody /// hears. pub fn duration(&self) -> Option { self.streams() .iter() .filter_map(|s| { s.duration.map(|d| { // `initial_padding` is a sample count, not a `time_base` // tick count — the two only coincide when the stream's // time base happens to be `1/sample_rate`, which a // container's own duration field usually is not. let padding_ticks = s .params .audio() .filter(|a| a.sample_rate > 0 && s.initial_padding > 0) .map(|a| { TimeBase::from_rate(a.sample_rate).rescale( i64::from(s.initial_padding), s.time_base, Rounding::Down, ) }) .unwrap_or(0); Timestamp::new(d.saturating_sub(padding_ticks), s.time_base) }) }) .max() } /// Every audio stream with no decoder behind it, and why. /// /// Non-audio streams are not listed: this is an audio probe, and a file's /// picture is another crate's business. pub fn unsupported(&self) -> Vec { self.streams() .iter() .filter(|s| s.params.codec.media_type() == MediaType::Audio) .filter_map(|s| match AudioDecoder::new(&s.params) { Ok(_) => None, Err(e) => Some(Unsupported { stream: s.index, codec: s.params.codec, reason: e.to_string(), }), }) .collect() } /// A decoder for one stream. pub fn make_decoder(&self, stream: u32) -> Result { let info = self .streams() .iter() .find(|s| s.index == stream) .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?; AudioDecoder::new(&info.params) } /// The next packet in storage order, or [`Error::Eof`]. pub fn next_packet(&mut self) -> Result { match self.queue.pop_front() { Some(packet) => Ok(packet), None => self.inner.next_packet(), } } /// Seek `stream` to `to` and answer where the reader actually landed. /// /// The landing is the next packet's own timestamp, so a caller can tell /// how far ahead of (or behind) its target the container put it — which is /// the number a sample-accurate segment start is trimmed against. Nothing /// is reopened and no packet is dropped: packets of other streams read on /// the way to the landing are queued, not discarded. pub fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result { self.queue.clear(); self.inner.seek(stream, to, mode)?; let base = self .streams() .iter() .find(|s| s.index == stream) .map(|s| s.time_base) .unwrap_or(TimeBase::MILLIS); for _ in 0..SEEK_LOOKAHEAD { let packet = match self.inner.next_packet() { Ok(packet) => packet, // Seeking past the end lands at the end; the target is as good // an answer as any and the next read says `Eof`. Err(e) if e.is_eof() => return Ok(to.rescale(base, Rounding::Down)), Err(e) => return Err(e), }; let hit = packet.stream == stream; let pts = packet.pts; self.queue.push_back(packet); if hit { return Ok(Timestamp::new(pts.unwrap_or(0), base)); } } Ok(to.rescale(base, Rounding::Down)) } } impl std::fmt::Debug for Reader { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Reader") .field("format", &self.format.name()) .field("streams", &self.streams().len()) .finish() } } /// Read until `buf` is full or the source ends; answers how much arrived. fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result { let mut at = 0; while at < buf.len() { match r.read(&mut buf[at..]) { Ok(0) => break, Ok(n) => at += n, Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} Err(e) => return Err(Error::Io(e)), } } Ok(at) } /// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a /// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the /// `0x2001` format tag that says so outright. The chunk walk is the file's /// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle. fn wav_dts_span(src: &mut R, end: u64) -> Result> { let mut at = 12u64; while at + 8 <= end { src.seek(SeekFrom::Start(at))?; let mut h = [0u8; 8]; if read_upto(src, &mut h)? < 8 { break; } let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]])); let body = at + 8; if &h[..4] == b"data" { // A streamed writer's placeholder size means the file is the bound. let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end { end } else { body + size }; let mut window = vec![0u8; HEAD.min((stop - body) as usize)]; src.seek(SeekFrom::Start(body))?; let got = read_upto(src, &mut window)?; window.truncate(got); return Ok(dts_chains(&window).then_some((body, stop))); } at = body + size + (size & 1); } Ok(None) } fn open_dts_span( mut src: R, format: Format, start: u64, end: u64, ) -> Result { let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; src.seek(SeekFrom::Start(start))?; let got = read_upto(&mut src, &mut window)?; window.truncate(got); let (core, _) = dts::access_unit(&window) .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?; let total = dts_total(&window, end, start); let demuxer = raw::RawDemuxer::new( src, raw::Kind::Dts, raw::dts_parameters(&core), start, end, total, None, )?; Ok(Reader::wrap( format, Box::new(demuxer), Tags::default(), vec![0], )) } fn open_wav(mut src: R, end: u64) -> Result { if let Some((start, stop)) = wav_dts_span(&mut src, end)? { return open_dts_span(src, Format::Wav, start, stop); } src.rewind()?; let (spec, frames, compressed) = { let reader = ec_riff::WavReader::new(&mut src)?; (reader.spec(), reader.duration(), reader.compressed().cloned()) }; let start = src.stream_position()?; if let Some(c) = compressed { let (params, kind) = raw::wav_compressed_parameters(spec, &c)?; let bytes_per = match kind { raw::Kind::WavBlocks { block, samples } => (block as u64, samples), _ => (u64::from(spec.channels.max(1)), 1), }; let audio_end = frames .map(|n| start + n / bytes_per.1 * bytes_per.0) .unwrap_or(end) .min(end); let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1)); let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?; return Ok(Reader::wrap( Format::Wav, Box::new(demuxer), Tags::default(), vec![0], )); } let (params, block_align) = raw::wav_parameters(spec)?; // A `data` size the header did not state (a streamed writer's placeholder) // means the file itself is the bound. let audio_end = frames .map(|n| start + n * block_align as u64) .unwrap_or(end) .min(end); let total = frames.or(Some((audio_end - start) / block_align as u64)); let demuxer = raw::RawDemuxer::new( src, raw::Kind::Wav { block_align }, params, start, audio_end, total, None, )?; Ok(Reader::wrap( Format::Wav, Box::new(demuxer), Tags::default(), vec![0], )) } fn open_flac(mut src: R, head: &[u8], end: u64) -> Result { let base = tags::id3v2_len(head).unwrap_or(0); src.seek(SeekFrom::Start(base))?; let mut magic = [0u8; 4]; read_upto(&mut src, &mut magic)?; if &magic != b"fLaC" { return Err(Error::corrupt("FLAC: no stream marker")); } let mut info: Option = None; let mut tags = Tags::default(); let mut at = base + 4; loop { let mut header = [0u8; 4]; if read_upto(&mut src, &mut header)? < 4 { return Err(Error::corrupt("FLAC: metadata ended before any frame")); } let last = header[0] & 0x80 != 0; let kind = header[0] & 0x7f; let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])) .min(end.saturating_sub(at + 4)); let mut body = vec![0u8; len as usize]; read_upto(&mut src, &mut body)?; at += 4 + len; match kind { 0 => info = Some(ec_flac::StreamInfo::parse(&body)?), 4 => tags.merge(tags::from_vorbis_comment(&body)), _ => {} } if last { break; } } let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?; let params = ec_flac::codec_parameters(&info); let total = match info.total_samples { 0 => None, n => Some(n), }; let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?; Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0])) } fn open_mp3(mut src: R, head: &[u8], end: u64) -> Result { let (start, tags) = id3(&mut src, head, end)?; let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; src.seek(SeekFrom::Start(start))?; let got = read_upto(&mut src, &mut window)?; window.truncate(got); let at = frame_sync(&window, Format::Mp3) .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?; let header = ec_mp3::FrameHeader::parse(&window[at..])?; let mut start = start + at as u64; let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); // A Xing/Info header states the frame count exactly; without one the // duration is the bitrate estimate the oracle also falls back to, which is // right for CBR and approximate for VBR. let per_frame = header.samples_per_frame() as u64; let xing = xing_frames(&window[at..], &header); if xing.is_some() { // The Xing frame carries no audio — it is a header wearing a frame's // clothes, and a decoder handed it emits a granule of silence. Both // the oracle and this reader start after it. start += header.frame_len().unwrap_or(0) as u64; } // Gapless, as the gapless tag states it: a decoder emits the encoder delay // plus its own 529 samples of Layer III synthesis delay before the first // sample that was ever recorded, and the file runs `padding` samples past // the last one. Both are silence a player must not play, and a file with no // tag has neither — its frames are all there is to go on. let (padding, total) = match &xing { Some(x) => ( x.delay + MP3_DECODER_DELAY, Some( (x.frames * per_frame) .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))), ), ), None => ( 0, header .frame_len() .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), ), }; let demuxer = raw::RawDemuxer::new( src, raw::Kind::Mp3, raw::mp3_parameters(&header), start, audio_end, total, None, )? .with_initial_padding(padding); Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0])) } fn open_adts(mut src: R, head: &[u8], end: u64) -> Result { let (start, tags) = id3(&mut src, head, end)?; let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; src.seek(SeekFrom::Start(start))?; let got = read_upto(&mut src, &mut window)?; window.truncate(got); let at = frame_sync(&window, Format::Adts) .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?; let header = ec_aac::parse_adts(&window[at..])?; let start = start + at as u64; let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); // ADTS states no duration anywhere: every frame is 1024 samples, so the // file's size over its *average* frame is the estimate — the same one // the oracle prints "estimating duration from bitrate" about. Averaged rather // than taken off the first frame, which on a real encode is nothing like // the mean (a 3-second fixture came out 5 seconds long that way). let (mut sum, mut count, mut walk) = (0u64, 0u64, at); while count < 512 { let Ok(h) = ec_aac::parse_adts(&window[walk..]) else { break; }; if h.frame_length == 0 || walk + h.frame_length > window.len() { break; } sum += h.frame_length as u64; count += 1; walk += h.frame_length; } let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024); let demuxer = raw::RawDemuxer::new( src, raw::Kind::Adts, raw::adts_parameters(&header), start, audio_end, total, None, )?; Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0])) } fn open_dts(src: R, end: u64) -> Result { open_dts_span(src, Format::Dts, 0, end) } /// Duration estimate in samples: the span's size over the mean access unit /// of the head window. fn dts_total(window: &[u8], end: u64, start: u64) -> Option { let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize); while sum < (1 << 20) { let Some((core, len)) = dts::access_unit(window.get(at..)?) else { break; }; if at + len > window.len() { break; } sum += len as u64; samples += u64::from(core.samples); at += len; } (sum > 0).then(|| (end - start) * samples / sum) } fn open_avi(src: R) -> Result { let reader = ec_riff::AviReader::new(src)?; let demuxer = AviDemuxer::new(reader)?; let native = demuxer .stream_numbers .iter() .map(|&n| u64::from(n)) .collect(); Ok(Reader::wrap( Format::Avi, Box::new(demuxer), Tags::default(), native, )) } struct AviDemuxer { reader: ec_riff::AviReader, streams: Vec, stream_numbers: Vec, samples: Vec, pending: VecDeque, carry: Vec>, sync_bias: Vec, seek_anchor: Vec>, } impl AviDemuxer { fn new(mut reader: ec_riff::AviReader) -> Result> { let mut streams = Vec::new(); let mut stream_numbers = Vec::new(); for (index, s) in reader.audio_streams().iter().enumerate() { let codec = match s.format_tag { 0x0001 if s.bits_per_sample <= 8 => CodecId::PcmU8, 0x0001 => CodecId::PcmS16Le, 0x0055 => CodecId::Mp3, 0x00ff => CodecId::Aac, 0x2000 => CodecId::Ac3, 0x0011 | 0x0002 | 0x0006 | 0x0007 => { ec_riff::WavCompressed::codec_of(s.format_tag).unwrap_or(CodecId::PcmAlaw) } tag => { return Err(Error::unsupported( format!("AVI audio format tag {tag:#06x}"), "no decoder for it exists in this family yet", )); } }; let mut params = CodecParameters::new(codec); params.media = MediaParameters::Audio(AudioParameters { sample_rate: s.sample_rate, layout: ChannelLayout::from_count(usize::from(s.channels).max(1)), format: match codec { CodecId::PcmU8 => Some(SampleFormat::U8), CodecId::PcmS16Le => Some(SampleFormat::S16), CodecId::ImaAdpcmWav | CodecId::MsAdpcm | CodecId::PcmAlaw | CodecId::PcmMulaw => Some(SampleFormat::S16), _ => None, }, bits_per_sample: (s.bits_per_sample > 0).then_some(u32::from(s.bits_per_sample)), }); let extra = reader.audio_extradata(index); if !extra.is_empty() && matches!(codec, CodecId::ImaAdpcmWav | CodecId::MsAdpcm) { params.extradata = Some(Buf::copy_from_slice(extra)); } let mut info = StreamInfo::new( index as u32, TimeBase::from_rate(s.sample_rate.max(1)), params, ); if s.length > 0 { info.duration = Some(avi_units_to_samples(*s, u64::from(s.length)) as i64); } streams.push(info); stream_numbers.push(s.index); } if streams.is_empty() { return Err(Error::unsupported( "this AVI file", "it declares no audio stream this reader can hand out", )); } let samples = vec![0; streams.len()]; let carry = vec![Vec::new(); streams.len()]; let seek_anchor = vec![None; streams.len()]; let sync_bias = avi_sync_biases(&mut reader, &streams, &stream_numbers)?; reader.rewind(); Ok(AviDemuxer { reader, streams, stream_numbers, samples, pending: VecDeque::new(), carry, sync_bias, seek_anchor, }) } fn queue_chunk(&mut self, chunk: ec_riff::AviPacket) -> Result<()> { let Some(stream) = self.stream_numbers.iter().position(|&n| n == chunk.stream) else { return Ok(()); }; let codec = self.streams[stream].params.codec; match codec { CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac => { self.queue_elementary_chunk(stream, chunk.data, codec) } CodecId::ImaAdpcmWav | CodecId::MsAdpcm => { // One decodable block per packet. let avi = self.reader.audio_streams().get(stream).copied(); let (ba, ch) = avi.map_or((0usize, 1u32), |s| { (usize::from(s.block_align), u32::from(s.channels.max(1))) }); let spb = ec_riff::WavCompressed::new( avi.map_or(0, |s| s.format_tag), ch as u16, ba as u16, &[], ) .map_or(0, |c| u64::from(c.samples_per_block)); if ba == 0 || spb == 0 { return Ok(()); } for block in chunk.data.chunks(ba).filter(|b| b.len() == ba) { self.push_packet(stream, Buf::copy_from_slice(block), spb); } Ok(()) } CodecId::PcmAlaw | CodecId::PcmMulaw => { let ch = self .reader .audio_streams() .get(stream) .map_or(1usize, |s| usize::from(s.channels.max(1))); let frames = (chunk.data.len() / ch) as u64; self.push_packet(stream, Buf::from_vec(chunk.data), frames); Ok(()) } _ => { let frames = match codec { CodecId::PcmU8 | CodecId::PcmS16Le => { let block = self .reader .audio_streams() .get(stream) .map_or(1usize, |s| usize::from(s.block_align).max(1)); (chunk.data.len() / block) as u64 } _ => 0, }; self.push_packet(stream, Buf::from_vec(chunk.data), frames); Ok(()) } } } fn queue_elementary_chunk( &mut self, stream: usize, chunk: Vec, codec: CodecId, ) -> Result<()> { let avi_stream = self .stream_numbers .get(stream) .and_then(|n| self.reader.audio_streams().iter().find(|s| s.index == *n)) .copied(); let mut data = std::mem::take(&mut self.carry[stream]); data.extend_from_slice(&chunk); let mut at = 0usize; let mut skipped = 0usize; while at < data.len() { match avi_elementary_frame(codec, &data[at..]) { Ok(Some((size, frames))) if at + size <= data.len() => { if skipped > 0 && matches!(codec, CodecId::Ac3 | CodecId::EAc3) && ec_ac3::Ac3Decoder::new() .decode_frame(&data[at..at + size]) .is_err() { at += 1; skipped += 1; continue; } if skipped > 0 { if let Some(s) = avi_stream { let skipped_samples = avi_units_to_samples(s, skipped as u64); let initial = self.sync_bias.get(stream).copied().unwrap_or(0); if self.samples[stream] != 0 || skipped_samples > initial { self.samples[stream] = self.samples[stream].saturating_add(skipped_samples); } } skipped = 0; } if let Some((anchor, after)) = self.seek_anchor[stream].take() { let phase = self.sync_bias.get(stream).copied().unwrap_or(0); let relative = anchor.saturating_sub(phase); let steps = if after { relative.saturating_add(frames.saturating_sub(1)) / frames } else { relative / frames }; self.samples[stream] = phase.saturating_add(steps.saturating_mul(frames)); } self.push_packet(stream, Buf::copy_from_slice(&data[at..at + size]), frames); at += size; } Ok(Some(_)) => break, Ok(None) => { at += 1; skipped += 1; } Err(e) if e.is_need_more() => break, Err(_) => { at += 1; skipped += 1; } } } self.carry[stream].extend_from_slice(&data[at..]); Ok(()) } fn push_packet(&mut self, stream: usize, data: Buf, frames: u64) { let base = self.streams[stream].time_base; let pts = self.samples[stream]; self.samples[stream] = self.samples[stream].saturating_add(frames); let mut packet = Packet::new(stream as u32, base, data); packet.pts = Some(pts as i64); packet.dts = Some(pts as i64); packet.duration = Some(frames as i64); packet.flags = PacketFlags { keyframe: true, ..PacketFlags::default() }; self.pending.push_back(packet); } } fn avi_elementary_frame(codec: CodecId, data: &[u8]) -> Result> { match codec { CodecId::Ac3 | CodecId::EAc3 => { if data.len() < 2 { return Err(Error::NeedMore); } if data[0] != 0x0b || data[1] != 0x77 { return Ok(None); } ec_ac3::frame_size(data).map(|size| { if data.len() >= size + 2 && data[size..size + 2] != [0x0b, 0x77] { None } else { Some((size, 1536)) } }) } CodecId::Mp3 => { if data.len() < 2 { return Err(Error::NeedMore); } if data[0] != 0xff || data[1] & 0xe0 != 0xe0 { return Ok(None); } let header = ec_mp3::FrameHeader::parse(data)?; if header.layer != 3 { return Ok(None); } Ok(header .frame_len() .map(|size| (size, header.samples_per_frame() as u64))) } CodecId::Aac => { if data.len() < 2 { return Err(Error::NeedMore); } if !ec_aac::is_adts(data) { return Ok(None); } let header = ec_aac::parse_adts(data)?; Ok(Some((header.frame_length, raw::adts_samples(&header)))) } _ => Ok(None), } } fn avi_sync_biases( reader: &mut ec_riff::AviReader, streams: &[StreamInfo], stream_numbers: &[u32], ) -> Result> { let mut out = vec![0; streams.len()]; for (i, info) in streams.iter().enumerate() { if !matches!( info.params.codec, CodecId::Ac3 | CodecId::EAc3 | CodecId::Mp3 | CodecId::Aac ) { continue; } let Some(&native) = stream_numbers.get(i) else { continue; }; let Some(avi_stream) = reader .audio_streams() .iter() .find(|s| s.index == native) .copied() else { continue; }; reader.seek_to_stream_time(native, 0, false)?; for _ in 0..16 { let chunk = match reader.next_packet() { Ok(chunk) => chunk, Err(e) if e.is_eof() => break, Err(e) => return Err(e), }; if chunk.stream != native { continue; } let skip = avi_elementary_leading_skip(info.params.codec, &chunk.data); out[i] = avi_units_to_samples(avi_stream, skip as u64); break; } } Ok(out) } fn avi_elementary_leading_skip(codec: CodecId, data: &[u8]) -> usize { for at in 0..data.len() { match avi_elementary_frame(codec, &data[at..]) { Ok(Some((size, _))) if at + size <= data.len() => return at, Ok(Some(_)) | Err(Error::NeedMore) => return at, Ok(None) | Err(_) => {} } } 0 } fn samples_to_avi_units(stream: ec_riff::AviAudioStream, samples: u64, round_up: bool) -> u64 { let scale = u128::from(stream.scale.max(1)); let rate = u128::from(stream.rate.max(1)); let sample_rate = u128::from(stream.sample_rate.max(1)); let denominator = scale * sample_rate; let numerator = u128::from(samples).saturating_mul(rate); let units = if round_up { numerator.saturating_add(denominator.saturating_sub(1)) / denominator } else { numerator / denominator }; let units = units.min(u128::from(u64::MAX)) as u64; match stream.length { 0 => units, n => units.min(u64::from(n)), } } fn avi_units_to_samples(stream: ec_riff::AviAudioStream, units: u64) -> u64 { let n = u128::from(units) .saturating_mul(u128::from(stream.scale.max(1))) .saturating_mul(u128::from(stream.sample_rate.max(1))); (n / u128::from(stream.rate.max(1))).min(u128::from(u64::MAX)) as u64 } impl Demuxer for AviDemuxer { fn streams(&self) -> &[StreamInfo] { &self.streams } fn next_packet(&mut self) -> Result { loop { if let Some(packet) = self.pending.pop_front() { return Ok(packet); } match self.reader.next_packet() { Ok(chunk) => self.queue_chunk(chunk)?, Err(e) if e.is_eof() => return Err(Error::Eof), Err(e) => return Err(e), } } } fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { let local = self .streams .iter() .position(|s| s.index == stream) .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?; let avi_stream_no = self.stream_numbers[local]; let avi_stream = *self .reader .audio_streams() .iter() .find(|s| s.index == avi_stream_no) .ok_or_else(|| Error::corrupt(format!("AVI: no audio stream {avi_stream_no}")))?; let base = self.streams[local].time_base; let target_samples = to.rescale(base, Rounding::Down).ticks.max(0) as u64; let seek_units = samples_to_avi_units( avi_stream, target_samples, matches!(mode, SeekMode::SyncAfter), ); let landed_units = self.reader.seek_to_stream_time( avi_stream_no, seek_units, matches!(mode, SeekMode::SyncAfter), )?; self.pending.clear(); for carry in &mut self.carry { carry.clear(); } self.samples[local] = avi_units_to_samples(avi_stream, landed_units) .saturating_sub(self.sync_bias.get(local).copied().unwrap_or(0)); self.seek_anchor[local] = Some(( avi_units_to_samples(avi_stream, seek_units), matches!(mode, SeekMode::SyncAfter), )); Ok(()) } } /// Skip an ID3v2 tag at the head of a stream, reading its text on the way past. fn id3(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> { let mut tags = Tags::default(); let start = match tags::id3v2_len(head) { Some(len) => { let len = len.min(end); let mut tag = vec![0u8; len as usize]; src.rewind()?; read_upto(src, &mut tag)?; tags.merge(tags::from_id3v2(&tag)); len } None => 0, }; // The v1 block at the end fills in what v2 did not say. if end >= 128 { src.seek(SeekFrom::Start(end - 128))?; let mut tail = [0u8; 128]; read_upto(src, &mut tail)?; tags.merge(tags::from_id3v1(&tail)); } Ok((start, tags)) } /// Bytes of ID3v1 at the end of a stream, which are not audio. fn id3v1_len(src: &mut R, end: u64) -> Result { if end < 128 { return Ok(0); } src.seek(SeekFrom::Start(end - 128))?; let mut tail = [0u8; 3]; read_upto(src, &mut tail)?; Ok(u64::from(&tail == b"TAG") * 128) } /// The frame count a Xing/Info header states, when the first frame carries one. fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { let at = 4 + usize::from(header.crc) * 2 + header.side_info_len(); let tag = frame.get(at..at + 8)?; if &tag[..4] != b"Xing" && &tag[..4] != b"Info" { return None; } let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]); if flags & 1 == 0 { return None; } let n = frame.get(at + 8..at + 12)?; let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])); // The gapless extension sits behind whichever optional fields the flags // claimed -- frame count, byte count, the 100-byte seek table, quality -- // and states the two trims 21 bytes into itself, twelve bits each. let mut extension_at = at + 12; extension_at += usize::from(flags & 2 != 0) * 4; extension_at += usize::from(flags & 4 != 0) * 100; extension_at += usize::from(flags & 8 != 0) * 4; let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) { Some(&[a, b, c]) => ( u32::from(a) << 4 | u32::from(b) >> 4, (u32::from(b) & 0xF) << 8 | u32::from(c), ), _ => (0, 0), }; Some(Xing { frames, delay, padding, }) } /// What an MP3's Xing/Info header states: how long the file is, and the two /// silences the encoder had to add to make whole frames of it. struct Xing { /// Audio frames in the file, the header frame itself excluded. frames: u64, /// Encoder delay: samples of silence in front of the first real one. delay: u32, /// Encoder padding: samples of silence after the last real one. padding: u32, } #[cfg(test)] mod tests { use super::*; #[test] fn magic_numbers_name_their_formats() { assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some(Format::Wav)); assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some(Format::Flac)); assert_eq!(sniff(b"OggS\0\x02\0\0"), Some(Format::Ogg)); assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x01\0\0\0"), Some(Format::Matroska)); assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\x02\0"), Some(Format::Mp4)); // MPEG-1 Layer III, 128 kbit/s, 44.1 kHz. assert_eq!(sniff(b"\xff\xfb\x90\x00\0\0\0\0\0\0"), Some(Format::Mp3)); // ADTS: same sync word, the layer bits MPEG audio reserves. assert_eq!( sniff(b"\xff\xf1\x50\x80\x01\x7f\xfc\0\0\0"), Some(Format::Adts) ); assert_eq!(sniff(b"not a media file at all"), None); } /// `initial_padding` is a *sample* count while a stream's `duration` is in /// `time_base` ticks -- for a Matroska file whose `TimestampScale` is not /// `1/sample_rate` (the common case: ticks are milliseconds), subtracting /// one from the other unconverted lopped a third off an AAC track's /// stated length (3.021 s of `CodecDelay`-bearing audio reported as 1.997 /// s: `1024` samples read straight off as `1024` one-millisecond ticks). #[test] fn duration_converts_initial_padding_out_of_sample_units() { let reader = Reader::open(ec_testkit::fixture("audio/aac-mka-stereo-48000.mka")).unwrap(); let d = reader.duration().expect("a stated duration").as_secs_f64(); assert!((d - 3.0).abs() < 0.1, "duration {d}, want ~3.0s"); } /// An `.aac` or `.mp3` that opens with a tag is still an `.aac` or `.mp3`. #[test] fn an_id3_tag_does_not_hide_the_format() { let mut file = b"ID3\x03\x00\x00\x00\x00\x00\x0a".to_vec(); file.extend_from_slice(&[0u8; 10]); file.extend_from_slice(b"\xff\xfb\x90\x00\0\0\0\0\0\0"); assert_eq!(tags::id3v2_len(&file), Some(20)); assert_eq!(sniff(&file), Some(Format::Mp3)); } }