forge
Explore
Log in

Don't you dare go Hollow

One sniffing reader and one decoder registry for every audio file

Browse files at this commit

51de303d1070b3f8030797d011ab304e38413bfaAhmet Kaan GümüşParent: 5a98e1b
  • feat
    • one sniffing reader and one decoder registry for every audio file
Show full message
feat(probe): one sniffing reader and one decoder registry for every audio file

Content decides the format, never the extension: RIFF, fLaC, OggS, EBML
and ftyp by magic, MP3 and ADTS by three chaining frames after any ID3
tag (a lone MPEG audio header turns up inside AAC payload often enough
that a single sync is not evidence).

WAV, MP3, FLAC and ADTS are demuxed here — one walk, four framings, a
frame index built on the first seek so a landing is sample-accurate.
Ogg, mp4 and Matroska are delegated to their own crates: there is one
EBML parser in this family and it is ec-matroska (cargo tree -p ec-probe
shows the edge). Everything is served on the one reader the file was
opened with, however many times it is seeked.

Reader::seek answers where it actually landed, which is the number a
segment start is trimmed against. Reader::unsupported names every audio
track with no decoder and why. Cover art is not a video track and never
appears as one. Tags: ID3v1/v2 and Vorbis comments; mp4 ilst is not read
(edith reads no metadata today) and says so in the module docs.

Verified: 26-file fixture matrix (format, codec, channels, packet counts
against ffprobe, sample counts against ffmpeg), 100 random seeks per
file each landing at or before its target within the container's own
granularity, and a 9-file sweep of the real library covering aac, ac3,
eac3, opus, mp3 and a TrueHD remux whose unplayable track is listed.
Cargo.tomlmodified+7 -0
@@ -9,10 +9,13 @@ license = "MIT OR Apache-2.0"
9 authors = ["Ahmet Kaan Gümüş"]9 authors = ["Ahmet Kaan Gümüş"]
10 10
11 [workspace.dependencies]11 [workspace.dependencies]
12+ec-aac = { path = "crates/ec-aac", version = "0.1.0" }
12 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }13 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }
14+ec-alac = { path = "crates/ec-alac", version = "0.1.0" }
13 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }15 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }
14 ec-core = { path = "crates/ec-core", version = "0.1.0" }16 ec-core = { path = "crates/ec-core", version = "0.1.0" }
15 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }17 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
18+ec-flac = { path = "crates/ec-flac", version = "0.1.0" }
16 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }19 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
17 ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }20 ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }
18 ec-image = { path = "crates/ec-image", version = "0.1.0" }21 ec-image = { path = "crates/ec-image", version = "0.1.0" }
@@ -20,7 +23,11 @@ ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
20 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }23 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
21 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }24 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }
22 ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }25 ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }
26+ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" }
27+ec-opus = { path = "crates/ec-opus", version = "0.1.0" }
28+ec-probe = { path = "crates/ec-probe", version = "0.1.0" }
23 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }29 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
30+ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" }
24 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }31 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }
25 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).32 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
26 wide = "1.5"33 wide = "1.5"
crates/ec-probe/Cargo.tomladded+21 -0
@@ -0,0 +1,21 @@
1+[package]
2+name = "ec-probe"
3+description = "Format detection and one unified audio reader: WAV/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-aac = { workspace = true }
11+ec-ac3 = { workspace = true }
12+ec-alac = { workspace = true }
13+ec-core = { workspace = true }
14+ec-flac = { workspace = true }
15+ec-matroska = { workspace = true }
16+ec-mp3 = { workspace = true }
17+ec-mp4 = { workspace = true }
18+ec-ogg = { workspace = true }
19+ec-opus = { workspace = true }
20+ec-riff = { workspace = true }
21+ec-vorbis = { workspace = true }
crates/ec-probe/src/decoder.rsadded+376 -0
@@ -0,0 +1,376 @@
1+//! One decoder seat for every audio codec the family carries: packets in,
2+//! interleaved `f32` out, in film channel order.
3+//!
4+//! This is the registry half of the probe. A caller that has a stream from
5+//! [`crate::Reader`] asks for [`AudioDecoder::new`] and gets either a decoder
6+//! or an [`ec_core::Error::Unsupported`] that names the codec *and* why nothing
7+//! here decodes it — a refusal string with no capability behind it is a bug,
8+//! not a message.
9+
10+use ec_core::error::{Error, Result};
11+use ec_core::frame::{Frame, SampleFormat};
12+use ec_core::packet::Packet;
13+use ec_core::registry::{CodecId, CodecParameters, Decoder};
14+
15+/// Which family decoder is doing the work.
16+enum Inner {
17+ Flac(Box<ec_flac::FlacDecoder>),
18+ Mp3(Box<ec_mp3::Mp3Decoder>),
19+ Vorbis(Box<ec_vorbis::VorbisDecoder>),
20+ Ac3(Box<ec_ac3::Ac3Decoder>),
21+ Aac(Box<ec_aac::AacDecoder>),
22+ Alac(Box<ec_alac::AlacDecoder>),
23+ Opus(Box<ec_opus::MultistreamDecoder>),
24+ /// PCM needs no decoder, only a reading of the bytes.
25+ Pcm(CodecId),
26+}
27+
28+/// A decoder for one audio stream.
29+pub struct AudioDecoder {
30+ inner: Inner,
31+ codec: CodecId,
32+ channels: usize,
33+ sample_rate: u32,
34+}
35+
36+impl std::fmt::Debug for AudioDecoder {
37+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38+ f.debug_struct("AudioDecoder")
39+ .field("codec", &self.codec.name())
40+ .field("channels", &self.channels)
41+ .field("sample_rate", &self.sample_rate)
42+ .finish()
43+ }
44+}
45+
46+impl AudioDecoder {
47+ /// A decoder for the stream `params` describes.
48+ pub fn new(params: &CodecParameters) -> Result<AudioDecoder> {
49+ let audio = params
50+ .audio()
51+ .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?;
52+ let channels = audio.layout.channel_count().max(1);
53+ let sample_rate = audio.sample_rate;
54+ let extradata = params.extradata.as_deref();
55+ let inner = match params.codec {
56+ CodecId::Flac => {
57+ let mut params = params.clone();
58+ params.extradata = flac_stream_info(extradata.unwrap_or_default())
59+ .map(ec_core::packet::Buf::copy_from_slice);
60+ Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?))
61+ }
62+ CodecId::Mp3 => Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?)),
63+ CodecId::Vorbis => {
64+ let data = extradata.ok_or_else(|| {
65+ Error::corrupt("a Vorbis stream with no header triplet in its extradata")
66+ })?;
67+ let headers = ec_ogg::xiph_unlace(data)?;
68+ Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?))
69+ }
70+ CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())),
71+ CodecId::Aac => {
72+ let decoder = match extradata {
73+ Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?,
74+ // ADTS states its own configuration in every frame.
75+ None => ec_aac::AacDecoder::new(),
76+ };
77+ Inner::Aac(Box::new(decoder))
78+ }
79+ CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters(
80+ params.clone(),
81+ )?)),
82+ CodecId::Opus => {
83+ let head = extradata.unwrap_or_default();
84+ let (streams, coupled, mapping) = opus_layout(head, channels)?;
85+ // 48 kHz whatever the container says: it is the only rate Opus
86+ // decodes at, and the rate its timestamps are in.
87+ Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate(
88+ 48_000, streams, coupled, &mapping,
89+ )?))
90+ }
91+ codec if is_pcm(codec) => Inner::Pcm(codec),
92+ codec => {
93+ return Err(Error::unsupported(
94+ format!("the {} track", codec.name()),
95+ match codec.media_type() {
96+ ec_core::MediaType::Audio => {
97+ "no decoder for it exists in this family (yet)"
98+ }
99+ _ => "this is an audio probe; picture and subtitles decode elsewhere",
100+ },
101+ ));
102+ }
103+ };
104+ Ok(AudioDecoder {
105+ inner,
106+ codec: params.codec,
107+ channels,
108+ sample_rate: match params.codec {
109+ CodecId::Opus => 48_000,
110+ _ => sample_rate,
111+ },
112+ })
113+ }
114+
115+ /// Which codec this is decoding.
116+ pub fn codec(&self) -> CodecId {
117+ self.codec
118+ }
119+
120+ /// Channels the decoder emits.
121+ pub fn channels(&self) -> usize {
122+ self.channels
123+ }
124+
125+ /// Rate the decoder emits at.
126+ pub fn sample_rate(&self) -> u32 {
127+ self.sample_rate
128+ }
129+
130+ /// One packet in, interleaved `f32` out, normalised to -1.0..=1.0.
131+ ///
132+ /// `out` is cleared first: a packet that decodes to nothing (a header
133+ /// packet, a frame the decoder swallowed) leaves it empty rather than
134+ /// leaving the caller with the previous packet's audio.
135+ pub fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
136+ out.clear();
137+ match &mut self.inner {
138+ Inner::Flac(d) => drain(d.as_mut(), packet, out)?,
139+ Inner::Mp3(d) => drain(d.as_mut(), packet, out)?,
140+ Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?,
141+ Inner::Ac3(d) => drain(d.as_mut(), packet, out)?,
142+ Inner::Aac(d) => {
143+ let audio = d.decode(&packet.data, packet.pts)?;
144+ self.channels = usize::from(audio.channels).max(1);
145+ if audio.sample_rate > 0 {
146+ self.sample_rate = audio.sample_rate;
147+ }
148+ out.extend_from_slice(&audio.samples);
149+ }
150+ Inner::Alac(d) => {
151+ let scale = match d.cookie().sample_format() {
152+ SampleFormat::S16 => 1.0 / 32768.0,
153+ _ => 1.0 / 2147483648.0,
154+ };
155+ out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale));
156+ }
157+ Inner::Opus(d) => {
158+ let samples = d.decode_packet(&packet.data)?;
159+ out.extend_from_slice(&samples);
160+ }
161+ Inner::Pcm(codec) => pcm(*codec, &packet.data, out),
162+ }
163+ Ok(())
164+ }
165+
166+ /// Drop everything buffered from before a seek.
167+ pub fn reset(&mut self) {
168+ match &mut self.inner {
169+ Inner::Flac(d) => d.reset(),
170+ Inner::Mp3(d) => d.reset(),
171+ Inner::Vorbis(d) => d.reset(),
172+ Inner::Ac3(d) => d.reset(),
173+ Inner::Aac(d) => **d = ec_aac::AacDecoder::new(),
174+ Inner::Alac(d) => d.reset(),
175+ Inner::Opus(d) => d.reset(),
176+ Inner::Pcm(_) => {}
177+ }
178+ }
179+}
180+
181+/// The bare 34-byte `STREAMINFO` inside whatever a container calls FLAC
182+/// extradata.
183+///
184+/// Three shapes carry the same block: Matroska's `CodecPrivate` is the whole
185+/// `fLaC` header chain, mp4's `dfLa` is a version word and then the blocks,
186+/// and Ogg's first packet has a `\x7fFLAC` wrapper in front of that. Rather
187+/// than encode three offsets, this looks for the one block header that can
188+/// only be `STREAMINFO`: type 0, length 34.
189+fn flac_stream_info(data: &[u8]) -> Option<&[u8]> {
190+ if data.len() == 34 {
191+ return Some(data);
192+ }
193+ for at in 0..data.len().saturating_sub(38).min(16) {
194+ let head = &data[at..at + 4];
195+ let len = u32::from_be_bytes([0, head[1], head[2], head[3]]);
196+ if head[0] & 0x7f == 0 && len == 34 {
197+ return data.get(at + 4..at + 38);
198+ }
199+ }
200+ // Nothing recognisable: hand the bytes over as they came and let the
201+ // decoder read the frames' own headers instead.
202+ None
203+}
204+
205+/// True for the PCM codec ids, which are read rather than decoded.
206+fn is_pcm(codec: CodecId) -> bool {
207+ matches!(
208+ codec,
209+ CodecId::PcmU8
210+ | CodecId::PcmS16Le
211+ | CodecId::PcmS16Be
212+ | CodecId::PcmS24Le
213+ | CodecId::PcmS32Le
214+ | CodecId::PcmF32Le
215+ )
216+}
217+
218+/// Push one packet through an [`ec_core::Decoder`] and take every frame it
219+/// yields, converted to interleaved `f32`.
220+fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
221+ decoder.send_packet(packet)?;
222+ loop {
223+ match decoder.receive_frame() {
224+ Ok(Frame::Audio(frame)) => interleave(&frame, out),
225+ Ok(Frame::Video(_)) => {
226+ return Err(Error::corrupt("an audio decoder produced a picture"));
227+ }
228+ Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
229+ Err(e) => return Err(e),
230+ }
231+ }
232+}
233+
234+/// One decoded frame appended to `out` as interleaved, normalised `f32`.
235+fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) {
236+ let channels = frame.channels().max(1);
237+ let width = frame.format.bytes_per_sample();
238+ let read = |plane: &[u8], i: usize| -> f32 {
239+ let at = i * width;
240+ let b = &plane[at..at + width];
241+ match frame.format {
242+ SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0,
243+ SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0,
244+ SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0,
245+ SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]),
246+ SampleFormat::F64 => {
247+ f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32
248+ }
249+ }
250+ };
251+ match frame.planar {
252+ false => {
253+ let Some(plane) = frame.data.first() else {
254+ return;
255+ };
256+ let n = (plane.len() / width).min(frame.samples * channels);
257+ out.extend((0..n).map(|i| read(plane, i)));
258+ }
259+ true => {
260+ for i in 0..frame.samples {
261+ for c in 0..channels {
262+ let Some(plane) = frame.data.get(c) else {
263+ continue;
264+ };
265+ if (i + 1) * width <= plane.len() {
266+ out.push(read(plane, i));
267+ }
268+ }
269+ }
270+ }
271+ }
272+}
273+
274+/// PCM bytes as normalised `f32`.
275+fn pcm(codec: CodecId, data: &[u8], out: &mut Vec<f32>) {
276+ match codec {
277+ CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)),
278+ CodecId::PcmS16Le => out.extend(
279+ data.chunks_exact(2)
280+ .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0),
281+ ),
282+ CodecId::PcmS16Be => out.extend(
283+ data.chunks_exact(2)
284+ .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0),
285+ ),
286+ // 24-bit is stored packed, little-endian, and sign-extends from bit 23.
287+ CodecId::PcmS24Le => out.extend(data.chunks_exact(3).map(|c| {
288+ let v = i32::from_le_bytes([0, c[0], c[1], c[2]]);
289+ v as f32 / 2147483648.0
290+ })),
291+ CodecId::PcmS32Le => out.extend(
292+ data.chunks_exact(4)
293+ .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0),
294+ ),
295+ CodecId::PcmF32Le => out.extend(
296+ data.chunks_exact(4)
297+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
298+ ),
299+ _ => {}
300+ }
301+}
302+
303+/// The stream layout of an Opus track, read off its `OpusHead`.
304+///
305+/// Mapping family 0 is the implied mono/stereo layout the header does not
306+/// spell out; families 1 and 255 carry the table. A header too short to hold
307+/// one is treated as family 0, which is what a `.opus` file with a truncated
308+/// head still plays as.
309+pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> {
310+ let channels = channels.max(1);
311+ let family = head.get(18).copied().unwrap_or(0);
312+ if family == 0 || head.len() < 21 {
313+ let coupled = usize::from(channels >= 2);
314+ let mapping: Vec<u8> = (0..channels.min(2) as u8).collect();
315+ return Ok((channels.min(2) - coupled, coupled, mapping));
316+ }
317+ let streams = usize::from(head[19]);
318+ let coupled = usize::from(head[20]);
319+ let mapping = head
320+ .get(21..21 + channels)
321+ .ok_or_else(|| {
322+ Error::corrupt(format!(
323+ "an OpusHead claiming {channels} channels with a {}-byte mapping table",
324+ head.len().saturating_sub(21)
325+ ))
326+ })?
327+ .to_vec();
328+ Ok((streams, coupled, mapping))
329+}
330+
331+/// The encoder delay an Opus track states in its `OpusHead`, in 48 kHz samples.
332+pub fn opus_pre_skip(head: &[u8]) -> u64 {
333+ match head.get(10..12) {
334+ Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])),
335+ None => 0,
336+ }
337+}
338+
339+#[cfg(test)]
340+mod tests {
341+ use super::*;
342+
343+ #[test]
344+ fn opus_layouts_come_off_the_head_or_are_implied() {
345+ // Family 0 stereo: one coupled stream, no table in the header.
346+ let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00";
347+ assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1]));
348+ assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0]));
349+ assert_eq!(opus_pre_skip(head), 312);
350+
351+ // Family 1, 5.1: four streams of which two are coupled.
352+ let mut six = head[..18].to_vec();
353+ six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]);
354+ assert_eq!(
355+ opus_layout(&six, 6).unwrap(),
356+ (4, 2, vec![0, 4, 1, 2, 3, 5])
357+ );
358+ // A table too short for the channel count is named, not guessed at.
359+ assert!(opus_layout(&six[..23], 6).is_err());
360+ }
361+
362+ #[test]
363+ fn pcm_reads_every_width_at_full_scale() {
364+ let mut out = Vec::new();
365+ pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out);
366+ assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]);
367+ out.clear();
368+ pcm(CodecId::PcmU8, &[0, 128, 255], &mut out);
369+ assert_eq!(out[0], -1.0);
370+ assert_eq!(out[1], 0.0);
371+ out.clear();
372+ // 24-bit sign-extends: 0x800000 is full-scale negative.
373+ pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out);
374+ assert_eq!(out, vec![-1.0]);
375+ }
376+}
crates/ec-probe/src/lib.rsadded+669 -0
@@ -0,0 +1,669 @@
1+//! Format detection and one reader for every audio file edith opens.
2+//!
3+//! [`Reader`] sniffs the content (never the extension — a mislabelled file is
4+//! still a file), builds the right demuxer, and hands out packets with rational
5+//! timestamps plus a sample-accurate [`Reader::seek`] that reports where it
6+//! actually landed. [`AudioDecoder`] is the registry half: one seat for every
7+//! audio codec the family carries.
8+//!
9+//! What this crate does *not* do is parse containers a sibling crate already
10+//! parses. Matroska goes to [`ec_matroska`], mp4 to [`ec_mp4`], Ogg to
11+//! [`ec_ogg`]; there is exactly one EBML parser in this family and it is not
12+//! here. What is implemented in [`raw`] is the four formats that are a codec
13+//! and nothing else: WAV, MP3, FLAC and ADTS.
14+//!
15+//! Two contracts worth knowing:
16+//!
17+//! - **One reader, always.** Opening takes a `Read + Seek` source and never
18+//! reopens it, whatever a seek does. Seeking a Matroska file a hundred times
19+//! costs one file handle and one cue table.
20+//! - **A track this cannot decode is listed, not hidden.** [`Reader::streams`]
21+//! reports every stream the container declares and
22+//! [`Reader::unsupported`] names the ones with no decoder *and why* — a
23+//! TrueHD track says "TrueHD", not silence. Cover art is not a video track
24+//! and never appears as one.
25+
26+#![forbid(unsafe_code)]
27+#![warn(missing_docs)]
28+
29+pub mod decoder;
30+mod raw;
31+pub mod tags;
32+
33+use std::collections::VecDeque;
34+use std::fs::File;
35+use std::io::{BufReader, Read, Seek, SeekFrom};
36+use std::path::Path;
37+
38+use ec_core::error::{Error, Result};
39+use ec_core::packet::Packet;
40+use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo};
41+use ec_core::timebase::{Rounding, TimeBase, Timestamp};
42+
43+pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};
44+pub use tags::Tags;
45+
46+/// Bytes read to sniff a format and to find the first frame of a raw stream.
47+const HEAD: usize = 64 << 10;
48+/// Packets a seek may look past to find one of the stream it was asked about.
49+const SEEK_LOOKAHEAD: usize = 64;
50+
51+/// A container (or the lack of one) this crate can open.
52+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53+pub enum Format {
54+ /// RIFF/WAVE PCM.
55+ Wav,
56+ /// Native FLAC.
57+ Flac,
58+ /// MPEG-1/2/2.5 Layer III, with or without an ID3 tag.
59+ Mp3,
60+ /// Raw AAC in ADTS framing.
61+ Adts,
62+ /// Ogg: Vorbis, Opus or FLAC inside it.
63+ Ogg,
64+ /// ISO base media: mp4, m4a, mov.
65+ Mp4,
66+ /// Matroska and WebM.
67+ Matroska,
68+}
69+
70+impl Format {
71+ /// Short lowercase name for logs and capability tables.
72+ pub fn name(&self) -> &'static str {
73+ match self {
74+ Format::Wav => "wav",
75+ Format::Flac => "flac",
76+ Format::Mp3 => "mp3",
77+ Format::Adts => "adts",
78+ Format::Ogg => "ogg",
79+ Format::Mp4 => "mp4",
80+ Format::Matroska => "matroska",
81+ }
82+ }
83+
84+ /// Extensions that usually carry this format. Advisory only: the sniff
85+ /// decides.
86+ pub fn extensions(&self) -> &'static [&'static str] {
87+ match self {
88+ Format::Wav => &["wav", "wave"],
89+ Format::Flac => &["flac"],
90+ Format::Mp3 => &["mp3"],
91+ Format::Adts => &["aac", "adts"],
92+ Format::Ogg => &["ogg", "oga", "opus"],
93+ Format::Mp4 => &["mp4", "m4a", "m4v", "mov"],
94+ Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"],
95+ }
96+ }
97+}
98+
99+/// The format `head` opens with, by content.
100+///
101+/// An ID3v2 tag is skipped first, because `.aac` and `.mp3` files both carry
102+/// one and the format is whatever follows it.
103+pub fn sniff(head: &[u8]) -> Option<Format> {
104+ let at = tags::id3v2_len(head).unwrap_or(0) as usize;
105+ let data = head.get(at..).filter(|d| !d.is_empty()).unwrap_or(head);
106+ if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WAVE" {
107+ return Some(Format::Wav);
108+ }
109+ if data.starts_with(b"fLaC") {
110+ return Some(Format::Flac);
111+ }
112+ if data.starts_with(b"OggS") {
113+ return Some(Format::Ogg);
114+ }
115+ if ec_matroska::is_matroska(data) {
116+ return Some(Format::Matroska);
117+ }
118+ if ec_mp4::is_mp4(data) {
119+ return Some(Format::Mp4);
120+ }
121+ // Whichever of the two framed formats starts *first*, and only where three
122+ // frames chain: AAC payload bytes routinely parse as a lone MPEG audio
123+ // header, which is how an `.aac` file came out an `.mp3` once.
124+ for at in 0..data.len().saturating_sub(8).min(SYNC_SCAN) {
125+ if data[at] != 0xFF {
126+ continue;
127+ }
128+ for format in [Format::Adts, Format::Mp3] {
129+ if chains(&data[at..], format) {
130+ return Some(format);
131+ }
132+ }
133+ }
134+ None
135+}
136+
137+/// Offsets a sync search looks through before giving up.
138+const SYNC_SCAN: usize = 8 << 10;
139+/// Consecutive frames that must parse for a sync to be believed.
140+const SYNC_CHAIN: usize = 3;
141+
142+/// One frame's length, as its own format states it.
143+fn frame_len(data: &[u8], format: Format) -> Option<usize> {
144+ match format {
145+ Format::Mp3 => ec_mp3::FrameHeader::parse(data).ok()?.frame_len(),
146+ Format::Adts => Some(ec_aac::parse_adts(data).ok()?.frame_length),
147+ _ => None,
148+ }
149+}
150+
151+/// True when [`SYNC_CHAIN`] frames of `format` chain from the head of `data`
152+/// (or the data runs out first, which is as much as a head can prove).
153+fn chains(data: &[u8], format: Format) -> bool {
154+ let mut at = 0;
155+ for _ in 0..SYNC_CHAIN {
156+ match frame_len(&data[at..], format) {
157+ Some(len) if len > 0 => at += len,
158+ _ => return false,
159+ }
160+ if at >= data.len() {
161+ return true;
162+ }
163+ }
164+ true
165+}
166+
167+/// The first offset where a frame of `format` really starts.
168+fn frame_sync(data: &[u8], format: Format) -> Option<usize> {
169+ (0..data.len().saturating_sub(8).min(SYNC_SCAN))
170+ .find(|&at| data[at] == 0xFF && chains(&data[at..], format))
171+}
172+
173+/// A stream nothing here decodes, and the reason.
174+#[derive(Debug, Clone, PartialEq, Eq)]
175+pub struct Unsupported {
176+ /// Index in [`Reader::streams`].
177+ pub stream: u32,
178+ /// What the container says it is.
179+ pub codec: CodecId,
180+ /// Why no decoder was built, in words a user can read.
181+ pub reason: String,
182+}
183+
184+/// One open media file: streams in, packets out.
185+pub struct Reader {
186+ format: Format,
187+ inner: Box<dyn Demuxer>,
188+ tags: Tags,
189+ /// Packets read ahead of the caller by a seek looking for its landing.
190+ queue: VecDeque<Packet>,
191+ /// Container-native track id per stream index — a Matroska `TrackNumber`,
192+ /// an mp4 `track_ID`, or the index itself.
193+ native: Vec<u64>,
194+}
195+
196+impl Reader {
197+ /// Open `path`, sniffing its content for the format.
198+ pub fn open(path: impl AsRef<Path>) -> Result<Reader> {
199+ let path = path.as_ref();
200+ let hint = path.extension().and_then(|e| e.to_str()).map(str::to_owned);
201+ Reader::new(BufReader::new(File::open(path)?), hint.as_deref())
202+ }
203+
204+ /// Open an already-open source. `hint` is an extension, used only when the
205+ /// content says nothing.
206+ pub fn new<R: Read + Seek + Send + 'static>(mut src: R, hint: Option<&str>) -> Result<Reader> {
207+ let end = src.seek(SeekFrom::End(0))?;
208+ src.rewind()?;
209+ let mut head = vec![0u8; HEAD.min(end as usize)];
210+ read_upto(&mut src, &mut head)?;
211+ let format = sniff(&head)
212+ .or_else(|| {
213+ let hint = hint?.to_ascii_lowercase();
214+ [
215+ Format::Wav,
216+ Format::Flac,
217+ Format::Mp3,
218+ Format::Adts,
219+ Format::Ogg,
220+ Format::Mp4,
221+ Format::Matroska,
222+ ]
223+ .into_iter()
224+ .find(|f| f.extensions().contains(&hint.as_str()))
225+ })
226+ .ok_or_else(|| {
227+ Error::unsupported(
228+ "this file",
229+ "its first bytes match no format this build reads (wav, flac, mp3, adts, ogg, mp4, matroska)",
230+ )
231+ })?;
232+ src.rewind()?;
233+ match format {
234+ Format::Matroska => {
235+ let demuxer = ec_matroska::MatroskaDemuxer::new(src)?;
236+ let native = demuxer
237+ .streams()
238+ .iter()
239+ .map(|s| demuxer.track_number(s.index).unwrap_or(u64::from(s.index)))
240+ .collect();
241+ Ok(Reader::wrap(
242+ format,
243+ Box::new(demuxer),
244+ Tags::default(),
245+ native,
246+ ))
247+ }
248+ Format::Mp4 => {
249+ let demuxer = ec_mp4::Mp4Demuxer::new(src)?;
250+ let tags = Tags {
251+ title: demuxer.title().map(str::to_owned),
252+ ..Tags::default()
253+ };
254+ let native = (0..demuxer.streams().len() as u64).collect();
255+ Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
256+ }
257+ Format::Ogg => {
258+ let demuxer = ec_ogg::OggDemuxer::open(src)?;
259+ // Vorbis carries its comment packet inside the header triplet
260+ // this crate publishes as extradata; Opus does not publish its
261+ // tags packet at all, so an `.opus` file reports none.
262+ let tags = demuxer
263+ .streams()
264+ .iter()
265+ .find(|s| s.params.codec == CodecId::Vorbis)
266+ .and_then(|s| s.params.extradata.as_deref())
267+ .and_then(|data| ec_ogg::xiph_unlace(data).ok())
268+ .and_then(|packets| packets.get(1).map(|p| tags::from_vorbis_comment(&p[7..])))
269+ .unwrap_or_default();
270+ let native = (0..demuxer.streams().len() as u64).collect();
271+ Ok(Reader::wrap(format, Box::new(demuxer), tags, native))
272+ }
273+ Format::Wav => open_wav(src, end),
274+ Format::Flac => open_flac(src, &head, end),
275+ Format::Mp3 => open_mp3(src, &head, end),
276+ Format::Adts => open_adts(src, &head, end),
277+ }
278+ }
279+
280+ fn wrap(format: Format, inner: Box<dyn Demuxer>, tags: Tags, native: Vec<u64>) -> Reader {
281+ Reader {
282+ format,
283+ inner,
284+ tags,
285+ queue: VecDeque::new(),
286+ native,
287+ }
288+ }
289+
290+ /// Which format the content turned out to be.
291+ pub fn format(&self) -> Format {
292+ self.format
293+ }
294+
295+ /// Every stream the container declares, decodable or not.
296+ pub fn streams(&self) -> &[StreamInfo] {
297+ self.inner.streams()
298+ }
299+
300+ /// The first stream of `kind`, which is what a caller that just wants "the
301+ /// audio" means.
302+ pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> {
303+ self.streams()
304+ .iter()
305+ .find(|s| s.params.codec.media_type() == kind)
306+ }
307+
308+ /// The container's own id for a stream: a Matroska `TrackNumber`, which is
309+ /// how a caller names one language of a dual-audio file.
310+ pub fn native_id(&self, stream: u32) -> u64 {
311+ self.native
312+ .get(stream as usize)
313+ .copied()
314+ .unwrap_or(u64::from(stream))
315+ }
316+
317+ /// The stream index carrying container-native id `id`.
318+ pub fn stream_of_native(&self, id: u64) -> Option<u32> {
319+ self.native.iter().position(|&n| n == id).map(|i| i as u32)
320+ }
321+
322+ /// What the file says about itself. Empty for a file with no tags, and for
323+ /// the formats [`tags`] does not read.
324+ pub fn tags(&self) -> &Tags {
325+ &self.tags
326+ }
327+
328+ /// The longest stream's duration, when any stream states or implies one.
329+ pub fn duration(&self) -> Option<Timestamp> {
330+ self.streams()
331+ .iter()
332+ .filter_map(|s| s.duration.map(|d| Timestamp::new(d, s.time_base)))
333+ .max_by(|a, b| {
334+ a.as_secs_f64()
335+ .partial_cmp(&b.as_secs_f64())
336+ .unwrap_or(std::cmp::Ordering::Equal)
337+ })
338+ }
339+
340+ /// Every audio stream with no decoder behind it, and why.
341+ ///
342+ /// Non-audio streams are not listed: this is an audio probe, and a file's
343+ /// picture is another crate's business.
344+ pub fn unsupported(&self) -> Vec<Unsupported> {
345+ self.streams()
346+ .iter()
347+ .filter(|s| s.params.codec.media_type() == MediaType::Audio)
348+ .filter_map(|s| match AudioDecoder::new(&s.params) {
349+ Ok(_) => None,
350+ Err(e) => Some(Unsupported {
351+ stream: s.index,
352+ codec: s.params.codec,
353+ reason: e.to_string(),
354+ }),
355+ })
356+ .collect()
357+ }
358+
359+ /// A decoder for one stream.
360+ pub fn make_decoder(&self, stream: u32) -> Result<AudioDecoder> {
361+ let info = self
362+ .streams()
363+ .iter()
364+ .find(|s| s.index == stream)
365+ .ok_or_else(|| Error::corrupt(format!("no stream {stream} in this file")))?;
366+ AudioDecoder::new(&info.params)
367+ }
368+
369+ /// The next packet in storage order, or [`Error::Eof`].
370+ pub fn next_packet(&mut self) -> Result<Packet> {
371+ match self.queue.pop_front() {
372+ Some(packet) => Ok(packet),
373+ None => self.inner.next_packet(),
374+ }
375+ }
376+
377+ /// Seek `stream` to `to` and answer where the reader actually landed.
378+ ///
379+ /// The landing is the next packet's own timestamp, so a caller can tell
380+ /// how far ahead of (or behind) its target the container put it — which is
381+ /// the number a sample-accurate segment start is trimmed against. Nothing
382+ /// is reopened and no packet is dropped: packets of other streams read on
383+ /// the way to the landing are queued, not discarded.
384+ pub fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<Timestamp> {
385+ self.queue.clear();
386+ self.inner.seek(stream, to, mode)?;
387+ let base = self
388+ .streams()
389+ .iter()
390+ .find(|s| s.index == stream)
391+ .map(|s| s.time_base)
392+ .unwrap_or(TimeBase::MILLIS);
393+ for _ in 0..SEEK_LOOKAHEAD {
394+ let packet = match self.inner.next_packet() {
395+ Ok(packet) => packet,
396+ // Seeking past the end lands at the end; the target is as good
397+ // an answer as any and the next read says `Eof`.
398+ Err(e) if e.is_eof() => return Ok(to.rescale(base, Rounding::Down)),
399+ Err(e) => return Err(e),
400+ };
401+ let hit = packet.stream == stream;
402+ let pts = packet.pts;
403+ self.queue.push_back(packet);
404+ if hit {
405+ return Ok(Timestamp::new(pts.unwrap_or(0), base));
406+ }
407+ }
408+ Ok(to.rescale(base, Rounding::Down))
409+ }
410+}
411+
412+impl std::fmt::Debug for Reader {
413+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414+ f.debug_struct("Reader")
415+ .field("format", &self.format.name())
416+ .field("streams", &self.streams().len())
417+ .finish()
418+ }
419+}
420+
421+/// Read until `buf` is full or the source ends; answers how much arrived.
422+fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
423+ let mut at = 0;
424+ while at < buf.len() {
425+ match r.read(&mut buf[at..]) {
426+ Ok(0) => break,
427+ Ok(n) => at += n,
428+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
429+ Err(e) => return Err(Error::Io(e)),
430+ }
431+ }
432+ Ok(at)
433+}
434+
435+fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
436+ src.rewind()?;
437+ let (spec, frames) = {
438+ let reader = ec_riff::WavReader::new(&mut src)?;
439+ (reader.spec(), reader.duration())
440+ };
441+ let start = src.stream_position()?;
442+ let (params, block_align) = raw::wav_parameters(spec)?;
443+ // A `data` size the header did not state (a streamed writer's placeholder)
444+ // means the file itself is the bound.
445+ let audio_end = frames
446+ .map(|n| start + n * block_align as u64)
447+ .unwrap_or(end)
448+ .min(end);
449+ let total = frames.or(Some((audio_end - start) / block_align as u64));
450+ let demuxer = raw::RawDemuxer::new(
451+ src,
452+ raw::Kind::Wav { block_align },
453+ params,
454+ start,
455+ audio_end,
456+ total,
457+ None,
458+ )?;
459+ Ok(Reader::wrap(
460+ Format::Wav,
461+ Box::new(demuxer),
462+ Tags::default(),
463+ vec![0],
464+ ))
465+}
466+
467+fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
468+ let base = tags::id3v2_len(head).unwrap_or(0);
469+ src.seek(SeekFrom::Start(base))?;
470+ let mut magic = [0u8; 4];
471+ read_upto(&mut src, &mut magic)?;
472+ if &magic != b"fLaC" {
473+ return Err(Error::corrupt("FLAC: no stream marker"));
474+ }
475+ let mut info: Option<ec_flac::StreamInfo> = None;
476+ let mut tags = Tags::default();
477+ let mut at = base + 4;
478+ loop {
479+ let mut header = [0u8; 4];
480+ if read_upto(&mut src, &mut header)? < 4 {
481+ return Err(Error::corrupt("FLAC: metadata ended before any frame"));
482+ }
483+ let last = header[0] & 0x80 != 0;
484+ let kind = header[0] & 0x7f;
485+ let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])).min(1 << 24);
486+ let mut body = vec![0u8; len as usize];
487+ read_upto(&mut src, &mut body)?;
488+ at += 4 + len;
489+ match kind {
490+ 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
491+ 4 => tags.merge(tags::from_vorbis_comment(&body)),
492+ _ => {}
493+ }
494+ if last {
495+ break;
496+ }
497+ }
498+ let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
499+ let params = ec_flac::codec_parameters(&info);
500+ let total = match info.total_samples {
501+ 0 => None,
502+ n => Some(n),
503+ };
504+ let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
505+ Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
506+}
507+
508+fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
509+ let (start, tags) = id3(&mut src, head, end)?;
510+ let mut window = vec![0u8; HEAD.min((end - start) as usize)];
511+ src.seek(SeekFrom::Start(start))?;
512+ let got = read_upto(&mut src, &mut window)?;
513+ window.truncate(got);
514+ let at = frame_sync(&window, Format::Mp3)
515+ .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
516+ let header = ec_mp3::FrameHeader::parse(&window[at..])?;
517+ let mut start = start + at as u64;
518+ let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
519+ // A Xing/Info header states the frame count exactly; without one the
520+ // duration is the bitrate estimate ffmpeg also falls back to, which is
521+ // right for CBR and approximate for VBR.
522+ let per_frame = header.samples_per_frame() as u64;
523+ let xing = xing_frames(&window[at..], &header);
524+ if xing.is_some() {
525+ // The Xing frame carries no audio — it is a header wearing a frame's
526+ // clothes, and a decoder handed it emits a granule of silence. Both
527+ // ffmpeg and this reader start after it.
528+ start += header.frame_len().unwrap_or(0) as u64;
529+ }
530+ let total = match xing {
531+ Some(frames) => Some(frames * per_frame),
532+ None => header
533+ .frame_len()
534+ .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)),
535+ };
536+ let demuxer = raw::RawDemuxer::new(
537+ src,
538+ raw::Kind::Mp3,
539+ raw::mp3_parameters(&header),
540+ start,
541+ audio_end,
542+ total,
543+ None,
544+ )?;
545+ Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
546+}
547+
548+fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
549+ let (start, tags) = id3(&mut src, head, end)?;
550+ let mut window = vec![0u8; HEAD.min((end - start) as usize)];
551+ src.seek(SeekFrom::Start(start))?;
552+ let got = read_upto(&mut src, &mut window)?;
553+ window.truncate(got);
554+ let at = frame_sync(&window, Format::Adts)
555+ .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
556+ let header = ec_aac::parse_adts(&window[at..])?;
557+ let start = start + at as u64;
558+ let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?);
559+ // ADTS states no duration anywhere: every frame is 1024 samples, so the
560+ // file's size over its *average* frame is the estimate — the same one
561+ // ffmpeg prints "estimating duration from bitrate" about. Averaged rather
562+ // than taken off the first frame, which on a real encode is nothing like
563+ // the mean (a 3-second fixture came out 5 seconds long that way).
564+ let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
565+ while count < 512 {
566+ let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
567+ break;
568+ };
569+ if h.frame_length == 0 || walk + h.frame_length > window.len() {
570+ break;
571+ }
572+ sum += h.frame_length as u64;
573+ count += 1;
574+ walk += h.frame_length;
575+ }
576+ let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
577+ let demuxer = raw::RawDemuxer::new(
578+ src,
579+ raw::Kind::Adts,
580+ raw::adts_parameters(&header),
581+ start,
582+ audio_end,
583+ total,
584+ None,
585+ )?;
586+ Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
587+}
588+
589+/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
590+fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
591+ let mut tags = Tags::default();
592+ let start = match tags::id3v2_len(head) {
593+ Some(len) => {
594+ let len = len.min(end);
595+ let mut tag = vec![0u8; len as usize];
596+ src.rewind()?;
597+ read_upto(src, &mut tag)?;
598+ tags.merge(tags::from_id3v2(&tag));
599+ len
600+ }
601+ None => 0,
602+ };
603+ // The v1 block at the end fills in what v2 did not say.
604+ if end >= 128 {
605+ src.seek(SeekFrom::Start(end - 128))?;
606+ let mut tail = [0u8; 128];
607+ read_upto(src, &mut tail)?;
608+ tags.merge(tags::from_id3v1(&tail));
609+ }
610+ Ok((start, tags))
611+}
612+
613+/// Bytes of ID3v1 at the end of a stream, which are not audio.
614+fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
615+ if end < 128 {
616+ return Ok(0);
617+ }
618+ src.seek(SeekFrom::Start(end - 128))?;
619+ let mut tail = [0u8; 3];
620+ read_upto(src, &mut tail)?;
621+ Ok(u64::from(&tail == b"TAG") * 128)
622+}
623+
624+/// The frame count a Xing/Info header states, when the first frame carries one.
625+fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<u64> {
626+ let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
627+ let tag = frame.get(at..at + 8)?;
628+ if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
629+ return None;
630+ }
631+ let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
632+ if flags & 1 == 0 {
633+ return None;
634+ }
635+ let n = frame.get(at + 8..at + 12)?;
636+ Some(u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])))
637+}
638+
639+#[cfg(test)]
640+mod tests {
641+ use super::*;
642+
643+ #[test]
644+ fn magic_numbers_name_their_formats() {
645+ assert_eq!(sniff(b"RIFF\0\0\0\0WAVEfmt "), Some(Format::Wav));
646+ assert_eq!(sniff(b"fLaC\0\0\0\x22"), Some(Format::Flac));
647+ assert_eq!(sniff(b"OggS\0\x02\0\0"), Some(Format::Ogg));
648+ assert_eq!(sniff(b"\x1a\x45\xdf\xa3\x01\0\0\0"), Some(Format::Matroska));
649+ assert_eq!(sniff(b"\0\0\0\x18ftypisom\0\0\x02\0"), Some(Format::Mp4));
650+ // MPEG-1 Layer III, 128 kbit/s, 44.1 kHz.
651+ assert_eq!(sniff(b"\xff\xfb\x90\x00\0\0\0\0\0\0"), Some(Format::Mp3));
652+ // ADTS: same sync word, the layer bits MPEG audio reserves.
653+ assert_eq!(
654+ sniff(b"\xff\xf1\x50\x80\x01\x7f\xfc\0\0\0"),
655+ Some(Format::Adts)
656+ );
657+ assert_eq!(sniff(b"not a media file at all"), None);
658+ }
659+
660+ /// An `.aac` or `.mp3` that opens with a tag is still an `.aac` or `.mp3`.
661+ #[test]
662+ fn an_id3_tag_does_not_hide_the_format() {
663+ let mut file = b"ID3\x03\x00\x00\x00\x00\x00\x0a".to_vec();
664+ file.extend_from_slice(&[0u8; 10]);
665+ file.extend_from_slice(b"\xff\xfb\x90\x00\0\0\0\0\0\0");
666+ assert_eq!(tags::id3v2_len(&file), Some(20));
667+ assert_eq!(sniff(&file), Some(Format::Mp3));
668+ }
669+}
crates/ec-probe/src/raw.rsadded+394 -0
@@ -0,0 +1,394 @@
1+//! The four formats that are a codec and nothing else: WAV, MP3, FLAC and
2+//! ADTS. One demuxer serves all four, because they differ only in how a frame
3+//! states its own length — everything after that (the packet stream, the frame
4+//! index, sample-accurate seeking) is the same walk.
5+//!
6+//! Framing comes from the codec crates rather than being re-derived here:
7+//! [`ec_mp3::FrameHeader`], [`ec_flac::decode::find_frame_sync`] and
8+//! [`ec_aac::parse_adts`] each already know their own header.
9+
10+use std::io::{Read, Seek, SeekFrom};
11+
12+use ec_core::error::{Error, Result};
13+use ec_core::frame::{ChannelLayout, SampleFormat};
14+use ec_core::packet::{Buf, Packet, PacketFlags};
15+use ec_core::registry::{
16+ AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, SeekMode, StreamInfo,
17+};
18+use ec_core::timebase::{Rounding, TimeBase, Timestamp};
19+
20+/// Bytes read per refill.
21+const CHUNK: usize = 64 << 10;
22+/// Consumed bytes tolerated in front of the window before it is compacted.
23+const COMPACT_AT: usize = 256 << 10;
24+/// Frames of PCM in one WAV packet: big enough that a packet is not a syscall
25+/// per millisecond, small enough to seek inside without decoding a second.
26+const WAV_FRAMES: usize = 4096;
27+
28+/// How a format states the length of one frame.
29+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30+pub(crate) enum Kind {
31+ /// Fixed-size PCM: a "frame" is one interleaved sample.
32+ Wav {
33+ block_align: usize,
34+ },
35+ Mp3,
36+ Flac,
37+ Adts,
38+}
39+
40+/// A frame's byte length and how many inter-channel samples it holds.
41+struct Framing {
42+ bytes: usize,
43+ samples: u64,
44+}
45+
46+/// One elementary audio stream read straight out of a file.
47+pub(crate) struct RawDemuxer<R> {
48+ r: R,
49+ kind: Kind,
50+ streams: Vec<StreamInfo>,
51+ /// Offset of the first frame and one past the last audio byte.
52+ start: u64,
53+ end: u64,
54+ /// Offset the window starts at, and the file offset the reader itself sits
55+ /// at (window end).
56+ pos: u64,
57+ read_at: u64,
58+ buf: Vec<u8>,
59+ head: usize,
60+ /// Next packet's first sample, in the stream's own time base.
61+ sample: u64,
62+ rate: u32,
63+ /// `STREAMINFO`, needed to read a FLAC frame header.
64+ flac: Option<ec_flac::StreamInfo>,
65+ /// `(first sample, offset)` per frame, built on the first seek.
66+ index: Vec<(u64, u64)>,
67+ indexed: bool,
68+}
69+
70+impl<R: Read + Seek> RawDemuxer<R> {
71+ pub(crate) fn new(
72+ mut r: R,
73+ kind: Kind,
74+ params: CodecParameters,
75+ start: u64,
76+ end: u64,
77+ total_samples: Option<u64>,
78+ flac: Option<ec_flac::StreamInfo>,
79+ ) -> Result<RawDemuxer<R>> {
80+ let rate = params
81+ .audio()
82+ .map(|a| a.sample_rate)
83+ .filter(|r| *r > 0)
84+ .ok_or_else(|| Error::corrupt("a raw audio stream with no sample rate"))?;
85+ let mut info = StreamInfo::new(0, TimeBase::from_rate(rate), params);
86+ info.start_time = Some(0);
87+ info.duration = total_samples.map(|n| n as i64);
88+ r.seek(SeekFrom::Start(start))?;
89+ Ok(RawDemuxer {
90+ r,
91+ kind,
92+ streams: vec![info],
93+ start,
94+ end,
95+ pos: start,
96+ read_at: start,
97+ buf: Vec::with_capacity(CHUNK),
98+ head: 0,
99+ sample: 0,
100+ rate,
101+ flac,
102+ index: Vec::new(),
103+ indexed: false,
104+ })
105+ }
106+
107+ /// Samples in a typical frame of this format, for the tail of an estimate.
108+ fn frame_samples(&self) -> u64 {
109+ match self.kind {
110+ Kind::Wav { .. } => WAV_FRAMES as u64,
111+ Kind::Mp3 => 1152,
112+ Kind::Flac => self
113+ .flac
114+ .as_ref()
115+ .map_or(4096, |i| u64::from(i.max_block_size)),
116+ Kind::Adts => 1024,
117+ }
118+ }
119+
120+ /// At least `want` bytes in the window, or fewer at the end of the stream.
121+ fn fill(&mut self, want: usize) -> Result<()> {
122+ if self.head > COMPACT_AT {
123+ self.buf.drain(..self.head);
124+ self.pos += self.head as u64;
125+ self.head = 0;
126+ }
127+ while self.buf.len() - self.head < want && self.read_at < self.end {
128+ let chunk = CHUNK.min((self.end - self.read_at) as usize);
129+ let at = self.buf.len();
130+ self.buf.resize(at + chunk, 0);
131+ let mut got = 0;
132+ while got < chunk {
133+ match self.r.read(&mut self.buf[at + got..]) {
134+ Ok(0) => break,
135+ Ok(n) => got += n,
136+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
137+ Err(e) => return Err(Error::Io(e)),
138+ }
139+ }
140+ self.buf.truncate(at + got);
141+ self.read_at += got as u64;
142+ if got == 0 {
143+ break;
144+ }
145+ }
146+ Ok(())
147+ }
148+
149+ /// The unread bytes of the window.
150+ fn window(&self) -> &[u8] {
151+ &self.buf[self.head..]
152+ }
153+
154+ /// Where the window's head sits in the file.
155+ fn offset(&self) -> u64 {
156+ self.pos + self.head as u64
157+ }
158+
159+ /// Drop the window and resume reading at `offset`.
160+ fn jump(&mut self, offset: u64) -> Result<()> {
161+ self.r.seek(SeekFrom::Start(offset))?;
162+ self.buf.clear();
163+ self.head = 0;
164+ self.pos = offset;
165+ self.read_at = offset;
166+ Ok(())
167+ }
168+
169+ /// The frame at the window's head, or [`Error::Eof`] at the end.
170+ ///
171+ /// Resyncs over junk: a byte that does not open a frame is skipped, which
172+ /// is what carries a reader over an ID3 tag in the middle of a stream or a
173+ /// scrap of a torn download.
174+ fn framing(&mut self) -> Result<Framing> {
175+ let want = match self.kind {
176+ Kind::Wav { block_align } => block_align * WAV_FRAMES,
177+ // A FLAC frame is bounded by the *next* sync word, so the window
178+ // has to hold a whole one plus the head of its successor.
179+ Kind::Flac => 1 << 20,
180+ _ => 8192,
181+ };
182+ let flac = self.flac.clone();
183+ let kind = self.kind;
184+ let mut skipped = 0u64;
185+ loop {
186+ self.fill(want)?;
187+ let left = self.window().len();
188+ if left == 0 {
189+ return Err(Error::Eof);
190+ }
191+ let tail = self.read_at >= self.end;
192+ match frame_at(kind, self.window(), flac.as_ref()) {
193+ Ok(f) => return Ok(f),
194+ Err(e) if e.is_need_more() && tail => {
195+ // The tail of a file: whatever is left is the last frame.
196+ return Ok(Framing {
197+ bytes: left,
198+ samples: self.frame_samples(),
199+ });
200+ }
201+ Err(_) if skipped < (1 << 20) => {
202+ self.head += 1;
203+ skipped += 1;
204+ }
205+ Err(e) => return Err(e),
206+ }
207+ }
208+ }
209+
210+ /// Walk every frame once, recording where each starts.
211+ fn build_index(&mut self) -> Result<()> {
212+ if self.indexed {
213+ return Ok(());
214+ }
215+ let (at, sample) = (self.offset(), self.sample);
216+ self.jump(self.start)?;
217+ let mut sample_at = 0u64;
218+ while self.offset() < self.end {
219+ let f = match self.framing() {
220+ Ok(f) => f,
221+ Err(e) if e.is_eof() => break,
222+ Err(e) => return Err(e),
223+ };
224+ // `framing` may have resynced past junk: index where the frame
225+ // really starts, not where the walk was standing.
226+ self.index.push((sample_at, self.offset()));
227+ sample_at += f.samples;
228+ self.head += f.bytes;
229+ }
230+ self.indexed = true;
231+ // Put the reader back where the caller had it.
232+ self.jump(at)?;
233+ self.sample = sample;
234+ Ok(())
235+ }
236+}
237+
238+/// One frame's geometry, read from the head of `data`.
239+fn frame_at(kind: Kind, data: &[u8], flac: Option<&ec_flac::StreamInfo>) -> Result<Framing> {
240+ match kind {
241+ Kind::Wav { block_align } => {
242+ let frames = (data.len() / block_align).min(WAV_FRAMES);
243+ match frames {
244+ 0 => Err(Error::Eof),
245+ n => Ok(Framing {
246+ bytes: n * block_align,
247+ samples: n as u64,
248+ }),
249+ }
250+ }
251+ Kind::Mp3 => {
252+ let header = ec_mp3::FrameHeader::parse(data)?;
253+ let bytes = header
254+ .frame_len()
255+ .ok_or_else(|| Error::corrupt("mp3: a free-format frame states no length"))?;
256+ if bytes > data.len() {
257+ return Err(Error::NeedMore);
258+ }
259+ Ok(Framing {
260+ bytes,
261+ samples: header.samples_per_frame() as u64,
262+ })
263+ }
264+ Kind::Adts => {
265+ let header = ec_aac::parse_adts(data)?;
266+ if header.frame_length > data.len() {
267+ return Err(Error::NeedMore);
268+ }
269+ Ok(Framing {
270+ bytes: header.frame_length,
271+ samples: 1024 * u64::from(header.raw_blocks),
272+ })
273+ }
274+ Kind::Flac => {
275+ if ec_flac::decode::find_frame_sync(data, 0, flac) != Some(0) {
276+ return Err(Error::corrupt("flac: not a frame header"));
277+ }
278+ let mut r = ec_core::BitReader::new(data);
279+ let header = ec_flac::decode::parse_frame_header(&mut r, flac)?;
280+ // A frame ends where the next one starts; the last frame of a file
281+ // ends at the file's end, which the caller's `NeedMore` handles.
282+ let bytes = ec_flac::decode::find_frame_sync(data, 1, flac).ok_or(Error::NeedMore)?;
283+ Ok(Framing {
284+ bytes,
285+ samples: header.block_size as u64,
286+ })
287+ }
288+ }
289+}
290+
291+impl<R: Read + Seek + Send> Demuxer for RawDemuxer<R> {
292+ fn streams(&self) -> &[StreamInfo] {
293+ &self.streams
294+ }
295+
296+ fn next_packet(&mut self) -> Result<Packet> {
297+ if self.offset() >= self.end {
298+ return Err(Error::Eof);
299+ }
300+ let f = self.framing()?;
301+ let data = Buf::copy_from_slice(&self.window()[..f.bytes]);
302+ self.head += f.bytes;
303+ let pts = self.sample;
304+ self.sample += f.samples;
305+ let mut packet = Packet::new(0, TimeBase::from_rate(self.rate), data);
306+ packet.pts = Some(pts as i64);
307+ packet.dts = Some(pts as i64);
308+ packet.duration = Some(f.samples as i64);
309+ packet.flags = PacketFlags {
310+ keyframe: true,
311+ ..PacketFlags::default()
312+ };
313+ Ok(packet)
314+ }
315+
316+ fn seek(&mut self, _stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
317+ let target = to
318+ .rescale(TimeBase::from_rate(self.rate), Rounding::Down)
319+ .ticks
320+ .max(0) as u64;
321+ // PCM needs no index and no rounding: every sample is a random access
322+ // point, at a byte offset arithmetic gives.
323+ if let Kind::Wav { block_align } = self.kind {
324+ let at = self.start + target * block_align as u64;
325+ self.jump(at.min(self.end))?;
326+ self.sample = target;
327+ return Ok(());
328+ }
329+ self.build_index()?;
330+ let found = self.index.partition_point(|(s, _)| *s <= target);
331+ let i = match mode {
332+ SeekMode::SyncAfter => found.min(self.index.len().saturating_sub(1)),
333+ // At or before: the frame the target sits inside.
334+ _ => found.saturating_sub(1),
335+ };
336+ let (sample, at) = match self.index.get(i) {
337+ Some(&entry) => entry,
338+ None => return Err(Error::Eof),
339+ };
340+ self.jump(at)?;
341+ self.sample = sample;
342+ Ok(())
343+ }
344+}
345+
346+/// Codec parameters for a WAVE stream, whose `fmt ` chunk names its codec
347+/// outright.
348+pub(crate) fn wav_parameters(spec: ec_riff::WavSpec) -> Result<(CodecParameters, usize)> {
349+ let format = spec.sample_format()?;
350+ let codec = match (format, spec.bits_per_sample) {
351+ (SampleFormat::F32, _) => CodecId::PcmF32Le,
352+ (_, 8) => CodecId::PcmU8,
353+ (_, 16) => CodecId::PcmS16Le,
354+ (_, 24) => CodecId::PcmS24Le,
355+ (_, 32) => CodecId::PcmS32Le,
356+ (_, bits) => {
357+ return Err(Error::unsupported(
358+ format!("a {bits}-bit WAVE file"),
359+ "only 8, 16, 24 and 32 bit samples have a PCM codec id",
360+ ));
361+ }
362+ };
363+ let mut params = CodecParameters::new(codec);
364+ params.media = MediaParameters::Audio(AudioParameters {
365+ sample_rate: spec.sample_rate,
366+ layout: spec.layout(),
367+ format: Some(format),
368+ bits_per_sample: Some(u32::from(spec.bits_per_sample)),
369+ });
370+ Ok((params, spec.block_align()))
371+}
372+
373+/// Codec parameters for an ADTS stream, from its first frame header.
374+pub(crate) fn adts_parameters(header: &ec_aac::AdtsHeader) -> CodecParameters {
375+ let mut params = CodecParameters::new(CodecId::Aac);
376+ params.media = MediaParameters::Audio(AudioParameters {
377+ sample_rate: header.sample_rate,
378+ layout: ChannelLayout::from_count(usize::from(header.channels.max(1))),
379+ format: Some(SampleFormat::F32),
380+ bits_per_sample: None,
381+ });
382+ // ADTS states its configuration in every frame, but a decoder built from
383+ // parameters alone still wants the ASC form of it.
384+ params.extradata = Some(Buf::from_vec(ec_aac::audio_specific_config_bytes(
385+ header.sample_rate,
386+ header.channels,
387+ )));
388+ params
389+}
390+
391+/// Codec parameters for an MP3 stream, from its first frame header.
392+pub(crate) fn mp3_parameters(header: &ec_mp3::FrameHeader) -> CodecParameters {
393+ ec_mp3::codec_parameters(header.sample_rate, header.channels())
394+}
crates/ec-probe/src/tags.rsadded+291 -0
@@ -0,0 +1,291 @@
1+//! The handful of tags a media library actually shows: title, artist, album,
2+//! date and track number, out of ID3v1, ID3v2 and Vorbis comments.
3+//!
4+//! Deliberately small. edith reads no metadata at all today (its symphonia
5+//! reader passes `MetadataOptions::default()` and never asks for the result),
6+//! so this exists to keep the door open rather than to be complete: no cover
7+//! art, no arbitrary user frames, and no mp4 `ilst` — an iTunes-tagged `.m4a`
8+//! reports the `moov/udta/name` title only. Adding a surface is a decision for
9+//! whoever needs one, and the parsers below are where it goes.
10+
11+/// What a file says about itself.
12+#[derive(Debug, Default, Clone, PartialEq, Eq)]
13+pub struct Tags {
14+ /// Track title.
15+ pub title: Option<String>,
16+ /// Performing artist.
17+ pub artist: Option<String>,
18+ /// Album (or "content group" in ID3 terms).
19+ pub album: Option<String>,
20+ /// Year or full date, as the file wrote it.
21+ pub date: Option<String>,
22+ /// Track number within its album.
23+ pub track: Option<u32>,
24+}
25+
26+impl Tags {
27+ /// True when nothing was found.
28+ pub fn is_empty(&self) -> bool {
29+ *self == Tags::default()
30+ }
31+
32+ /// Fill any field this does not have from `other`.
33+ pub(crate) fn merge(&mut self, other: Tags) {
34+ self.title = self.title.take().or(other.title);
35+ self.artist = self.artist.take().or(other.artist);
36+ self.album = self.album.take().or(other.album);
37+ self.date = self.date.take().or(other.date);
38+ self.track = self.track.or(other.track);
39+ }
40+
41+ fn set(&mut self, key: &str, value: String) {
42+ if value.is_empty() {
43+ return;
44+ }
45+ let field = match key {
46+ "TIT2" | "TT2" | "TITLE" => &mut self.title,
47+ "TPE1" | "TP1" | "ARTIST" => &mut self.artist,
48+ "TALB" | "TAL" | "ALBUM" => &mut self.album,
49+ "TDRC" | "TYER" | "TYE" | "DATE" => &mut self.date,
50+ "TRCK" | "TRK" | "TRACKNUMBER" => {
51+ // "3/12" is a track number and a total; the number is the part
52+ // anything displays.
53+ self.track = value
54+ .split(['/', ' '])
55+ .next()
56+ .and_then(|n| n.trim().parse().ok());
57+ return;
58+ }
59+ _ => return,
60+ };
61+ if field.is_none() {
62+ *field = Some(value);
63+ }
64+ }
65+}
66+
67+/// Total bytes an ID3v2 tag at the head of a stream occupies, header included.
68+pub(crate) fn id3v2_len(head: &[u8]) -> Option<u64> {
69+ if head.len() < 10 || &head[..3] != b"ID3" {
70+ return None;
71+ }
72+ let size = syncsafe(&head[6..10])?;
73+ // Bit 4 of the flags is a footer, which is another ten bytes.
74+ let footer = u64::from(head[5] & 0x10 != 0) * 10;
75+ Some(10 + u64::from(size) + footer)
76+}
77+
78+/// A 28-bit syncsafe integer.
79+fn syncsafe(b: &[u8]) -> Option<u32> {
80+ let b: [u8; 4] = b.get(..4)?.try_into().ok()?;
81+ if b.iter().any(|&x| x & 0x80 != 0) {
82+ return None;
83+ }
84+ Some(u32::from(b[0]) << 21 | u32::from(b[1]) << 14 | u32::from(b[2]) << 7 | u32::from(b[3]))
85+}
86+
87+/// The text frames of a whole ID3v2 tag (header included).
88+pub(crate) fn from_id3v2(data: &[u8]) -> Tags {
89+ let mut tags = Tags::default();
90+ if id3v2_len(data).is_none() {
91+ return tags;
92+ }
93+ let version = data[3];
94+ // An unsynchronised or compressed tag is left alone rather than
95+ // mis-parsed: the audio is what matters here.
96+ if data[5] & 0x80 != 0 {
97+ return tags;
98+ }
99+ let mut at = 10usize;
100+ // An extended header sits between the header and the first frame.
101+ if data[5] & 0x40 != 0 && version >= 3 {
102+ let len = match version {
103+ 3 => data
104+ .get(at..at + 4)
105+ .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize + 4),
106+ _ => data.get(at..at + 4).and_then(syncsafe).map(|n| n as usize),
107+ };
108+ at += len.unwrap_or(0);
109+ }
110+ let (id_len, size_len) = match version {
111+ 2 => (3, 3),
112+ _ => (4, 4),
113+ };
114+ while at + id_len + size_len <= data.len() {
115+ let id = &data[at..at + id_len];
116+ if id[0] == 0 {
117+ break; // padding
118+ }
119+ let size = match (version, &data[at + id_len..at + id_len + size_len]) {
120+ (2, s) => usize::from(s[0]) << 16 | usize::from(s[1]) << 8 | usize::from(s[2]),
121+ (4, s) => syncsafe(s).unwrap_or(0) as usize,
122+ (_, s) => u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize,
123+ };
124+ let flags = match version {
125+ 2 => 0,
126+ _ => 2,
127+ };
128+ let start = at + id_len + size_len + flags;
129+ let Some(body) = data.get(start..start + size) else {
130+ break;
131+ };
132+ if id[0] == b'T'
133+ && let Ok(key) = std::str::from_utf8(id)
134+ {
135+ tags.set(key, text(body));
136+ }
137+ at = start + size;
138+ }
139+ tags
140+}
141+
142+/// An ID3v2 text frame body: an encoding byte and then the string.
143+fn text(body: &[u8]) -> String {
144+ let Some((&encoding, rest)) = body.split_first() else {
145+ return String::new();
146+ };
147+ let s = match encoding {
148+ // ISO-8859-1: every byte is its own code point.
149+ 0 => rest.iter().map(|&b| char::from(b)).collect(),
150+ 1 | 2 => utf16(rest, encoding == 1),
151+ _ => String::from_utf8_lossy(rest).into_owned(),
152+ };
153+ s.trim_end_matches('\0').trim().to_string()
154+}
155+
156+/// UTF-16, big-endian unless a byte-order mark says otherwise.
157+fn utf16(data: &[u8], bom: bool) -> String {
158+ let (data, little) = match (bom, data) {
159+ (true, [0xFF, 0xFE, rest @ ..]) => (rest, true),
160+ (true, [0xFE, 0xFF, rest @ ..]) => (rest, false),
161+ _ => (data, false),
162+ };
163+ let units: Vec<u16> = data
164+ .chunks_exact(2)
165+ .map(|c| match little {
166+ true => u16::from_le_bytes([c[0], c[1]]),
167+ false => u16::from_be_bytes([c[0], c[1]]),
168+ })
169+ .collect();
170+ String::from_utf16_lossy(&units)
171+}
172+
173+/// The 128-byte ID3v1 block at the end of a file.
174+pub(crate) fn from_id3v1(tail: &[u8]) -> Tags {
175+ let mut tags = Tags::default();
176+ if tail.len() < 128 || &tail[..3] != b"TAG" {
177+ return tags;
178+ }
179+ let field = |r: std::ops::Range<usize>| -> String {
180+ tail[r]
181+ .iter()
182+ .take_while(|&&b| b != 0)
183+ .map(|&b| char::from(b))
184+ .collect::<String>()
185+ .trim()
186+ .to_string()
187+ };
188+ tags.set("TIT2", field(3..33));
189+ tags.set("TPE1", field(33..63));
190+ tags.set("TALB", field(63..93));
191+ tags.set("TDRC", field(93..97));
192+ // A zero separator before the last byte means the track number is there.
193+ if tail[125] == 0 && tail[126] != 0 {
194+ tags.track = Some(u32::from(tail[126]));
195+ }
196+ tags
197+}
198+
199+/// A Vorbis comment block: the FLAC metadata block body, or the Ogg packet
200+/// with its `\x03vorbis` / `OpusTags` signature already stripped.
201+pub(crate) fn from_vorbis_comment(data: &[u8]) -> Tags {
202+ let mut tags = Tags::default();
203+ let u32_at = |at: usize| -> Option<usize> {
204+ let b: [u8; 4] = data.get(at..at + 4)?.try_into().ok()?;
205+ Some(u32::from_le_bytes(b) as usize)
206+ };
207+ let Some(vendor) = u32_at(0) else {
208+ return tags;
209+ };
210+ let mut at = 4 + vendor;
211+ let Some(count) = u32_at(at) else {
212+ return tags;
213+ };
214+ at += 4;
215+ for _ in 0..count.min(1024) {
216+ let Some(len) = u32_at(at) else { break };
217+ at += 4;
218+ let Some(entry) = data.get(at..at + len) else {
219+ break;
220+ };
221+ at += len;
222+ let entry = String::from_utf8_lossy(entry);
223+ if let Some((key, value)) = entry.split_once('=') {
224+ tags.set(&key.to_ascii_uppercase(), value.to_string());
225+ }
226+ }
227+ tags
228+}
229+
230+#[cfg(test)]
231+mod tests {
232+ use super::*;
233+
234+ /// An ID3v2.3 tag of the shape ffmpeg writes, and the v1 block behind it.
235+ #[test]
236+ fn id3_tags_are_read_in_both_versions() {
237+ let mut tag = b"ID3\x03\x00\x00".to_vec();
238+ let mut frames = Vec::new();
239+ for (id, body) in [
240+ ("TIT2", "A Tone"),
241+ ("TPE1", "edith_codecs"),
242+ ("TRCK", "3/12"),
243+ ] {
244+ frames.extend_from_slice(id.as_bytes());
245+ let text = format!("\u{0}{body}");
246+ frames.extend_from_slice(&(text.len() as u32).to_be_bytes());
247+ frames.extend_from_slice(&[0, 0]);
248+ frames.extend_from_slice(text.as_bytes());
249+ }
250+ let size = frames.len() as u32;
251+ tag.extend_from_slice(&[
252+ (size >> 21) as u8 & 0x7f,
253+ (size >> 14) as u8 & 0x7f,
254+ (size >> 7) as u8 & 0x7f,
255+ size as u8 & 0x7f,
256+ ]);
257+ tag.extend_from_slice(&frames);
258+ assert_eq!(id3v2_len(&tag), Some(tag.len() as u64));
259+ let tags = from_id3v2(&tag);
260+ assert_eq!(tags.title.as_deref(), Some("A Tone"));
261+ assert_eq!(tags.artist.as_deref(), Some("edith_codecs"));
262+ assert_eq!(tags.track, Some(3));
263+
264+ let mut v1 = vec![0u8; 128];
265+ v1[..3].copy_from_slice(b"TAG");
266+ v1[3..3 + 6].copy_from_slice(b"A Tone");
267+ v1[126] = 7;
268+ let tags = from_id3v1(&v1);
269+ assert_eq!(tags.title.as_deref(), Some("A Tone"));
270+ assert_eq!(tags.track, Some(7));
271+ }
272+
273+ #[test]
274+ fn vorbis_comments_are_case_insensitive_keys() {
275+ let mut block = Vec::new();
276+ let vendor = b"ec-probe";
277+ block.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
278+ block.extend_from_slice(vendor);
279+ let entries = ["title=A Tone", "Artist=edith_codecs", "TRACKNUMBER=4"];
280+ block.extend_from_slice(&(entries.len() as u32).to_le_bytes());
281+ for e in entries {
282+ block.extend_from_slice(&(e.len() as u32).to_le_bytes());
283+ block.extend_from_slice(e.as_bytes());
284+ }
285+ let tags = from_vorbis_comment(&block);
286+ assert_eq!(tags.title.as_deref(), Some("A Tone"));
287+ assert_eq!(tags.artist.as_deref(), Some("edith_codecs"));
288+ assert_eq!(tags.track, Some(4));
289+ assert!(!tags.is_empty());
290+ }
291+}
crates/ec-probe/tests/library.rsadded+261 -0
@@ -0,0 +1,261 @@
1+//! His library, not fixtures: open, list, decode and seek real files, and
2+//! compare what the probe says against ffprobe file by file.
3+//!
4+//! Driven by `fixtures/real-library-manifest.tsv` (written by
5+//! `scripts/scan-real-library.sh`). Files that have since moved are skipped and
6+//! reported, never failed — the manifest is a snapshot of a moving library.
7+
8+use std::path::{Path, PathBuf};
9+use std::process::Command;
10+
11+use ec_core::registry::{MediaType, SeekMode};
12+use ec_core::timebase::{TimeBase, Timestamp};
13+use ec_probe::Reader;
14+
15+fn manifest() -> Vec<(PathBuf, String, String, f64)> {
16+ let path =
17+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
18+ let Ok(text) = std::fs::read_to_string(path) else {
19+ return Vec::new();
20+ };
21+ text.lines()
22+ .skip(1)
23+ .filter_map(|line| {
24+ let f: Vec<&str> = line.split('\t').collect();
25+ let path = PathBuf::from(f.first()?);
26+ Some((
27+ path,
28+ (*f.get(1)?).to_string(),
29+ (*f.get(7)?).to_string(),
30+ f.get(8)?.parse().unwrap_or(0.0),
31+ ))
32+ })
33+ .collect()
34+}
35+
36+/// Decode `secs` of audio from the current position; answers sample frames.
37+fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result<u64, String> {
38+ let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?;
39+ let rate = f64::from(decoder.sample_rate().max(1));
40+ let want = (secs * rate) as u64;
41+ let mut out = Vec::new();
42+ let mut frames = 0u64;
43+ while frames < want {
44+ let packet = match reader.next_packet() {
45+ Ok(p) => p,
46+ Err(e) if e.is_eof() => break,
47+ Err(e) => return Err(format!("demux: {e}")),
48+ };
49+ if packet.stream != stream {
50+ continue;
51+ }
52+ decoder
53+ .decode(&packet, &mut out)
54+ .map_err(|e| format!("decode: {e}"))?;
55+ frames += (out.len() / decoder.channels().max(1)) as u64;
56+ }
57+ Ok(frames)
58+}
59+
60+/// Ten files with sound, standalone audio first, then Matroska — opened,
61+/// decoded and seeked, with a per-file row in the report.
62+#[test]
63+fn a_real_library_sweep() {
64+ let files = manifest();
65+ if files.is_empty() {
66+ eprintln!("no manifest — run scripts/scan-real-library.sh");
67+ return;
68+ }
69+ // Half standalone audio, half Matroska: the two paths this crate owns, and
70+ // one row per distinct audio codec the library actually holds rather than
71+ // ten copies of the same aac remux.
72+ let standalone = |p: &Path| {
73+ let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");
74+ [
75+ "mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "mp4", "mov",
76+ ]
77+ .contains(&ext)
78+ };
79+ let mut chosen: Vec<_> = Vec::new();
80+ let mut seen = Vec::new();
81+ for want_mkv in [false, true] {
82+ let mut taken = 0;
83+ for f in &files {
84+ let (p, container, acodecs, _) = f;
85+ if acodecs.is_empty() || !p.exists() || taken >= 5 {
86+ continue;
87+ }
88+ let is_mkv = container.contains("matroska");
89+ if is_mkv != want_mkv || (!is_mkv && !standalone(p)) {
90+ continue;
91+ }
92+ // One file per (container, codec set): variety beats repetition.
93+ let key = format!("{is_mkv}:{acodecs}");
94+ if seen.contains(&key) {
95+ continue;
96+ }
97+ seen.push(key);
98+ chosen.push(f);
99+ taken += 1;
100+ }
101+ }
102+ assert!(!chosen.is_empty(), "no readable files in the manifest");
103+
104+ let mut rows = Vec::new();
105+ let mut failures = Vec::new();
106+ for (path, container, acodecs, duration) in &chosen {
107+ let name = path.file_name().unwrap().to_string_lossy().to_string();
108+ let mut reader = match Reader::open(path) {
109+ Ok(r) => r,
110+ Err(e) => {
111+ failures.push(format!("{name}: open failed: {e}"));
112+ continue;
113+ }
114+ };
115+ // The first audio stream that actually decodes, which is what a player
116+ // plays; the ones that do not are named below rather than skipped over.
117+ let audio = reader
118+ .streams()
119+ .iter()
120+ .find(|s| {
121+ s.params.codec.media_type() == MediaType::Audio
122+ && reader.make_decoder(s.index).is_ok()
123+ })
124+ .or_else(|| reader.default_stream(MediaType::Audio))
125+ .cloned();
126+ let Some(audio) = audio else {
127+ failures.push(format!("{name}: no audio stream, ffprobe says {acodecs}"));
128+ continue;
129+ };
130+ let unsupported = reader.unsupported();
131+ // Every codec ffprobe lists is either decodable here or named as not.
132+ let listed: Vec<String> = reader
133+ .streams()
134+ .iter()
135+ .filter(|s| s.params.codec.media_type() == MediaType::Audio)
136+ .map(|s| s.params.codec.name().to_string())
137+ .collect();
138+ let decoded = decode_some(&mut reader, audio.index, 1.0);
139+ let rate = audio.params.audio().map_or(0, |a| a.sample_rate).max(1);
140+ let landing = if *duration > 4.0 {
141+ let ticks = (duration / 2.0 * f64::from(rate)) as i64;
142+ reader
143+ .seek(
144+ audio.index,
145+ Timestamp::new(ticks, TimeBase::from_rate(rate)),
146+ SeekMode::SyncBefore,
147+ )
148+ .map(|t| t.as_secs_f64())
149+ .map_err(|e| e.to_string())
150+ } else {
151+ Ok(0.0)
152+ };
153+ let after_seek = landing
154+ .as_ref()
155+ .ok()
156+ .map(|_| decode_some(&mut reader, audio.index, 0.5));
157+
158+ let ok = decoded.is_ok()
159+ && landing.is_ok()
160+ && matches!(after_seek, Some(Ok(n)) if n > 0)
161+ && listed.iter().any(|c| acodecs.split(',').any(|a| a == c));
162+ if !ok {
163+ failures.push(format!(
164+ "{name}: decode {decoded:?} seek {landing:?} after {after_seek:?} \
165+ codecs {listed:?} vs ffprobe {acodecs}"
166+ ));
167+ }
168+ rows.push(format!(
169+ "{:<52} {:<16} {:<14} {:>7} frames seek->{:>8} {}",
170+ name.chars().take(52).collect::<String>(),
171+ container.split(',').next().unwrap_or(container),
172+ listed.join(","),
173+ decoded.clone().unwrap_or(0),
174+ landing
175+ .as_ref()
176+ .map(|s| format!("{s:.2}s"))
177+ .unwrap_or_else(|e| e.clone()),
178+ match unsupported.is_empty() {
179+ true => "all decodable".to_string(),
180+ false => unsupported
181+ .iter()
182+ .map(|u| format!("unsupported: {} ({})", u.codec.name(), u.reason))
183+ .collect::<Vec<_>>()
184+ .join("; "),
185+ }
186+ ));
187+ }
188+ eprintln!(
189+ "real-library sweep ({} files):\n{}",
190+ rows.len(),
191+ rows.join("\n")
192+ );
193+ assert!(failures.is_empty(), "{}", failures.join("\n"));
194+}
195+
196+/// The TrueHD remux in his library: the track is *listed*, with a reason, and
197+/// the AC-3 track beside it still decodes. A file whose sound is refused
198+/// silently is the failure this exists to prevent.
199+#[test]
200+fn an_undecodable_track_is_named_not_hidden() {
201+ let Some((path, ..)) = manifest()
202+ .into_iter()
203+ .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists())
204+ else {
205+ eprintln!("no TrueHD file in the manifest — skipping");
206+ return;
207+ };
208+ let reader = Reader::open(&path).expect("open");
209+ let unsupported = reader.unsupported();
210+ let truehd = unsupported
211+ .iter()
212+ .find(|u| u.codec.name() == "truehd")
213+ .expect("the TrueHD track is listed as unsupported");
214+ assert!(
215+ truehd.reason.contains("truehd"),
216+ "the reason names the codec: {}",
217+ truehd.reason
218+ );
219+ // ...and the other track of the same file plays.
220+ let decodable: Vec<_> = reader
221+ .streams()
222+ .iter()
223+ .filter(|s| s.params.codec.media_type() == MediaType::Audio)
224+ .filter(|s| reader.make_decoder(s.index).is_ok())
225+ .map(|s| s.params.codec.name())
226+ .collect();
227+ assert!(
228+ !decodable.is_empty(),
229+ "a file with a TrueHD track and an AC-3 one came out with nothing to play"
230+ );
231+ eprintln!(
232+ "{}: {} listed unsupported ({}), decodable: {decodable:?}",
233+ path.file_name().unwrap().to_string_lossy(),
234+ truehd.codec.name(),
235+ truehd.reason
236+ );
237+}
238+
239+/// ffprobe's stream count for the same file, as a cross-check that nothing is
240+/// being hidden.
241+#[allow(dead_code)]
242+fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
243+ let out = Command::new("ffprobe")
244+ .args([
245+ "-v",
246+ "error",
247+ "-select_streams",
248+ "a",
249+ "-show_entries",
250+ "stream=codec_name",
251+ "-of",
252+ "default=nw=1:nk=1",
253+ ])
254+ .arg(path)
255+ .output()
256+ .expect("ffprobe");
257+ String::from_utf8_lossy(&out.stdout)
258+ .lines()
259+ .map(|l| l.trim().to_string())
260+ .collect()
261+}
crates/ec-probe/tests/matrix.rsadded+309 -0
@@ -0,0 +1,309 @@
1+//! The probe matrix: every standalone audio fixture opens as the right format
2+//! and codec, decodes to the end, counts the packets ffprobe counts, and lands
3+//! where it says it does after a hundred random seeks — on one reader.
4+//!
5+//! Oracle is ffmpeg/ffprobe (labelled as such: this is not a conformance
6+//! claim). A missing fixture skips its row rather than failing the suite, so a
7+//! checkout without generated fixtures still builds and runs.
8+
9+use std::path::{Path, PathBuf};
10+use std::process::Command;
11+
12+use ec_core::registry::{MediaType, SeekMode};
13+use ec_core::timebase::{TimeBase, Timestamp};
14+use ec_probe::{Format, Reader};
15+
16+fn fixtures() -> PathBuf {
17+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18+}
19+
20+/// `ffprobe` on one entry of the first audio stream.
21+fn probe(path: &Path, args: &[&str]) -> String {
22+ let out = Command::new("ffprobe")
23+ .args(["-v", "error", "-select_streams", "a:0"])
24+ .args(args)
25+ .args(["-of", "default=nw=1:nk=1"])
26+ .arg(path)
27+ .output()
28+ .expect("ffprobe");
29+ assert!(
30+ out.status.success(),
31+ "ffprobe {}: {}",
32+ path.display(),
33+ String::from_utf8_lossy(&out.stderr)
34+ );
35+ String::from_utf8_lossy(&out.stdout).trim().to_string()
36+}
37+
38+/// Packets ffprobe counts on the first audio stream.
39+fn ffprobe_packets(path: &Path) -> u64 {
40+ probe(
41+ path,
42+ &["-count_packets", "-show_entries", "stream=nb_read_packets"],
43+ )
44+ .lines()
45+ .next()
46+ .and_then(|l| l.trim().parse().ok())
47+ .unwrap_or(0)
48+}
49+
50+/// Sample frames ffmpeg decodes out of the first audio stream.
51+fn ffmpeg_frames(path: &Path, channels: usize) -> u64 {
52+ let out = Command::new("ffmpeg")
53+ .args(["-nostdin", "-v", "error", "-i"])
54+ .arg(path)
55+ .args(["-map", "0:a:0", "-f", "f32le", "-"])
56+ .output()
57+ .expect("ffmpeg");
58+ assert!(out.status.success(), "ffmpeg {}", path.display());
59+ (out.stdout.len() / 4 / channels.max(1)) as u64
60+}
61+
62+/// Decode a whole file through the probe: `(packets, sample frames, channels)`.
63+fn decode_all(reader: &mut Reader, stream: u32) -> (u64, u64, usize) {
64+ let mut decoder = reader.make_decoder(stream).expect("a decoder");
65+ let mut out = Vec::new();
66+ let (mut packets, mut frames) = (0u64, 0u64);
67+ loop {
68+ let packet = match reader.next_packet() {
69+ Ok(p) => p,
70+ Err(e) if e.is_eof() => break,
71+ Err(e) => panic!("demux: {e}"),
72+ };
73+ if packet.stream != stream {
74+ continue;
75+ }
76+ packets += 1;
77+ decoder.decode(&packet, &mut out).expect("decode");
78+ frames += (out.len() / decoder.channels().max(1)) as u64;
79+ }
80+ (packets, frames, decoder.channels())
81+}
82+
83+/// name, expected format, expected codec name.
84+const MATRIX: &[(&str, Format, &str)] = &[
85+ ("wav16-mono-44100.wav", Format::Wav, "pcm_s16le"),
86+ ("wav16-stereo-48000.wav", Format::Wav, "pcm_s16le"),
87+ ("wav16-5.1-48000.wav", Format::Wav, "pcm_s16le"),
88+ ("flac-mono-44100.flac", Format::Flac, "flac"),
89+ ("flac-stereo-48000.flac", Format::Flac, "flac"),
90+ ("flac-5.1-44100.flac", Format::Flac, "flac"),
91+ ("mp3-mono-44100.mp3", Format::Mp3, "mp3"),
92+ ("mp3-stereo-48000.mp3", Format::Mp3, "mp3"),
93+ ("aac-adts-mono-44100.aac", Format::Adts, "aac"),
94+ ("aac-adts-stereo-48000.aac", Format::Adts, "aac"),
95+ ("aac-adts-5.1-48000.aac", Format::Adts, "aac"),
96+ ("aac-mp4-stereo-48000.mp4", Format::Mp4, "aac"),
97+ ("aac-mp4-5.1-44100.mp4", Format::Mp4, "aac"),
98+ ("alac-mp4-stereo-44100.m4a", Format::Mp4, "alac"),
99+ ("alac-mp4-5.1-48000.m4a", Format::Mp4, "alac"),
100+ ("alac24-mp4-stereo-48000.m4a", Format::Mp4, "alac"),
101+ ("vorbis-ogg-mono-44100.ogg", Format::Ogg, "vorbis"),
102+ ("vorbis-ogg-stereo-48000.ogg", Format::Ogg, "vorbis"),
103+ ("vorbis-ogg-5.1-48000.ogg", Format::Ogg, "vorbis"),
104+ ("opus-ogg-mono-48000.opus", Format::Ogg, "opus"),
105+ ("opus-ogg-stereo-48000.opus", Format::Ogg, "opus"),
106+ ("opus-ogg-5.1-48000.opus", Format::Ogg, "opus"),
107+ ("aac-mka-stereo-48000.mka", Format::Matroska, "aac"),
108+ ("flac-mka-stereo-48000.mka", Format::Matroska, "flac"),
109+ ("opus-mka-stereo-48000.mka", Format::Matroska, "opus"),
110+ ("av-h264-aac-stereo-48000.mkv", Format::Matroska, "aac"),
111+];
112+
113+#[test]
114+fn every_fixture_probes_decodes_and_counts() {
115+ let mut checked = 0;
116+ let mut rows = Vec::new();
117+ for &(name, format, codec) in MATRIX {
118+ let path = fixtures().join(name);
119+ if !path.exists() {
120+ continue;
121+ }
122+ let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
123+ assert_eq!(reader.format(), format, "{name}: format");
124+ let audio = reader
125+ .default_stream(MediaType::Audio)
126+ .unwrap_or_else(|| panic!("{name}: no audio stream"))
127+ .clone();
128+ assert_eq!(audio.params.codec.name(), codec, "{name}: codec");
129+
130+ let (packets, frames, channels) = decode_all(&mut reader, audio.index);
131+ let want_frames = ffmpeg_frames(&path, channels);
132+ // Lossless formats are exact; a coded one carries encoder priming that
133+ // ffmpeg trims and this reader hands out, so it decodes *more*.
134+ let exact = matches!(codec, "flac" | "alac") || codec.starts_with("pcm");
135+ if exact {
136+ assert_eq!(frames, want_frames, "{name}: sample frames");
137+ } else {
138+ let slack = 4096 + want_frames / 20;
139+ assert!(
140+ frames + slack >= want_frames && frames <= want_frames + slack,
141+ "{name}: {frames} frames decoded, ffmpeg says {want_frames}"
142+ );
143+ }
144+ // Packet counts are the demuxer's own claim and must match exactly —
145+ // except for PCM, where a "packet" is this reader's own chunking.
146+ if !codec.starts_with("pcm") {
147+ let want_packets = ffprobe_packets(&path);
148+ assert_eq!(packets, want_packets, "{name}: packet count");
149+ }
150+ // A stated duration must be within a frame of the truth.
151+ if let Some(d) = reader.duration() {
152+ let want = want_frames as f64 / f64::from(audio.params.audio().unwrap().sample_rate);
153+ assert!(
154+ (d.as_secs_f64() - want).abs() < 0.2,
155+ "{name}: duration {} vs {want}",
156+ d.as_secs_f64()
157+ );
158+ }
159+ rows.push(format!(
160+ "{name:34} {:9} {codec:6} {channels}ch {packets:5} packets {frames:8} frames",
161+ format.name()
162+ ));
163+ checked += 1;
164+ }
165+ assert!(
166+ checked > 0,
167+ "no fixtures found — run scripts/gen-fixtures.sh"
168+ );
169+ eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n"));
170+}
171+
172+/// A hundred random seeks per format, on **one** reader, each landing at or
173+/// before its target and within the container's own granularity of it.
174+#[test]
175+fn a_hundred_random_seeks_land_where_they_say() {
176+ let mut checked = 0;
177+ for &(name, _, codec) in MATRIX {
178+ let path = fixtures().join(name);
179+ if !path.exists() {
180+ continue;
181+ }
182+ let mut reader = Reader::open(&path).expect("open");
183+ let audio = reader
184+ .default_stream(MediaType::Audio)
185+ .expect("audio")
186+ .clone();
187+ let rate = audio.params.audio().unwrap().sample_rate.max(1);
188+ let Some(duration) = reader.duration() else {
189+ continue;
190+ };
191+ let secs = duration.as_secs_f64();
192+ // Tolerance is the container's own granularity: Ogg lands on a page
193+ // (3936 bytes on these fixtures, over a second of audio) and Matroska
194+ // on a cluster, while every other format lands inside the frame that
195+ // holds the target — so their tolerance is that frame's own length,
196+ // taken from the packet itself below.
197+ let coarse = match name {
198+ n if n.ends_with(".mka") || n.ends_with(".mkv") => Some(2.5),
199+ n if n.ends_with(".ogg") || n.ends_with(".opus") => Some(2.5),
200+ _ => None,
201+ };
202+ let mut state = 0x2545_F491_4F6C_DD1Du64;
203+ for _ in 0..100 {
204+ // xorshift: a deterministic spread of targets, no dev-dependency.
205+ state ^= state << 13;
206+ state ^= state >> 7;
207+ state ^= state << 17;
208+ let target = (state % 1_000_000) as f64 / 1_000_000.0 * secs;
209+ let ticks = (target * f64::from(rate)) as i64;
210+ let landed = reader
211+ .seek(
212+ audio.index,
213+ Timestamp::new(ticks, TimeBase::from_rate(rate)),
214+ SeekMode::SyncBefore,
215+ )
216+ .unwrap_or_else(|e| panic!("{name}: seek to {target:.3}s: {e}"));
217+ let at = landed.as_secs_f64();
218+ assert!(
219+ at <= target + 0.001,
220+ "{name}: asked for {target:.3}s, landed at {at:.3}s — past the target"
221+ );
222+ // And the reader really is there: the landing is a packet's own
223+ // timestamp, not an estimate.
224+ let tolerance = loop {
225+ let packet = reader.next_packet().expect("a packet after a seek");
226+ if packet.stream != audio.index {
227+ continue;
228+ }
229+ assert!(!packet.data.is_empty(), "{name}: an empty packet");
230+ assert_eq!(
231+ packet.pts.unwrap_or(0),
232+ landed.ticks,
233+ "{name}: the landing is not the next packet's own timestamp"
234+ );
235+ break coarse.unwrap_or_else(|| {
236+ packet.duration.unwrap_or(1) as f64 / f64::from(rate) + 0.001
237+ });
238+ };
239+ assert!(
240+ target - at <= tolerance,
241+ "{name}: asked for {target:.3}s, landed at {at:.3}s — {:.3}s short of a container granularity of {tolerance:.3}s",
242+ target - at
243+ );
244+ }
245+ let _ = codec;
246+ checked += 1;
247+ }
248+ assert!(
249+ checked > 0,
250+ "no fixtures found — run scripts/gen-fixtures.sh"
251+ );
252+ eprintln!("100 random seeks each on {checked} files, one reader per file");
253+}
254+
255+/// Cover art is a still picture, not a video track, in both containers that
256+/// carry one — and the audio beside it still opens.
257+#[test]
258+fn cover_art_is_never_a_video_track() {
259+ let mut checked = 0;
260+ for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] {
261+ let path = fixtures().join(name);
262+ if !path.exists() {
263+ continue;
264+ }
265+ let reader = Reader::open(&path).expect("open");
266+ let video: Vec<_> = reader
267+ .streams()
268+ .iter()
269+ .filter(|s| s.params.codec.media_type() == MediaType::Video)
270+ .collect();
271+ assert!(
272+ video.is_empty(),
273+ "{name}: cover art listed as a video track: {video:?}"
274+ );
275+ assert!(
276+ reader.default_stream(MediaType::Audio).is_some(),
277+ "{name}: no audio"
278+ );
279+ checked += 1;
280+ }
281+ assert!(checked > 0, "no cover-art fixtures — run gen-fixtures.sh");
282+}
283+
284+/// The tags an ID3v2-tagged file carries come back off it.
285+#[test]
286+fn id3_tags_come_off_a_real_file() {
287+ let path = fixtures().join("cover-mp3-stereo-44100.mp3");
288+ if !path.exists() {
289+ return;
290+ }
291+ let reader = Reader::open(&path).expect("open");
292+ assert_eq!(reader.tags().title.as_deref(), Some("A Tone"));
293+ assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs"));
294+}
295+
296+/// A mislabelled file is still the file it is: the sniff decides, not the
297+/// extension.
298+#[test]
299+fn a_mislabelled_file_opens_as_what_it_is() {
300+ let src = fixtures().join("flac-stereo-48000.flac");
301+ if !src.exists() {
302+ return;
303+ }
304+ let liar = std::env::temp_dir().join("ec-probe-liar.mp3");
305+ std::fs::copy(&src, &liar).expect("copy");
306+ let reader = Reader::open(&liar).expect("open");
307+ assert_eq!(reader.format(), Format::Flac);
308+ std::fs::remove_file(&liar).ok();
309+}