forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_ext.rs486 lines, 15.6 KiBHistoryRawDownload
1//! DTS and the legacy audio codecs (IMA and MS ADPCM, ima4, A-law, mu-law, AMR-NB/WB)
2//! imported and decoded through the engine from every container that carries them.
3//!
4//! The fixtures are made here, at test time, by ffmpeg: a short two-tone signal
5//! encoded with the codec under test into a Matroska, mp4 / QuickTime / 3GP, WAVE,
6//! AVI or MPEG transport stream file, or a raw `.dts` / `.amr`. Each file is held to
7//! ffmpeg's own decode of the same bytes: mono and stereo sample for sample within a
8//! tight tolerance (the decoders are integer or bit-exact against ffmpeg's), and the
9//! 5.1 DTS, which reaches the timeline as the stereo pair every multichannel source
10//! does, by correlation with ffmpeg's `-ac 2` fold (the fold's coefficients are
11//! edith's, not ffmpeg's, so the samples cannot be equal).
12//!
13//! Skipped, loudly, where ffmpeg (or the encoder a case needs, AMR's above all) is
14//! not installed.
15
16use std::path::Path;
17use std::process::Command;
18
19use engine::audio::AudioSession;
20use engine::scratch::Scratch;
21
22fn have_ffmpeg() -> bool {
23 Command::new("ffmpeg")
24 .arg("-version")
25 .output()
26 .is_ok_and(|o| o.status.success())
27}
28
29/// Whether this ffmpeg lists `name` among its encoders (or decoders with `-decoders`).
30fn ffmpeg_has(kind: &str, name: &str) -> bool {
31 Command::new("ffmpeg")
32 .args(["-hide_banner", kind])
33 .output()
34 .is_ok_and(|o| {
35 String::from_utf8_lossy(&o.stdout)
36 .lines()
37 .any(|l| l.split_whitespace().nth(1) == Some(name))
38 })
39}
40
41/// What a case is: how it is made, what comes out of the engine.
42struct Case {
43 name: &'static str,
44 /// File extension, which picks ffmpeg's muxer.
45 ext: &'static str,
46 codec: &'static str,
47 /// The encoder ffmpeg must have, else the case is skipped.
48 encoder: &'static str,
49 /// Extra output arguments (`-strict -2`, a bit rate, `-f dts`).
50 extra: &'static [&'static str],
51 rate: u32,
52 /// Channels of the source; the timeline gets 1 or 2.
53 channels: usize,
54 /// A picture alongside the sound (`mpeg4`, or `mpeg2video` for a transport stream).
55 video: Option<&'static str>,
56 /// ffmpeg decoder to read the reference with, when the default is not the one.
57 decoder: Option<&'static str>,
58}
59
60impl Case {
61 const fn new(
62 name: &'static str,
63 ext: &'static str,
64 codec: &'static str,
65 rate: u32,
66 channels: usize,
67 ) -> Self {
68 Self {
69 name,
70 ext,
71 codec,
72 encoder: codec,
73 extra: &[],
74 rate,
75 channels,
76 video: None,
77 decoder: None,
78 }
79 }
80
81 const fn extra(mut self, extra: &'static [&'static str]) -> Self {
82 self.extra = extra;
83 self
84 }
85
86 const fn video(mut self, codec: &'static str) -> Self {
87 self.video = Some(codec);
88 self
89 }
90
91 const fn decoder(mut self, decoder: &'static str) -> Self {
92 self.decoder = Some(decoder);
93 self
94 }
95
96 const fn encoder(mut self, encoder: &'static str) -> Self {
97 self.encoder = encoder;
98 self
99 }
100
101 /// The fixture, or `None` (said aloud) where ffmpeg cannot make it.
102 fn make(&self) -> Option<Scratch> {
103 if !have_ffmpeg() {
104 eprintln!("skipped {}: no ffmpeg to encode the fixture with", self.name);
105 return None;
106 }
107 if !ffmpeg_has("-encoders", self.encoder) {
108 eprintln!(
109 "skipped {}: this ffmpeg has no `{}` encoder to make the fixture with",
110 self.name, self.encoder
111 );
112 return None;
113 }
114 if let Some(decoder) = self.decoder
115 && !ffmpeg_has("-decoders", decoder)
116 {
117 eprintln!(
118 "skipped {}: this ffmpeg has no `{decoder}` decoder to make the reference with",
119 self.name
120 );
121 return None;
122 }
123 // A distinct tone per channel, so a swapped or dropped channel is heard.
124 let tones = [440.0, 660.0, 880.0, 110.0, 550.0, 330.0];
125 let expr = (0..self.channels)
126 .map(|c| {
127 format!(
128 "{:.2}*sin(2*PI*{}*t)+0.15*sin(2*PI*{}*t)",
129 0.35 - 0.02 * c as f64,
130 tones[c % tones.len()],
131 tones[(c + 2) % tones.len()] * 3.0
132 )
133 })
134 .collect::<Vec<_>>()
135 .join("|");
136 let file = Scratch::file(self.name, self.ext);
137 let mut cmd = Command::new("ffmpeg");
138 cmd.args(["-v", "error", "-y"])
139 .args(["-f", "lavfi", "-i"])
140 .arg(format!("aevalsrc={expr}:s={}:d=2", self.rate));
141 if let Some(video) = self.video {
142 cmd.args(["-f", "lavfi", "-i", "color=c=gray:s=64x64:r=10:d=2"])
143 .args(["-c:v", video, "-pix_fmt", "yuv420p"]);
144 }
145 let out = cmd
146 .args(["-c:a", self.codec])
147 .args(self.extra)
148 .arg(&*file)
149 .output()
150 .expect("ffmpeg runs");
151 assert!(
152 out.status.success(),
153 "ffmpeg ({}): {}",
154 self.name,
155 String::from_utf8_lossy(&out.stderr)
156 );
157 Some(file)
158 }
159}
160
161/// ffmpeg's decode of `path`'s first audio track as f32, `channels` wide when given.
162fn ffmpeg_f32(path: &Path, decoder: Option<&str>, channels: Option<&str>) -> Vec<f32> {
163 let mut cmd = Command::new("ffmpeg");
164 cmd.args(["-v", "error"]);
165 if let Some(decoder) = decoder {
166 cmd.args(["-c:a", decoder]);
167 }
168 cmd.arg("-i").arg(path).args(["-map", "0:a:0"]);
169 if let Some(channels) = channels {
170 cmd.args(["-ac", channels]);
171 }
172 let out = cmd.args(["-f", "f32le", "-"]).output().expect("ffmpeg runs");
173 assert!(
174 out.status.success(),
175 "ffmpeg decode: {}",
176 String::from_utf8_lossy(&out.stderr)
177 );
178 out.stdout
179 .as_chunks::<4>()
180 .0
181 .iter()
182 .map(|b| f32::from_le_bytes(*b))
183 .collect()
184}
185
186/// The interleaved samples of `path`'s first audio track at its own `rate` (the mix
187/// would otherwise take a source under 44.1 kHz up to 48 kHz), with its metadata.
188fn decode_at(path: &Path, rate: u32) -> (engine::audio::AudioMeta, Vec<f32>) {
189 let (meta, rx) = AudioSession::open_multi_streams_speed_at(
190 &[(path.to_path_buf(), 0)],
191 &[(Some(0), 0.0, f64::INFINITY)],
192 &[],
193 &[],
194 Some(rate),
195 )
196 .expect("opens")
197 .expect("has an audio track");
198 let mut samples = Vec::new();
199 for chunk in rx {
200 samples.extend_from_slice(&chunk.samples);
201 }
202 (meta, samples)
203}
204
205fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> {
206 interleaved
207 .iter()
208 .skip(index)
209 .step_by(channels)
210 .copied()
211 .collect()
212}
213
214fn correlation(a: &[f32], b: &[f32]) -> f64 {
215 let n = a.len().min(b.len());
216 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
217 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
218 dot += f64::from(x) * f64::from(y);
219 aa += f64::from(x) * f64::from(x);
220 bb += f64::from(y) * f64::from(y);
221 }
222 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
223}
224
225/// Opens the case's fixture through the engine and holds it to ffmpeg's decode.
226fn check(case: &Case, tolerance: f32) {
227 let Some(file) = case.make() else { return };
228 let timeline = if case.channels == 1 { 1 } else { 2 };
229 let (meta, ours) = decode_at(&file, case.rate);
230 assert_eq!(
231 (meta.sample_rate, usize::from(meta.channels)),
232 (case.rate, timeline),
233 "{}: rate and channels of the import",
234 case.name
235 );
236 assert!(!ours.is_empty(), "{}: no sound out of the track", case.name);
237 assert!(
238 ours.iter().any(|s| s.abs() > 0.05),
239 "{}: the decode is silent",
240 case.name
241 );
242
243 if case.channels <= 2 {
244 let theirs = ffmpeg_f32(&file, case.decoder, None);
245 let slack = 4096 * timeline;
246 assert!(
247 ours.len().abs_diff(theirs.len()) <= slack,
248 "{}: {} samples out, {} from ffmpeg",
249 case.name,
250 ours.len(),
251 theirs.len()
252 );
253 let n = ours.len().min(theirs.len());
254 let worst = ours[..n]
255 .iter()
256 .zip(&theirs[..n])
257 .map(|(o, t)| (o - t).abs())
258 .fold(0f32, f32::max);
259 assert!(
260 worst <= tolerance,
261 "{}: worst sample differs from ffmpeg by {worst} (limit {tolerance})",
262 case.name
263 );
264 } else {
265 let theirs = ffmpeg_f32(&file, case.decoder, Some("2"));
266 for index in 0..2 {
267 let level = ours.iter().skip(index).step_by(2).map(|s| s.abs()).fold(0f32, f32::max);
268 assert!(level > 1e-3, "{}: timeline channel {index} is silent", case.name);
269 let score = correlation(&channel(&ours, 2, index), &channel(&theirs, 2, index));
270 assert!(
271 score > 0.98,
272 "{}: timeline channel {index} correlates {score:.4} with ffmpeg's -ac 2 decode",
273 case.name
274 );
275 }
276 }
277}
278
279const DTS: &[&str] = &["-strict", "-2", "-b:a", "384k"];
280/// Float decoding of the integer DTS core: well inside this on every sample.
281const DTS_TOL: f32 = 2e-4;
282const EXACT: f32 = 1e-4;
283
284#[test]
285fn dts_stereo_in_matroska_matches_ffmpeg() {
286 check(&Case::new("ve_dts_mka", "mka", "dca", 48_000, 2).extra(DTS), DTS_TOL);
287}
288
289#[test]
290fn dts_stereo_in_matroska_video_matches_ffmpeg() {
291 check(
292 &Case::new("ve_dts_mkv", "mkv", "dca", 48_000, 2)
293 .extra(DTS)
294 .video("mpeg4"),
295 DTS_TOL,
296 );
297}
298
299#[test]
300fn dts_51_in_matroska_folds_to_ffmpegs_stereo_by_correlation() {
301 check(
302 &Case::new("ve_dts_51_mka", "mka", "dca", 48_000, 6).extra(&["-strict", "-2", "-b:a", "1536k"]),
303 DTS_TOL,
304 );
305}
306
307#[test]
308fn raw_dts_file_matches_ffmpeg() {
309 check(
310 &Case::new("ve_dts_raw", "dts", "dca", 48_000, 2).extra(&["-strict", "-2", "-b:a", "384k", "-f", "dts"]),
311 DTS_TOL,
312 );
313}
314
315#[test]
316fn dts_in_mp4_matches_ffmpeg() {
317 check(
318 &Case::new("ve_dts_mp4", "mp4", "dca", 48_000, 2)
319 .extra(DTS)
320 .video("mpeg4"),
321 DTS_TOL,
322 );
323}
324
325#[test]
326fn dts_in_transport_stream_matches_ffmpeg() {
327 check(
328 &Case::new("ve_dts_ts", "ts", "dca", 48_000, 2)
329 .extra(DTS)
330 .video("mpeg2video"),
331 DTS_TOL,
332 );
333}
334
335#[test]
336fn dts_in_wav_matches_ffmpeg() {
337 check(
338 &Case::new("ve_dts_wav", "wav", "dca", 48_000, 2).extra(&["-strict", "-2", "-b:a", "384k", "-f", "wav"]),
339 DTS_TOL,
340 );
341}
342
343#[test]
344fn dts_in_avi_matches_ffmpeg() {
345 check(
346 &Case::new("ve_dts_avi", "avi", "dca", 48_000, 2)
347 .extra(DTS)
348 .video("mpeg4"),
349 DTS_TOL,
350 );
351}
352
353#[test]
354fn ima_adpcm_wav_matches_ffmpeg() {
355 check(&Case::new("ve_ima_wav", "wav", "adpcm_ima_wav", 44_100, 2), EXACT);
356 check(&Case::new("ve_ima_wav_mono", "wav", "adpcm_ima_wav", 22_050, 1), EXACT);
357}
358
359#[test]
360fn ms_adpcm_wav_matches_ffmpeg() {
361 check(&Case::new("ve_msadpcm_wav", "wav", "adpcm_ms", 44_100, 2), EXACT);
362 check(&Case::new("ve_msadpcm_wav_mono", "wav", "adpcm_ms", 22_050, 1), EXACT);
363}
364
365#[test]
366fn alaw_and_mulaw_wav_match_ffmpeg() {
367 check(&Case::new("ve_alaw_wav", "wav", "pcm_alaw", 8_000, 1), EXACT);
368 check(&Case::new("ve_mulaw_wav", "wav", "pcm_mulaw", 8_000, 1), EXACT);
369 check(&Case::new("ve_alaw_wav_st", "wav", "pcm_alaw", 44_100, 2), EXACT);
370}
371
372#[test]
373fn adpcm_and_g711_in_avi_match_ffmpeg() {
374 for (name, codec, rate) in [
375 ("ve_ima_avi", "adpcm_ima_wav", 44_100),
376 ("ve_msadpcm_avi", "adpcm_ms", 44_100),
377 ("ve_alaw_avi", "pcm_alaw", 8_000),
378 ("ve_mulaw_avi", "pcm_mulaw", 8_000),
379 ] {
380 let channels = if rate == 8_000 { 1 } else { 2 };
381 check(&Case::new(name, "avi", codec, rate, channels).video("mpeg4"), EXACT);
382 }
383}
384
385#[test]
386fn ima4_and_g711_in_quicktime_match_ffmpeg() {
387 check(
388 &Case::new("ve_ima4_mov", "mov", "adpcm_ima_qt", 44_100, 2).video("mpeg4"),
389 EXACT,
390 );
391 check(
392 &Case::new("ve_alaw_mov", "mov", "pcm_alaw", 8_000, 1).video("mpeg4"),
393 EXACT,
394 );
395 check(
396 &Case::new("ve_mulaw_mov", "mov", "pcm_mulaw", 8_000, 1).video("mpeg4"),
397 EXACT,
398 );
399}
400
401#[test]
402fn amr_nb_in_3gp_and_raw_matches_ffmpeg() {
403 let nb = |name, ext, extra: &'static [&'static str]| {
404 Case::new(name, ext, "libopencore_amrnb", 8_000, 1)
405 .extra(extra)
406 .decoder("libopencore_amrnb")
407 };
408 check(&nb("ve_amrnb_3gp", "3gp", &["-b:a", "12.2k"]).video("mpeg4"), EXACT);
409 check(&nb("ve_amrnb_raw", "amr", &["-b:a", "7.95k"]), EXACT);
410 check(&nb("ve_amrnb_mov", "mov", &["-b:a", "10.2k"]).video("mpeg4"), EXACT);
411}
412
413#[test]
414fn amr_wb_in_3gp_and_raw_matches_ffmpeg() {
415 let wb = |name, ext| {
416 Case::new(name, ext, "libvo_amrwbenc", 16_000, 1)
417 .extra(if ext == "awb" { &["-f", "amr"] } else { &["-f", "3gp"] })
418 .encoder("libvo_amrwbenc")
419 .decoder("libopencore_amrwb")
420 };
421 check(&wb("ve_amrwb_3gp", "3gp").video("mpeg4"), EXACT);
422 check(&wb("ve_amrwb_raw", "awb"), EXACT);
423}
424
425#[test]
426fn dts_refuses_lossless_by_name_and_reports_decodable_streams() {
427 // The stream listing of a DTS Matroska file says it decodes.
428 let Some(file) = Case::new("ve_dts_probe", "mka", "dca", 48_000, 2).extra(DTS).make() else {
429 return;
430 };
431 let streams = AudioSession::probe_streams(&*file).expect("lists");
432 assert_eq!(streams.len(), 1);
433 assert!(streams[0].decodable, "{:?}", streams[0]);
434 assert_eq!((streams[0].sample_rate, streams[0].channels), (48_000, 2));
435 assert_eq!(AudioSession::unsupported(&*file).expect("asks"), None);
436}
437
438#[test]
439fn dts_window_starts_where_asked() {
440 let Some(file) = Case::new("ve_dts_window", "mka", "dca", 48_000, 2).extra(DTS).make() else {
441 return;
442 };
443 let (_, whole) = decode_at(&file, 48_000);
444 let (meta, rx) = AudioSession::open_at(&*file, 1.0).expect("opens").expect("has sound");
445 let mut tail = Vec::new();
446 for chunk in rx {
447 tail.extend_from_slice(&chunk.samples);
448 }
449 let from = 48_000 * usize::from(meta.channels);
450 let n = tail.len().min(whole.len() - from);
451 assert!(n > 40_000, "the window decoded only {n} samples");
452 let worst = tail[..n]
453 .iter()
454 .zip(&whole[from..from + n])
455 .map(|(a, b)| (a - b).abs())
456 .fold(0f32, f32::max);
457 assert!(worst < 2e-3, "a window at 1 s differs from the whole decode by {worst}");
458}
459
460/// MP2 (MPEG-1 Layer II). ffmpeg writes it into mp4 under the MP3 object type (0x6B), and into
461/// Matroska as `A_MPEG/L2`; the frames are read by `ec-mp3`, which takes every layer.
462const MP2_TOL: f32 = 1e-3;
463
464#[test]
465fn mp2_in_mp4_and_matroska_matches_ffmpeg() {
466 let mp2 = |name, ext| {
467 Case::new(name, ext, "mp2", 44_100, 1).extra(&["-b:a", "128k"]).video("mpeg4")
468 };
469 check(&mp2("ve_mp2_mp4", "mp4"), MP2_TOL);
470 check(&mp2("ve_mp2_mkv", "mkv"), MP2_TOL);
471}
472
473#[test]
474fn mp2_is_named_mp2_and_decodes_in_mp4_and_matroska() {
475 for (name, ext) in [("ve_mp2_named_mp4", "mp4"), ("ve_mp2_named_mkv", "mkv")] {
476 let case = Case::new(name, ext, "mp2", 44_100, 1).extra(&["-b:a", "128k"]).video("mpeg4");
477 let Some(file) = case.make() else {
478 return;
479 };
480 let streams = AudioSession::probe_streams(&*file).expect("lists");
481 assert_eq!(streams.len(), 1, "{name}");
482 assert_eq!(streams[0].codec, "mp2", "{name}: named by its layer, not as mp3");
483 assert!(streams[0].decodable, "{name}: {:?}", streams[0]);
484 assert_eq!(AudioSession::unsupported(&*file).expect("asks"), None, "{name}");
485 }
486}