From 51de303d1070b3f8030797d011ab304e38413bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 14:06:39 +0300 Subject: [PATCH] feat(probe): one sniffing reader and one decoder registry for every audio file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.toml | 7 + crates/ec-probe/Cargo.toml | 21 + crates/ec-probe/src/decoder.rs | 376 +++++++++++++++++ crates/ec-probe/src/lib.rs | 669 +++++++++++++++++++++++++++++++ crates/ec-probe/src/raw.rs | 394 ++++++++++++++++++ crates/ec-probe/src/tags.rs | 291 ++++++++++++++ crates/ec-probe/tests/library.rs | 261 ++++++++++++ crates/ec-probe/tests/matrix.rs | 309 ++++++++++++++ 8 files changed, 2328 insertions(+) create mode 100644 crates/ec-probe/Cargo.toml create mode 100644 crates/ec-probe/src/decoder.rs create mode 100644 crates/ec-probe/src/lib.rs create mode 100644 crates/ec-probe/src/raw.rs create mode 100644 crates/ec-probe/src/tags.rs create mode 100644 crates/ec-probe/tests/library.rs create mode 100644 crates/ec-probe/tests/matrix.rs diff --git a/Cargo.toml b/Cargo.toml index 5f29fb79..c88558ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,10 +9,13 @@ license = "MIT OR Apache-2.0" authors = ["Ahmet Kaan Gümüş"] [workspace.dependencies] +ec-aac = { path = "crates/ec-aac", version = "0.1.0" } ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" } +ec-alac = { path = "crates/ec-alac", version = "0.1.0" } ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" } ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } +ec-flac = { path = "crates/ec-flac", version = "0.1.0" } ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } ec-image = { path = "crates/ec-image", version = "0.1.0" } @@ -20,7 +23,11 @@ ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" } ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" } +ec-ogg = { path = "crates/ec-ogg", version = "0.1.0" } +ec-opus = { path = "crates/ec-opus", version = "0.1.0" } +ec-probe = { path = "crates/ec-probe", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } +ec-vorbis = { path = "crates/ec-vorbis", version = "0.1.0" } ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } # Portable SIMD without asm or build-time tooling (family rule: pure Rust only). wide = "1.5" diff --git a/crates/ec-probe/Cargo.toml b/crates/ec-probe/Cargo.toml new file mode 100644 index 00000000..5d30bac6 --- /dev/null +++ b/crates/ec-probe/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "ec-probe" +description = "Format detection and one unified audio reader: WAV/MP3/FLAC/ADTS in-crate, Ogg/mp4/Matroska delegated to their own crates." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-aac = { workspace = true } +ec-ac3 = { workspace = true } +ec-alac = { workspace = true } +ec-core = { workspace = true } +ec-flac = { workspace = true } +ec-matroska = { workspace = true } +ec-mp3 = { workspace = true } +ec-mp4 = { workspace = true } +ec-ogg = { workspace = true } +ec-opus = { workspace = true } +ec-riff = { workspace = true } +ec-vorbis = { workspace = true } diff --git a/crates/ec-probe/src/decoder.rs b/crates/ec-probe/src/decoder.rs new file mode 100644 index 00000000..33bf624a --- /dev/null +++ b/crates/ec-probe/src/decoder.rs @@ -0,0 +1,376 @@ +//! One decoder seat for every audio codec the family carries: packets in, +//! interleaved `f32` out, in film channel order. +//! +//! This is the registry half of the probe. A caller that has a stream from +//! [`crate::Reader`] asks for [`AudioDecoder::new`] and gets either a decoder +//! or an [`ec_core::Error::Unsupported`] that names the codec *and* why nothing +//! here decodes it — a refusal string with no capability behind it is a bug, +//! not a message. + +use ec_core::error::{Error, Result}; +use ec_core::frame::{Frame, SampleFormat}; +use ec_core::packet::Packet; +use ec_core::registry::{CodecId, CodecParameters, Decoder}; + +/// Which family decoder is doing the work. +enum Inner { + Flac(Box), + Mp3(Box), + Vorbis(Box), + Ac3(Box), + Aac(Box), + Alac(Box), + Opus(Box), + /// PCM needs no decoder, only a reading of the bytes. + Pcm(CodecId), +} + +/// A decoder for one audio stream. +pub struct AudioDecoder { + inner: Inner, + codec: CodecId, + channels: usize, + sample_rate: u32, +} + +impl std::fmt::Debug for AudioDecoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AudioDecoder") + .field("codec", &self.codec.name()) + .field("channels", &self.channels) + .field("sample_rate", &self.sample_rate) + .finish() + } +} + +impl AudioDecoder { + /// A decoder for the stream `params` describes. + pub fn new(params: &CodecParameters) -> Result { + let audio = params + .audio() + .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?; + let channels = audio.layout.channel_count().max(1); + let sample_rate = audio.sample_rate; + let extradata = params.extradata.as_deref(); + let inner = match params.codec { + CodecId::Flac => { + let mut params = params.clone(); + params.extradata = flac_stream_info(extradata.unwrap_or_default()) + .map(ec_core::packet::Buf::copy_from_slice); + Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?)) + } + CodecId::Mp3 => Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?)), + CodecId::Vorbis => { + let data = extradata.ok_or_else(|| { + Error::corrupt("a Vorbis stream with no header triplet in its extradata") + })?; + let headers = ec_ogg::xiph_unlace(data)?; + Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?)) + } + CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())), + CodecId::Aac => { + let decoder = match extradata { + Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, + // ADTS states its own configuration in every frame. + None => ec_aac::AacDecoder::new(), + }; + Inner::Aac(Box::new(decoder)) + } + CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters( + params.clone(), + )?)), + CodecId::Opus => { + let head = extradata.unwrap_or_default(); + let (streams, coupled, mapping) = opus_layout(head, channels)?; + // 48 kHz whatever the container says: it is the only rate Opus + // decodes at, and the rate its timestamps are in. + Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate( + 48_000, streams, coupled, &mapping, + )?)) + } + codec if is_pcm(codec) => Inner::Pcm(codec), + codec => { + return Err(Error::unsupported( + format!("the {} track", codec.name()), + match codec.media_type() { + ec_core::MediaType::Audio => { + "no decoder for it exists in this family (yet)" + } + _ => "this is an audio probe; picture and subtitles decode elsewhere", + }, + )); + } + }; + Ok(AudioDecoder { + inner, + codec: params.codec, + channels, + sample_rate: match params.codec { + CodecId::Opus => 48_000, + _ => sample_rate, + }, + }) + } + + /// Which codec this is decoding. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// Channels the decoder emits. + pub fn channels(&self) -> usize { + self.channels + } + + /// Rate the decoder emits at. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// One packet in, interleaved `f32` out, normalised to -1.0..=1.0. + /// + /// `out` is cleared first: a packet that decodes to nothing (a header + /// packet, a frame the decoder swallowed) leaves it empty rather than + /// leaving the caller with the previous packet's audio. + pub fn decode(&mut self, packet: &Packet, out: &mut Vec) -> Result<()> { + out.clear(); + match &mut self.inner { + Inner::Flac(d) => drain(d.as_mut(), packet, out)?, + Inner::Mp3(d) => drain(d.as_mut(), packet, out)?, + Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?, + Inner::Ac3(d) => drain(d.as_mut(), packet, out)?, + Inner::Aac(d) => { + let audio = d.decode(&packet.data, packet.pts)?; + self.channels = usize::from(audio.channels).max(1); + if audio.sample_rate > 0 { + self.sample_rate = audio.sample_rate; + } + out.extend_from_slice(&audio.samples); + } + Inner::Alac(d) => { + let scale = match d.cookie().sample_format() { + SampleFormat::S16 => 1.0 / 32768.0, + _ => 1.0 / 2147483648.0, + }; + out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale)); + } + Inner::Opus(d) => { + let samples = d.decode_packet(&packet.data)?; + out.extend_from_slice(&samples); + } + Inner::Pcm(codec) => pcm(*codec, &packet.data, out), + } + Ok(()) + } + + /// Drop everything buffered from before a seek. + pub fn reset(&mut self) { + match &mut self.inner { + Inner::Flac(d) => d.reset(), + Inner::Mp3(d) => d.reset(), + Inner::Vorbis(d) => d.reset(), + Inner::Ac3(d) => d.reset(), + Inner::Aac(d) => **d = ec_aac::AacDecoder::new(), + Inner::Alac(d) => d.reset(), + Inner::Opus(d) => d.reset(), + Inner::Pcm(_) => {} + } + } +} + +/// The bare 34-byte `STREAMINFO` inside whatever a container calls FLAC +/// extradata. +/// +/// Three shapes carry the same block: Matroska's `CodecPrivate` is the whole +/// `fLaC` header chain, mp4's `dfLa` is a version word and then the blocks, +/// and Ogg's first packet has a `\x7fFLAC` wrapper in front of that. Rather +/// than encode three offsets, this looks for the one block header that can +/// only be `STREAMINFO`: type 0, length 34. +fn flac_stream_info(data: &[u8]) -> Option<&[u8]> { + if data.len() == 34 { + return Some(data); + } + for at in 0..data.len().saturating_sub(38).min(16) { + let head = &data[at..at + 4]; + let len = u32::from_be_bytes([0, head[1], head[2], head[3]]); + if head[0] & 0x7f == 0 && len == 34 { + return data.get(at + 4..at + 38); + } + } + // Nothing recognisable: hand the bytes over as they came and let the + // decoder read the frames' own headers instead. + None +} + +/// True for the PCM codec ids, which are read rather than decoded. +fn is_pcm(codec: CodecId) -> bool { + matches!( + codec, + CodecId::PcmU8 + | CodecId::PcmS16Le + | CodecId::PcmS16Be + | CodecId::PcmS24Le + | CodecId::PcmS32Le + | CodecId::PcmF32Le + ) +} + +/// Push one packet through an [`ec_core::Decoder`] and take every frame it +/// yields, converted to interleaved `f32`. +fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec) -> Result<()> { + decoder.send_packet(packet)?; + loop { + match decoder.receive_frame() { + Ok(Frame::Audio(frame)) => interleave(&frame, out), + Ok(Frame::Video(_)) => { + return Err(Error::corrupt("an audio decoder produced a picture")); + } + Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), + Err(e) => return Err(e), + } + } +} + +/// One decoded frame appended to `out` as interleaved, normalised `f32`. +fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec) { + let channels = frame.channels().max(1); + let width = frame.format.bytes_per_sample(); + let read = |plane: &[u8], i: usize| -> f32 { + let at = i * width; + let b = &plane[at..at + width]; + match frame.format { + SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0, + SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0, + SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0, + SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]), + SampleFormat::F64 => { + f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32 + } + } + }; + match frame.planar { + false => { + let Some(plane) = frame.data.first() else { + return; + }; + let n = (plane.len() / width).min(frame.samples * channels); + out.extend((0..n).map(|i| read(plane, i))); + } + true => { + for i in 0..frame.samples { + for c in 0..channels { + let Some(plane) = frame.data.get(c) else { + continue; + }; + if (i + 1) * width <= plane.len() { + out.push(read(plane, i)); + } + } + } + } + } +} + +/// PCM bytes as normalised `f32`. +fn pcm(codec: CodecId, data: &[u8], out: &mut Vec) { + match codec { + CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)), + CodecId::PcmS16Le => out.extend( + data.chunks_exact(2) + .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0), + ), + CodecId::PcmS16Be => out.extend( + data.chunks_exact(2) + .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0), + ), + // 24-bit is stored packed, little-endian, and sign-extends from bit 23. + CodecId::PcmS24Le => out.extend(data.chunks_exact(3).map(|c| { + let v = i32::from_le_bytes([0, c[0], c[1], c[2]]); + v as f32 / 2147483648.0 + })), + CodecId::PcmS32Le => out.extend( + data.chunks_exact(4) + .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0), + ), + CodecId::PcmF32Le => out.extend( + data.chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), + ), + _ => {} + } +} + +/// The stream layout of an Opus track, read off its `OpusHead`. +/// +/// Mapping family 0 is the implied mono/stereo layout the header does not +/// spell out; families 1 and 255 carry the table. A header too short to hold +/// one is treated as family 0, which is what a `.opus` file with a truncated +/// head still plays as. +pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec)> { + let channels = channels.max(1); + let family = head.get(18).copied().unwrap_or(0); + if family == 0 || head.len() < 21 { + let coupled = usize::from(channels >= 2); + let mapping: Vec = (0..channels.min(2) as u8).collect(); + return Ok((channels.min(2) - coupled, coupled, mapping)); + } + let streams = usize::from(head[19]); + let coupled = usize::from(head[20]); + let mapping = head + .get(21..21 + channels) + .ok_or_else(|| { + Error::corrupt(format!( + "an OpusHead claiming {channels} channels with a {}-byte mapping table", + head.len().saturating_sub(21) + )) + })? + .to_vec(); + Ok((streams, coupled, mapping)) +} + +/// The encoder delay an Opus track states in its `OpusHead`, in 48 kHz samples. +pub fn opus_pre_skip(head: &[u8]) -> u64 { + match head.get(10..12) { + Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])), + None => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn opus_layouts_come_off_the_head_or_are_implied() { + // Family 0 stereo: one coupled stream, no table in the header. + let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00"; + assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1])); + assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0])); + assert_eq!(opus_pre_skip(head), 312); + + // Family 1, 5.1: four streams of which two are coupled. + let mut six = head[..18].to_vec(); + six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]); + assert_eq!( + opus_layout(&six, 6).unwrap(), + (4, 2, vec![0, 4, 1, 2, 3, 5]) + ); + // A table too short for the channel count is named, not guessed at. + assert!(opus_layout(&six[..23], 6).is_err()); + } + + #[test] + fn pcm_reads_every_width_at_full_scale() { + let mut out = Vec::new(); + pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out); + assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]); + out.clear(); + pcm(CodecId::PcmU8, &[0, 128, 255], &mut out); + assert_eq!(out[0], -1.0); + assert_eq!(out[1], 0.0); + out.clear(); + // 24-bit sign-extends: 0x800000 is full-scale negative. + pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out); + assert_eq!(out, vec![-1.0]); + } +} diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs new file mode 100644 index 00000000..815beed7 --- /dev/null +++ b/crates/ec-probe/src/lib.rs @@ -0,0 +1,669 @@ +//! 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`]; there is exactly one EBML parser in this family and it is not +//! here. What is implemented in [`raw`] is the four formats that are a codec +//! and nothing else: WAV, 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 +//! TrueHD track says "TrueHD", not silence. Cover art is not a video track +//! and never appears as one. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod decoder; +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::Packet; +use ec_core::registry::{CodecId, Demuxer, MediaType, SeekMode, StreamInfo}; +use ec_core::timebase::{Rounding, TimeBase, Timestamp}; + +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; + +/// 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, + /// ISO base media: mp4, m4a, mov. + Mp4, + /// Matroska and WebM. + Matroska, +} + +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::Ogg => "ogg", + Format::Mp4 => "mp4", + Format::Matroska => "matroska", + } + } + + /// 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::Ogg => &["ogg", "oga", "opus"], + Format::Mp4 => &["mp4", "m4a", "m4v", "mov"], + Format::Matroska => &["mkv", "mka", "mks", "mk3d", "webm"], + } + } +} + +/// 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" && &data[8..12] == b"WAVE" { + return Some(Format::Wav); + } + 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); + } + // 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 +} + +/// 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::Ogg, + Format::Mp4, + Format::Matroska, + ] + .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, matroska)", + ) + })?; + 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).map(|p| tags::from_vorbis_comment(&p[7..]))) + .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::Flac => open_flac(src, &head, end), + Format::Mp3 => open_mp3(src, &head, end), + Format::Adts => open_adts(src, &head, 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 first stream of `kind`, which is what a caller that just wants "the + /// audio" means. + pub fn default_stream(&self, kind: MediaType) -> Option<&StreamInfo> { + self.streams() + .iter() + .find(|s| s.params.codec.media_type() == kind) + } + + /// 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. + pub fn duration(&self) -> Option { + self.streams() + .iter() + .filter_map(|s| s.duration.map(|d| Timestamp::new(d, s.time_base))) + .max_by(|a, b| { + a.as_secs_f64() + .partial_cmp(&b.as_secs_f64()) + .unwrap_or(std::cmp::Ordering::Equal) + }) + } + + /// 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) +} + +fn open_wav(mut src: R, end: u64) -> Result { + src.rewind()?; + let (spec, frames) = { + let reader = ec_riff::WavReader::new(&mut src)?; + (reader.spec(), reader.duration()) + }; + let start = src.stream_position()?; + 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(1 << 24); + 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 - 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)?); + // A Xing/Info header states the frame count exactly; without one the + // duration is the bitrate estimate ffmpeg 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 + // ffmpeg and this reader start after it. + start += header.frame_len().unwrap_or(0) as u64; + } + let total = match xing { + Some(frames) => Some(frames * per_frame), + None => 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, + )?; + 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 - 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)?); + // 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 + // ffmpeg 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])) +} + +/// 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)?; + Some(u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]))) +} + +#[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); + } + + /// 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)); + } +} diff --git a/crates/ec-probe/src/raw.rs b/crates/ec-probe/src/raw.rs new file mode 100644 index 00000000..cd676dba --- /dev/null +++ b/crates/ec-probe/src/raw.rs @@ -0,0 +1,394 @@ +//! The four formats that are a codec and nothing else: WAV, MP3, FLAC and +//! ADTS. One demuxer serves all four, because they differ only in how a frame +//! states its own length — everything after that (the packet stream, the frame +//! index, sample-accurate seeking) is the same walk. +//! +//! Framing comes from the codec crates rather than being re-derived here: +//! [`ec_mp3::FrameHeader`], [`ec_flac::decode::find_frame_sync`] and +//! [`ec_aac::parse_adts`] each already know their own header. + +use std::io::{Read, Seek, SeekFrom}; + +use ec_core::error::{Error, Result}; +use ec_core::frame::{ChannelLayout, SampleFormat}; +use ec_core::packet::{Buf, Packet, PacketFlags}; +use ec_core::registry::{ + AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, SeekMode, StreamInfo, +}; +use ec_core::timebase::{Rounding, TimeBase, Timestamp}; + +/// Bytes read per refill. +const CHUNK: usize = 64 << 10; +/// Consumed bytes tolerated in front of the window before it is compacted. +const COMPACT_AT: usize = 256 << 10; +/// Frames of PCM in one WAV packet: big enough that a packet is not a syscall +/// per millisecond, small enough to seek inside without decoding a second. +const WAV_FRAMES: usize = 4096; + +/// How a format states the length of one frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Kind { + /// Fixed-size PCM: a "frame" is one interleaved sample. + Wav { + block_align: usize, + }, + Mp3, + Flac, + Adts, +} + +/// A frame's byte length and how many inter-channel samples it holds. +struct Framing { + bytes: usize, + samples: u64, +} + +/// One elementary audio stream read straight out of a file. +pub(crate) struct RawDemuxer { + r: R, + kind: Kind, + streams: Vec, + /// Offset of the first frame and one past the last audio byte. + start: u64, + end: u64, + /// Offset the window starts at, and the file offset the reader itself sits + /// at (window end). + pos: u64, + read_at: u64, + buf: Vec, + head: usize, + /// Next packet's first sample, in the stream's own time base. + sample: u64, + rate: u32, + /// `STREAMINFO`, needed to read a FLAC frame header. + flac: Option, + /// `(first sample, offset)` per frame, built on the first seek. + index: Vec<(u64, u64)>, + indexed: bool, +} + +impl RawDemuxer { + pub(crate) fn new( + mut r: R, + kind: Kind, + params: CodecParameters, + start: u64, + end: u64, + total_samples: Option, + flac: Option, + ) -> Result> { + let rate = params + .audio() + .map(|a| a.sample_rate) + .filter(|r| *r > 0) + .ok_or_else(|| Error::corrupt("a raw audio stream with no sample rate"))?; + let mut info = StreamInfo::new(0, TimeBase::from_rate(rate), params); + info.start_time = Some(0); + info.duration = total_samples.map(|n| n as i64); + r.seek(SeekFrom::Start(start))?; + Ok(RawDemuxer { + r, + kind, + streams: vec![info], + start, + end, + pos: start, + read_at: start, + buf: Vec::with_capacity(CHUNK), + head: 0, + sample: 0, + rate, + flac, + index: Vec::new(), + indexed: false, + }) + } + + /// Samples in a typical frame of this format, for the tail of an estimate. + fn frame_samples(&self) -> u64 { + match self.kind { + Kind::Wav { .. } => WAV_FRAMES as u64, + Kind::Mp3 => 1152, + Kind::Flac => self + .flac + .as_ref() + .map_or(4096, |i| u64::from(i.max_block_size)), + Kind::Adts => 1024, + } + } + + /// At least `want` bytes in the window, or fewer at the end of the stream. + fn fill(&mut self, want: usize) -> Result<()> { + if self.head > COMPACT_AT { + self.buf.drain(..self.head); + self.pos += self.head as u64; + self.head = 0; + } + while self.buf.len() - self.head < want && self.read_at < self.end { + let chunk = CHUNK.min((self.end - self.read_at) as usize); + let at = self.buf.len(); + self.buf.resize(at + chunk, 0); + let mut got = 0; + while got < chunk { + match self.r.read(&mut self.buf[at + got..]) { + Ok(0) => break, + Ok(n) => got += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(Error::Io(e)), + } + } + self.buf.truncate(at + got); + self.read_at += got as u64; + if got == 0 { + break; + } + } + Ok(()) + } + + /// The unread bytes of the window. + fn window(&self) -> &[u8] { + &self.buf[self.head..] + } + + /// Where the window's head sits in the file. + fn offset(&self) -> u64 { + self.pos + self.head as u64 + } + + /// Drop the window and resume reading at `offset`. + fn jump(&mut self, offset: u64) -> Result<()> { + self.r.seek(SeekFrom::Start(offset))?; + self.buf.clear(); + self.head = 0; + self.pos = offset; + self.read_at = offset; + Ok(()) + } + + /// The frame at the window's head, or [`Error::Eof`] at the end. + /// + /// Resyncs over junk: a byte that does not open a frame is skipped, which + /// is what carries a reader over an ID3 tag in the middle of a stream or a + /// scrap of a torn download. + fn framing(&mut self) -> Result { + let want = match self.kind { + Kind::Wav { block_align } => block_align * WAV_FRAMES, + // A FLAC frame is bounded by the *next* sync word, so the window + // has to hold a whole one plus the head of its successor. + Kind::Flac => 1 << 20, + _ => 8192, + }; + let flac = self.flac.clone(); + let kind = self.kind; + let mut skipped = 0u64; + loop { + self.fill(want)?; + let left = self.window().len(); + if left == 0 { + return Err(Error::Eof); + } + let tail = self.read_at >= self.end; + match frame_at(kind, self.window(), flac.as_ref()) { + Ok(f) => return Ok(f), + Err(e) if e.is_need_more() && tail => { + // The tail of a file: whatever is left is the last frame. + return Ok(Framing { + bytes: left, + samples: self.frame_samples(), + }); + } + Err(_) if skipped < (1 << 20) => { + self.head += 1; + skipped += 1; + } + Err(e) => return Err(e), + } + } + } + + /// Walk every frame once, recording where each starts. + fn build_index(&mut self) -> Result<()> { + if self.indexed { + return Ok(()); + } + let (at, sample) = (self.offset(), self.sample); + self.jump(self.start)?; + let mut sample_at = 0u64; + while self.offset() < self.end { + let f = match self.framing() { + Ok(f) => f, + Err(e) if e.is_eof() => break, + Err(e) => return Err(e), + }; + // `framing` may have resynced past junk: index where the frame + // really starts, not where the walk was standing. + self.index.push((sample_at, self.offset())); + sample_at += f.samples; + self.head += f.bytes; + } + self.indexed = true; + // Put the reader back where the caller had it. + self.jump(at)?; + self.sample = sample; + Ok(()) + } +} + +/// One frame's geometry, read from the head of `data`. +fn frame_at(kind: Kind, data: &[u8], flac: Option<&ec_flac::StreamInfo>) -> Result { + match kind { + Kind::Wav { block_align } => { + let frames = (data.len() / block_align).min(WAV_FRAMES); + match frames { + 0 => Err(Error::Eof), + n => Ok(Framing { + bytes: n * block_align, + samples: n as u64, + }), + } + } + Kind::Mp3 => { + let header = ec_mp3::FrameHeader::parse(data)?; + let bytes = header + .frame_len() + .ok_or_else(|| Error::corrupt("mp3: a free-format frame states no length"))?; + if bytes > data.len() { + return Err(Error::NeedMore); + } + Ok(Framing { + bytes, + samples: header.samples_per_frame() as u64, + }) + } + Kind::Adts => { + let header = ec_aac::parse_adts(data)?; + if header.frame_length > data.len() { + return Err(Error::NeedMore); + } + Ok(Framing { + bytes: header.frame_length, + samples: 1024 * u64::from(header.raw_blocks), + }) + } + Kind::Flac => { + if ec_flac::decode::find_frame_sync(data, 0, flac) != Some(0) { + return Err(Error::corrupt("flac: not a frame header")); + } + let mut r = ec_core::BitReader::new(data); + let header = ec_flac::decode::parse_frame_header(&mut r, flac)?; + // A frame ends where the next one starts; the last frame of a file + // ends at the file's end, which the caller's `NeedMore` handles. + let bytes = ec_flac::decode::find_frame_sync(data, 1, flac).ok_or(Error::NeedMore)?; + Ok(Framing { + bytes, + samples: header.block_size as u64, + }) + } + } +} + +impl Demuxer for RawDemuxer { + fn streams(&self) -> &[StreamInfo] { + &self.streams + } + + fn next_packet(&mut self) -> Result { + if self.offset() >= self.end { + return Err(Error::Eof); + } + let f = self.framing()?; + let data = Buf::copy_from_slice(&self.window()[..f.bytes]); + self.head += f.bytes; + let pts = self.sample; + self.sample += f.samples; + let mut packet = Packet::new(0, TimeBase::from_rate(self.rate), data); + packet.pts = Some(pts as i64); + packet.dts = Some(pts as i64); + packet.duration = Some(f.samples as i64); + packet.flags = PacketFlags { + keyframe: true, + ..PacketFlags::default() + }; + Ok(packet) + } + + fn seek(&mut self, _stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { + let target = to + .rescale(TimeBase::from_rate(self.rate), Rounding::Down) + .ticks + .max(0) as u64; + // PCM needs no index and no rounding: every sample is a random access + // point, at a byte offset arithmetic gives. + if let Kind::Wav { block_align } = self.kind { + let at = self.start + target * block_align as u64; + self.jump(at.min(self.end))?; + self.sample = target; + return Ok(()); + } + self.build_index()?; + let found = self.index.partition_point(|(s, _)| *s <= target); + let i = match mode { + SeekMode::SyncAfter => found.min(self.index.len().saturating_sub(1)), + // At or before: the frame the target sits inside. + _ => found.saturating_sub(1), + }; + let (sample, at) = match self.index.get(i) { + Some(&entry) => entry, + None => return Err(Error::Eof), + }; + self.jump(at)?; + self.sample = sample; + Ok(()) + } +} + +/// Codec parameters for a WAVE stream, whose `fmt ` chunk names its codec +/// outright. +pub(crate) fn wav_parameters(spec: ec_riff::WavSpec) -> Result<(CodecParameters, usize)> { + let format = spec.sample_format()?; + let codec = match (format, spec.bits_per_sample) { + (SampleFormat::F32, _) => CodecId::PcmF32Le, + (_, 8) => CodecId::PcmU8, + (_, 16) => CodecId::PcmS16Le, + (_, 24) => CodecId::PcmS24Le, + (_, 32) => CodecId::PcmS32Le, + (_, bits) => { + return Err(Error::unsupported( + format!("a {bits}-bit WAVE file"), + "only 8, 16, 24 and 32 bit samples have a PCM codec id", + )); + } + }; + let mut params = CodecParameters::new(codec); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: spec.sample_rate, + layout: spec.layout(), + format: Some(format), + bits_per_sample: Some(u32::from(spec.bits_per_sample)), + }); + Ok((params, spec.block_align())) +} + +/// Codec parameters for an ADTS stream, from its first frame header. +pub(crate) fn adts_parameters(header: &ec_aac::AdtsHeader) -> CodecParameters { + let mut params = CodecParameters::new(CodecId::Aac); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: header.sample_rate, + layout: ChannelLayout::from_count(usize::from(header.channels.max(1))), + format: Some(SampleFormat::F32), + bits_per_sample: None, + }); + // ADTS states its configuration in every frame, but a decoder built from + // parameters alone still wants the ASC form of it. + params.extradata = Some(Buf::from_vec(ec_aac::audio_specific_config_bytes( + header.sample_rate, + header.channels, + ))); + params +} + +/// Codec parameters for an MP3 stream, from its first frame header. +pub(crate) fn mp3_parameters(header: &ec_mp3::FrameHeader) -> CodecParameters { + ec_mp3::codec_parameters(header.sample_rate, header.channels()) +} diff --git a/crates/ec-probe/src/tags.rs b/crates/ec-probe/src/tags.rs new file mode 100644 index 00000000..b788c002 --- /dev/null +++ b/crates/ec-probe/src/tags.rs @@ -0,0 +1,291 @@ +//! The handful of tags a media library actually shows: title, artist, album, +//! date and track number, out of ID3v1, ID3v2 and Vorbis comments. +//! +//! Deliberately small. edith reads no metadata at all today (its symphonia +//! reader passes `MetadataOptions::default()` and never asks for the result), +//! so this exists to keep the door open rather than to be complete: no cover +//! art, no arbitrary user frames, and no mp4 `ilst` — an iTunes-tagged `.m4a` +//! reports the `moov/udta/name` title only. Adding a surface is a decision for +//! whoever needs one, and the parsers below are where it goes. + +/// What a file says about itself. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Tags { + /// Track title. + pub title: Option, + /// Performing artist. + pub artist: Option, + /// Album (or "content group" in ID3 terms). + pub album: Option, + /// Year or full date, as the file wrote it. + pub date: Option, + /// Track number within its album. + pub track: Option, +} + +impl Tags { + /// True when nothing was found. + pub fn is_empty(&self) -> bool { + *self == Tags::default() + } + + /// Fill any field this does not have from `other`. + pub(crate) fn merge(&mut self, other: Tags) { + self.title = self.title.take().or(other.title); + self.artist = self.artist.take().or(other.artist); + self.album = self.album.take().or(other.album); + self.date = self.date.take().or(other.date); + self.track = self.track.or(other.track); + } + + fn set(&mut self, key: &str, value: String) { + if value.is_empty() { + return; + } + let field = match key { + "TIT2" | "TT2" | "TITLE" => &mut self.title, + "TPE1" | "TP1" | "ARTIST" => &mut self.artist, + "TALB" | "TAL" | "ALBUM" => &mut self.album, + "TDRC" | "TYER" | "TYE" | "DATE" => &mut self.date, + "TRCK" | "TRK" | "TRACKNUMBER" => { + // "3/12" is a track number and a total; the number is the part + // anything displays. + self.track = value + .split(['/', ' ']) + .next() + .and_then(|n| n.trim().parse().ok()); + return; + } + _ => return, + }; + if field.is_none() { + *field = Some(value); + } + } +} + +/// Total bytes an ID3v2 tag at the head of a stream occupies, header included. +pub(crate) fn id3v2_len(head: &[u8]) -> Option { + if head.len() < 10 || &head[..3] != b"ID3" { + return None; + } + let size = syncsafe(&head[6..10])?; + // Bit 4 of the flags is a footer, which is another ten bytes. + let footer = u64::from(head[5] & 0x10 != 0) * 10; + Some(10 + u64::from(size) + footer) +} + +/// A 28-bit syncsafe integer. +fn syncsafe(b: &[u8]) -> Option { + let b: [u8; 4] = b.get(..4)?.try_into().ok()?; + if b.iter().any(|&x| x & 0x80 != 0) { + return None; + } + Some(u32::from(b[0]) << 21 | u32::from(b[1]) << 14 | u32::from(b[2]) << 7 | u32::from(b[3])) +} + +/// The text frames of a whole ID3v2 tag (header included). +pub(crate) fn from_id3v2(data: &[u8]) -> Tags { + let mut tags = Tags::default(); + if id3v2_len(data).is_none() { + return tags; + } + let version = data[3]; + // An unsynchronised or compressed tag is left alone rather than + // mis-parsed: the audio is what matters here. + if data[5] & 0x80 != 0 { + return tags; + } + let mut at = 10usize; + // An extended header sits between the header and the first frame. + if data[5] & 0x40 != 0 && version >= 3 { + let len = match version { + 3 => data + .get(at..at + 4) + .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize + 4), + _ => data.get(at..at + 4).and_then(syncsafe).map(|n| n as usize), + }; + at += len.unwrap_or(0); + } + let (id_len, size_len) = match version { + 2 => (3, 3), + _ => (4, 4), + }; + while at + id_len + size_len <= data.len() { + let id = &data[at..at + id_len]; + if id[0] == 0 { + break; // padding + } + let size = match (version, &data[at + id_len..at + id_len + size_len]) { + (2, s) => usize::from(s[0]) << 16 | usize::from(s[1]) << 8 | usize::from(s[2]), + (4, s) => syncsafe(s).unwrap_or(0) as usize, + (_, s) => u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize, + }; + let flags = match version { + 2 => 0, + _ => 2, + }; + let start = at + id_len + size_len + flags; + let Some(body) = data.get(start..start + size) else { + break; + }; + if id[0] == b'T' + && let Ok(key) = std::str::from_utf8(id) + { + tags.set(key, text(body)); + } + at = start + size; + } + tags +} + +/// An ID3v2 text frame body: an encoding byte and then the string. +fn text(body: &[u8]) -> String { + let Some((&encoding, rest)) = body.split_first() else { + return String::new(); + }; + let s = match encoding { + // ISO-8859-1: every byte is its own code point. + 0 => rest.iter().map(|&b| char::from(b)).collect(), + 1 | 2 => utf16(rest, encoding == 1), + _ => String::from_utf8_lossy(rest).into_owned(), + }; + s.trim_end_matches('\0').trim().to_string() +} + +/// UTF-16, big-endian unless a byte-order mark says otherwise. +fn utf16(data: &[u8], bom: bool) -> String { + let (data, little) = match (bom, data) { + (true, [0xFF, 0xFE, rest @ ..]) => (rest, true), + (true, [0xFE, 0xFF, rest @ ..]) => (rest, false), + _ => (data, false), + }; + let units: Vec = data + .chunks_exact(2) + .map(|c| match little { + true => u16::from_le_bytes([c[0], c[1]]), + false => u16::from_be_bytes([c[0], c[1]]), + }) + .collect(); + String::from_utf16_lossy(&units) +} + +/// The 128-byte ID3v1 block at the end of a file. +pub(crate) fn from_id3v1(tail: &[u8]) -> Tags { + let mut tags = Tags::default(); + if tail.len() < 128 || &tail[..3] != b"TAG" { + return tags; + } + let field = |r: std::ops::Range| -> String { + tail[r] + .iter() + .take_while(|&&b| b != 0) + .map(|&b| char::from(b)) + .collect::() + .trim() + .to_string() + }; + tags.set("TIT2", field(3..33)); + tags.set("TPE1", field(33..63)); + tags.set("TALB", field(63..93)); + tags.set("TDRC", field(93..97)); + // A zero separator before the last byte means the track number is there. + if tail[125] == 0 && tail[126] != 0 { + tags.track = Some(u32::from(tail[126])); + } + tags +} + +/// A Vorbis comment block: the FLAC metadata block body, or the Ogg packet +/// with its `\x03vorbis` / `OpusTags` signature already stripped. +pub(crate) fn from_vorbis_comment(data: &[u8]) -> Tags { + let mut tags = Tags::default(); + let u32_at = |at: usize| -> Option { + let b: [u8; 4] = data.get(at..at + 4)?.try_into().ok()?; + Some(u32::from_le_bytes(b) as usize) + }; + let Some(vendor) = u32_at(0) else { + return tags; + }; + let mut at = 4 + vendor; + let Some(count) = u32_at(at) else { + return tags; + }; + at += 4; + for _ in 0..count.min(1024) { + let Some(len) = u32_at(at) else { break }; + at += 4; + let Some(entry) = data.get(at..at + len) else { + break; + }; + at += len; + let entry = String::from_utf8_lossy(entry); + if let Some((key, value)) = entry.split_once('=') { + tags.set(&key.to_ascii_uppercase(), value.to_string()); + } + } + tags +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An ID3v2.3 tag of the shape ffmpeg writes, and the v1 block behind it. + #[test] + fn id3_tags_are_read_in_both_versions() { + let mut tag = b"ID3\x03\x00\x00".to_vec(); + let mut frames = Vec::new(); + for (id, body) in [ + ("TIT2", "A Tone"), + ("TPE1", "edith_codecs"), + ("TRCK", "3/12"), + ] { + frames.extend_from_slice(id.as_bytes()); + let text = format!("\u{0}{body}"); + frames.extend_from_slice(&(text.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); + frames.extend_from_slice(text.as_bytes()); + } + let size = frames.len() as u32; + tag.extend_from_slice(&[ + (size >> 21) as u8 & 0x7f, + (size >> 14) as u8 & 0x7f, + (size >> 7) as u8 & 0x7f, + size as u8 & 0x7f, + ]); + tag.extend_from_slice(&frames); + assert_eq!(id3v2_len(&tag), Some(tag.len() as u64)); + let tags = from_id3v2(&tag); + assert_eq!(tags.title.as_deref(), Some("A Tone")); + assert_eq!(tags.artist.as_deref(), Some("edith_codecs")); + assert_eq!(tags.track, Some(3)); + + let mut v1 = vec![0u8; 128]; + v1[..3].copy_from_slice(b"TAG"); + v1[3..3 + 6].copy_from_slice(b"A Tone"); + v1[126] = 7; + let tags = from_id3v1(&v1); + assert_eq!(tags.title.as_deref(), Some("A Tone")); + assert_eq!(tags.track, Some(7)); + } + + #[test] + fn vorbis_comments_are_case_insensitive_keys() { + let mut block = Vec::new(); + let vendor = b"ec-probe"; + block.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); + block.extend_from_slice(vendor); + let entries = ["title=A Tone", "Artist=edith_codecs", "TRACKNUMBER=4"]; + block.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for e in entries { + block.extend_from_slice(&(e.len() as u32).to_le_bytes()); + block.extend_from_slice(e.as_bytes()); + } + let tags = from_vorbis_comment(&block); + assert_eq!(tags.title.as_deref(), Some("A Tone")); + assert_eq!(tags.artist.as_deref(), Some("edith_codecs")); + assert_eq!(tags.track, Some(4)); + assert!(!tags.is_empty()); + } +} diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs new file mode 100644 index 00000000..4337e1d0 --- /dev/null +++ b/crates/ec-probe/tests/library.rs @@ -0,0 +1,261 @@ +//! His library, not fixtures: open, list, decode and seek real files, and +//! compare what the probe says against ffprobe file by file. +//! +//! Driven by `fixtures/real-library-manifest.tsv` (written by +//! `scripts/scan-real-library.sh`). Files that have since moved are skipped and +//! reported, never failed — the manifest is a snapshot of a moving library. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::registry::{MediaType, SeekMode}; +use ec_core::timebase::{TimeBase, Timestamp}; +use ec_probe::Reader; + +fn manifest() -> Vec<(PathBuf, String, String, f64)> { + let path = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); + let Ok(text) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + text.lines() + .skip(1) + .filter_map(|line| { + let f: Vec<&str> = line.split('\t').collect(); + let path = PathBuf::from(f.first()?); + Some(( + path, + (*f.get(1)?).to_string(), + (*f.get(7)?).to_string(), + f.get(8)?.parse().unwrap_or(0.0), + )) + }) + .collect() +} + +/// Decode `secs` of audio from the current position; answers sample frames. +fn decode_some(reader: &mut Reader, stream: u32, secs: f64) -> Result { + let mut decoder = reader.make_decoder(stream).map_err(|e| e.to_string())?; + let rate = f64::from(decoder.sample_rate().max(1)); + let want = (secs * rate) as u64; + let mut out = Vec::new(); + let mut frames = 0u64; + while frames < want { + let packet = match reader.next_packet() { + Ok(p) => p, + Err(e) if e.is_eof() => break, + Err(e) => return Err(format!("demux: {e}")), + }; + if packet.stream != stream { + continue; + } + decoder + .decode(&packet, &mut out) + .map_err(|e| format!("decode: {e}"))?; + frames += (out.len() / decoder.channels().max(1)) as u64; + } + Ok(frames) +} + +/// Ten files with sound, standalone audio first, then Matroska — opened, +/// decoded and seeked, with a per-file row in the report. +#[test] +fn a_real_library_sweep() { + let files = manifest(); + if files.is_empty() { + eprintln!("no manifest — run scripts/scan-real-library.sh"); + return; + } + // Half standalone audio, half Matroska: the two paths this crate owns, and + // one row per distinct audio codec the library actually holds rather than + // ten copies of the same aac remux. + let standalone = |p: &Path| { + let ext = p.extension().and_then(|e| e.to_str()).unwrap_or(""); + [ + "mp3", "flac", "wav", "ogg", "opus", "m4a", "aac", "mp4", "mov", + ] + .contains(&ext) + }; + let mut chosen: Vec<_> = Vec::new(); + let mut seen = Vec::new(); + for want_mkv in [false, true] { + let mut taken = 0; + for f in &files { + let (p, container, acodecs, _) = f; + if acodecs.is_empty() || !p.exists() || taken >= 5 { + continue; + } + let is_mkv = container.contains("matroska"); + if is_mkv != want_mkv || (!is_mkv && !standalone(p)) { + continue; + } + // One file per (container, codec set): variety beats repetition. + let key = format!("{is_mkv}:{acodecs}"); + if seen.contains(&key) { + continue; + } + seen.push(key); + chosen.push(f); + taken += 1; + } + } + assert!(!chosen.is_empty(), "no readable files in the manifest"); + + let mut rows = Vec::new(); + let mut failures = Vec::new(); + for (path, container, acodecs, duration) in &chosen { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + let mut reader = match Reader::open(path) { + Ok(r) => r, + Err(e) => { + failures.push(format!("{name}: open failed: {e}")); + continue; + } + }; + // The first audio stream that actually decodes, which is what a player + // plays; the ones that do not are named below rather than skipped over. + let audio = reader + .streams() + .iter() + .find(|s| { + s.params.codec.media_type() == MediaType::Audio + && reader.make_decoder(s.index).is_ok() + }) + .or_else(|| reader.default_stream(MediaType::Audio)) + .cloned(); + let Some(audio) = audio else { + failures.push(format!("{name}: no audio stream, ffprobe says {acodecs}")); + continue; + }; + let unsupported = reader.unsupported(); + // Every codec ffprobe lists is either decodable here or named as not. + let listed: Vec = reader + .streams() + .iter() + .filter(|s| s.params.codec.media_type() == MediaType::Audio) + .map(|s| s.params.codec.name().to_string()) + .collect(); + let decoded = decode_some(&mut reader, audio.index, 1.0); + let rate = audio.params.audio().map_or(0, |a| a.sample_rate).max(1); + let landing = if *duration > 4.0 { + let ticks = (duration / 2.0 * f64::from(rate)) as i64; + reader + .seek( + audio.index, + Timestamp::new(ticks, TimeBase::from_rate(rate)), + SeekMode::SyncBefore, + ) + .map(|t| t.as_secs_f64()) + .map_err(|e| e.to_string()) + } else { + Ok(0.0) + }; + let after_seek = landing + .as_ref() + .ok() + .map(|_| decode_some(&mut reader, audio.index, 0.5)); + + let ok = decoded.is_ok() + && landing.is_ok() + && matches!(after_seek, Some(Ok(n)) if n > 0) + && listed.iter().any(|c| acodecs.split(',').any(|a| a == c)); + if !ok { + failures.push(format!( + "{name}: decode {decoded:?} seek {landing:?} after {after_seek:?} \ + codecs {listed:?} vs ffprobe {acodecs}" + )); + } + rows.push(format!( + "{:<52} {:<16} {:<14} {:>7} frames seek->{:>8} {}", + name.chars().take(52).collect::(), + container.split(',').next().unwrap_or(container), + listed.join(","), + decoded.clone().unwrap_or(0), + landing + .as_ref() + .map(|s| format!("{s:.2}s")) + .unwrap_or_else(|e| e.clone()), + match unsupported.is_empty() { + true => "all decodable".to_string(), + false => unsupported + .iter() + .map(|u| format!("unsupported: {} ({})", u.codec.name(), u.reason)) + .collect::>() + .join("; "), + } + )); + } + eprintln!( + "real-library sweep ({} files):\n{}", + rows.len(), + rows.join("\n") + ); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +/// The TrueHD remux in his library: the track is *listed*, with a reason, and +/// the AC-3 track beside it still decodes. A file whose sound is refused +/// silently is the failure this exists to prevent. +#[test] +fn an_undecodable_track_is_named_not_hidden() { + let Some((path, ..)) = manifest() + .into_iter() + .find(|(p, _, acodecs, _)| acodecs.contains("truehd") && p.exists()) + else { + eprintln!("no TrueHD file in the manifest — skipping"); + return; + }; + let reader = Reader::open(&path).expect("open"); + let unsupported = reader.unsupported(); + let truehd = unsupported + .iter() + .find(|u| u.codec.name() == "truehd") + .expect("the TrueHD track is listed as unsupported"); + assert!( + truehd.reason.contains("truehd"), + "the reason names the codec: {}", + truehd.reason + ); + // ...and the other track of the same file plays. + let decodable: Vec<_> = reader + .streams() + .iter() + .filter(|s| s.params.codec.media_type() == MediaType::Audio) + .filter(|s| reader.make_decoder(s.index).is_ok()) + .map(|s| s.params.codec.name()) + .collect(); + assert!( + !decodable.is_empty(), + "a file with a TrueHD track and an AC-3 one came out with nothing to play" + ); + eprintln!( + "{}: {} listed unsupported ({}), decodable: {decodable:?}", + path.file_name().unwrap().to_string_lossy(), + truehd.codec.name(), + truehd.reason + ); +} + +/// ffprobe's stream count for the same file, as a cross-check that nothing is +/// being hidden. +#[allow(dead_code)] +fn ffprobe_audio_codecs(path: &Path) -> Vec { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a", + "-show_entries", + "stream=codec_name", + "-of", + "default=nw=1:nk=1", + ]) + .arg(path) + .output() + .expect("ffprobe"); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim().to_string()) + .collect() +} diff --git a/crates/ec-probe/tests/matrix.rs b/crates/ec-probe/tests/matrix.rs new file mode 100644 index 00000000..db94d9d9 --- /dev/null +++ b/crates/ec-probe/tests/matrix.rs @@ -0,0 +1,309 @@ +//! The probe matrix: every standalone audio fixture opens as the right format +//! and codec, decodes to the end, counts the packets ffprobe counts, and lands +//! where it says it does after a hundred random seeks — on one reader. +//! +//! Oracle is ffmpeg/ffprobe (labelled as such: this is not a conformance +//! claim). A missing fixture skips its row rather than failing the suite, so a +//! checkout without generated fixtures still builds and runs. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::registry::{MediaType, SeekMode}; +use ec_core::timebase::{TimeBase, Timestamp}; +use ec_probe::{Format, Reader}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") +} + +/// `ffprobe` on one entry of the first audio stream. +fn probe(path: &Path, args: &[&str]) -> String { + let out = Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "a:0"]) + .args(args) + .args(["-of", "default=nw=1:nk=1"]) + .arg(path) + .output() + .expect("ffprobe"); + assert!( + out.status.success(), + "ffprobe {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +/// Packets ffprobe counts on the first audio stream. +fn ffprobe_packets(path: &Path) -> u64 { + probe( + path, + &["-count_packets", "-show_entries", "stream=nb_read_packets"], + ) + .lines() + .next() + .and_then(|l| l.trim().parse().ok()) + .unwrap_or(0) +} + +/// Sample frames ffmpeg decodes out of the first audio stream. +fn ffmpeg_frames(path: &Path, channels: usize) -> u64 { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(path) + .args(["-map", "0:a:0", "-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + assert!(out.status.success(), "ffmpeg {}", path.display()); + (out.stdout.len() / 4 / channels.max(1)) as u64 +} + +/// Decode a whole file through the probe: `(packets, sample frames, channels)`. +fn decode_all(reader: &mut Reader, stream: u32) -> (u64, u64, usize) { + let mut decoder = reader.make_decoder(stream).expect("a decoder"); + let mut out = Vec::new(); + let (mut packets, mut frames) = (0u64, 0u64); + loop { + let packet = match reader.next_packet() { + Ok(p) => p, + Err(e) if e.is_eof() => break, + Err(e) => panic!("demux: {e}"), + }; + if packet.stream != stream { + continue; + } + packets += 1; + decoder.decode(&packet, &mut out).expect("decode"); + frames += (out.len() / decoder.channels().max(1)) as u64; + } + (packets, frames, decoder.channels()) +} + +/// name, expected format, expected codec name. +const MATRIX: &[(&str, Format, &str)] = &[ + ("wav16-mono-44100.wav", Format::Wav, "pcm_s16le"), + ("wav16-stereo-48000.wav", Format::Wav, "pcm_s16le"), + ("wav16-5.1-48000.wav", Format::Wav, "pcm_s16le"), + ("flac-mono-44100.flac", Format::Flac, "flac"), + ("flac-stereo-48000.flac", Format::Flac, "flac"), + ("flac-5.1-44100.flac", Format::Flac, "flac"), + ("mp3-mono-44100.mp3", Format::Mp3, "mp3"), + ("mp3-stereo-48000.mp3", Format::Mp3, "mp3"), + ("aac-adts-mono-44100.aac", Format::Adts, "aac"), + ("aac-adts-stereo-48000.aac", Format::Adts, "aac"), + ("aac-adts-5.1-48000.aac", Format::Adts, "aac"), + ("aac-mp4-stereo-48000.mp4", Format::Mp4, "aac"), + ("aac-mp4-5.1-44100.mp4", Format::Mp4, "aac"), + ("alac-mp4-stereo-44100.m4a", Format::Mp4, "alac"), + ("alac-mp4-5.1-48000.m4a", Format::Mp4, "alac"), + ("alac24-mp4-stereo-48000.m4a", Format::Mp4, "alac"), + ("vorbis-ogg-mono-44100.ogg", Format::Ogg, "vorbis"), + ("vorbis-ogg-stereo-48000.ogg", Format::Ogg, "vorbis"), + ("vorbis-ogg-5.1-48000.ogg", Format::Ogg, "vorbis"), + ("opus-ogg-mono-48000.opus", Format::Ogg, "opus"), + ("opus-ogg-stereo-48000.opus", Format::Ogg, "opus"), + ("opus-ogg-5.1-48000.opus", Format::Ogg, "opus"), + ("aac-mka-stereo-48000.mka", Format::Matroska, "aac"), + ("flac-mka-stereo-48000.mka", Format::Matroska, "flac"), + ("opus-mka-stereo-48000.mka", Format::Matroska, "opus"), + ("av-h264-aac-stereo-48000.mkv", Format::Matroska, "aac"), +]; + +#[test] +fn every_fixture_probes_decodes_and_counts() { + let mut checked = 0; + let mut rows = Vec::new(); + for &(name, format, codec) in MATRIX { + let path = fixtures().join(name); + if !path.exists() { + continue; + } + let mut reader = Reader::open(&path).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!(reader.format(), format, "{name}: format"); + let audio = reader + .default_stream(MediaType::Audio) + .unwrap_or_else(|| panic!("{name}: no audio stream")) + .clone(); + assert_eq!(audio.params.codec.name(), codec, "{name}: codec"); + + let (packets, frames, channels) = decode_all(&mut reader, audio.index); + let want_frames = ffmpeg_frames(&path, channels); + // Lossless formats are exact; a coded one carries encoder priming that + // ffmpeg trims and this reader hands out, so it decodes *more*. + let exact = matches!(codec, "flac" | "alac") || codec.starts_with("pcm"); + if exact { + assert_eq!(frames, want_frames, "{name}: sample frames"); + } else { + let slack = 4096 + want_frames / 20; + assert!( + frames + slack >= want_frames && frames <= want_frames + slack, + "{name}: {frames} frames decoded, ffmpeg says {want_frames}" + ); + } + // Packet counts are the demuxer's own claim and must match exactly — + // except for PCM, where a "packet" is this reader's own chunking. + if !codec.starts_with("pcm") { + let want_packets = ffprobe_packets(&path); + assert_eq!(packets, want_packets, "{name}: packet count"); + } + // A stated duration must be within a frame of the truth. + if let Some(d) = reader.duration() { + let want = want_frames as f64 / f64::from(audio.params.audio().unwrap().sample_rate); + assert!( + (d.as_secs_f64() - want).abs() < 0.2, + "{name}: duration {} vs {want}", + d.as_secs_f64() + ); + } + rows.push(format!( + "{name:34} {:9} {codec:6} {channels}ch {packets:5} packets {frames:8} frames", + format.name() + )); + checked += 1; + } + assert!( + checked > 0, + "no fixtures found — run scripts/gen-fixtures.sh" + ); + eprintln!("probe matrix ({checked} files):\n{}", rows.join("\n")); +} + +/// A hundred random seeks per format, on **one** reader, each landing at or +/// before its target and within the container's own granularity of it. +#[test] +fn a_hundred_random_seeks_land_where_they_say() { + let mut checked = 0; + for &(name, _, codec) in MATRIX { + let path = fixtures().join(name); + if !path.exists() { + continue; + } + let mut reader = Reader::open(&path).expect("open"); + let audio = reader + .default_stream(MediaType::Audio) + .expect("audio") + .clone(); + let rate = audio.params.audio().unwrap().sample_rate.max(1); + let Some(duration) = reader.duration() else { + continue; + }; + let secs = duration.as_secs_f64(); + // Tolerance is the container's own granularity: Ogg lands on a page + // (3936 bytes on these fixtures, over a second of audio) and Matroska + // on a cluster, while every other format lands inside the frame that + // holds the target — so their tolerance is that frame's own length, + // taken from the packet itself below. + let coarse = match name { + n if n.ends_with(".mka") || n.ends_with(".mkv") => Some(2.5), + n if n.ends_with(".ogg") || n.ends_with(".opus") => Some(2.5), + _ => None, + }; + let mut state = 0x2545_F491_4F6C_DD1Du64; + for _ in 0..100 { + // xorshift: a deterministic spread of targets, no dev-dependency. + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let target = (state % 1_000_000) as f64 / 1_000_000.0 * secs; + let ticks = (target * f64::from(rate)) as i64; + let landed = reader + .seek( + audio.index, + Timestamp::new(ticks, TimeBase::from_rate(rate)), + SeekMode::SyncBefore, + ) + .unwrap_or_else(|e| panic!("{name}: seek to {target:.3}s: {e}")); + let at = landed.as_secs_f64(); + assert!( + at <= target + 0.001, + "{name}: asked for {target:.3}s, landed at {at:.3}s — past the target" + ); + // And the reader really is there: the landing is a packet's own + // timestamp, not an estimate. + let tolerance = loop { + let packet = reader.next_packet().expect("a packet after a seek"); + if packet.stream != audio.index { + continue; + } + assert!(!packet.data.is_empty(), "{name}: an empty packet"); + assert_eq!( + packet.pts.unwrap_or(0), + landed.ticks, + "{name}: the landing is not the next packet's own timestamp" + ); + break coarse.unwrap_or_else(|| { + packet.duration.unwrap_or(1) as f64 / f64::from(rate) + 0.001 + }); + }; + assert!( + target - at <= tolerance, + "{name}: asked for {target:.3}s, landed at {at:.3}s — {:.3}s short of a container granularity of {tolerance:.3}s", + target - at + ); + } + let _ = codec; + checked += 1; + } + assert!( + checked > 0, + "no fixtures found — run scripts/gen-fixtures.sh" + ); + eprintln!("100 random seeks each on {checked} files, one reader per file"); +} + +/// Cover art is a still picture, not a video track, in both containers that +/// carry one — and the audio beside it still opens. +#[test] +fn cover_art_is_never_a_video_track() { + let mut checked = 0; + for name in ["cover-mp3-stereo-44100.mp3", "cover-mp4-stereo-44100.m4a"] { + let path = fixtures().join(name); + if !path.exists() { + continue; + } + let reader = Reader::open(&path).expect("open"); + let video: Vec<_> = reader + .streams() + .iter() + .filter(|s| s.params.codec.media_type() == MediaType::Video) + .collect(); + assert!( + video.is_empty(), + "{name}: cover art listed as a video track: {video:?}" + ); + assert!( + reader.default_stream(MediaType::Audio).is_some(), + "{name}: no audio" + ); + checked += 1; + } + assert!(checked > 0, "no cover-art fixtures — run gen-fixtures.sh"); +} + +/// The tags an ID3v2-tagged file carries come back off it. +#[test] +fn id3_tags_come_off_a_real_file() { + let path = fixtures().join("cover-mp3-stereo-44100.mp3"); + if !path.exists() { + return; + } + let reader = Reader::open(&path).expect("open"); + assert_eq!(reader.tags().title.as_deref(), Some("A Tone")); + assert_eq!(reader.tags().artist.as_deref(), Some("edith_codecs")); +} + +/// A mislabelled file is still the file it is: the sniff decides, not the +/// extension. +#[test] +fn a_mislabelled_file_opens_as_what_it_is() { + let src = fixtures().join("flac-stereo-48000.flac"); + if !src.exists() { + return; + } + let liar = std::env::temp_dir().join("ec-probe-liar.mp3"); + std::fs::copy(&src, &liar).expect("copy"); + let reader = Reader::open(&liar).expect("open"); + assert_eq!(reader.format(), Format::Flac); + std::fs::remove_file(&liar).ok(); +}