forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

matrix.rs375 lines, 14.5 KiBHistoryRawDownload
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
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_core::registry::{MediaType, SeekMode};
13use ec_core::timebase::{TimeBase, Timestamp};
14use ec_probe::{Format, Reader};
15
16fn fixtures() -> PathBuf {
17 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18}
19
20/// `ffprobe` on one entry of the first audio stream.
21fn 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.
39fn 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.
51fn 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)`.
63fn 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.
84const 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]
114fn 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]
175fn 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]
258fn 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]
286fn 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]
299fn 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}
310
311/// The head of a file, where two things are exact rather than approximate:
312/// what a gapless MP3's audible length is, and where a seek to zero lands.
313///
314/// Both were wrong at once. The LAME tag's encoder delay and padding went
315/// unread, so an `.mp3` claimed the silence around its sound as part of it and
316/// played 25 ms late against a `.flac` of the same tone; and a seek to zero
317/// started at the first *cue*, which in a file whose cues name only the video
318/// track sits past the first audio block — 20 ms of an export, a cluster of a
319/// film, gone from the start of every playback that seeked to the beginning.
320#[test]
321fn the_head_of_a_file_is_exact() {
322 let mut checked = 0;
323 for &(name, _, codec) in MATRIX {
324 let path = fixtures().join(name);
325 if !path.exists() {
326 continue;
327 }
328 let mut reader = Reader::open(&path).expect("open");
329 let audio = reader
330 .default_stream(MediaType::Audio)
331 .expect("audio")
332 .clone();
333 // Gapless: what the file states it holds, less the silence it states it
334 // padded with, is exactly what ffmpeg decodes out of it.
335 if codec == "mp3" {
336 let padding = u64::from(audio.initial_padding);
337 assert!(
338 padding > 0,
339 "{name}: no encoder delay read out of the LAME tag"
340 );
341 let stated = audio.duration.expect("an mp3 states its length") as u64;
342 let channels = audio.params.audio().unwrap().layout.channel_count();
343 assert_eq!(
344 stated - padding,
345 ffmpeg_frames(&path, channels),
346 "{name}: audible frames"
347 );
348 }
349 // A seek to the beginning lands on the file's own first packet, never
350 // past it. Asked for by that packet's own timestamp rather than by
351 // zero, because an mp4's first AAC packet is at -1024: its priming.
352 let first = loop {
353 let packet = reader.next_packet().expect("a first packet");
354 if packet.stream == audio.index {
355 break packet.pts.unwrap_or(0);
356 }
357 };
358 let landed = reader
359 .seek(
360 audio.index,
361 Timestamp::new(first, audio.time_base),
362 SeekMode::SyncBefore,
363 )
364 .unwrap_or_else(|e| panic!("{name}: seek to the beginning: {e}"));
365 assert_eq!(
366 landed.ticks, first,
367 "{name}: a seek to the beginning landed past the first packet"
368 );
369 checked += 1;
370 }
371 assert!(
372 checked > 0,
373 "no fixtures found — run scripts/gen-fixtures.sh"
374 );
375}