forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

real_library_audio.rs290 lines, 9.3 KiBHistoryRawDownload
1//! The audio seats on the owner's own files, against ffmpeg's own decode of the
2//! same file at the same rate and channel count, in 32-bit float.
3//!
4//! * AAC (HE-AAC v1 and AAC-LC, in mp4): per channel, the Pearson correlation of
5//! the decoded track against ffmpeg's must be at least 0.999, at the lag the
6//! two streams line up at. That lag is searched first (+-2048 samples over the
7//! opening two seconds), and must be 0 or the engine's documented default
8//! priming of 1024 samples: a track with no edit list, which the engine trims
9//! as an AAC-LC encoder delay (`audio.rs`, `DEFAULT_PRIMING`) and ffmpeg does
10//! not. Any other lag is a failure.
11//! * PCM16 WAV: every sample bit-equal to ffmpeg's (`s16 / 32768` is exact in
12//! float, so there is no rounding to excuse a difference), at lag 0.
13//!
14//! Named by `real_library.toml` (gitignored): `mp4_heaac`, `mp4_h264_aac`,
15//! `mp4_phone_h264`, `wav_pcm16`. Skips where the key is absent or ffmpeg is
16//! not installed.
17
18use crate::reallib;
19
20use std::io::Read;
21use std::path::Path;
22use std::process::Command;
23
24use engine::audio::AudioSession;
25use reallib::{ffmpeg_pipe, fill, have};
26
27/// The engine's documented priming for an AAC track with no edit list.
28const DEFAULT_PRIMING_LAG: i64 = 1024;
29
30/// Running sums for one channel's Pearson correlation.
31#[derive(Default, Clone, Copy)]
32struct Pearson {
33 n: f64,
34 sx: f64,
35 sy: f64,
36 sxx: f64,
37 syy: f64,
38 sxy: f64,
39}
40
41impl Pearson {
42 fn add(&mut self, x: f64, y: f64) {
43 self.n += 1.0;
44 self.sx += x;
45 self.sy += y;
46 self.sxx += x * x;
47 self.syy += y * y;
48 self.sxy += x * y;
49 }
50
51 fn r(&self) -> f64 {
52 let cov = self.n * self.sxy - self.sx * self.sy;
53 let vx = self.n * self.sxx - self.sx * self.sx;
54 let vy = self.n * self.syy - self.sy * self.sy;
55 cov / (vx * vy).sqrt()
56 }
57}
58
59/// What one comparison found.
60struct Witness {
61 /// Engine frame `i` lines up with ffmpeg frame `i + lag`.
62 lag: i64,
63 /// Per channel, at that lag.
64 r: Vec<f64>,
65 /// Frames the engine delivered, and frames ffmpeg decoded.
66 engine_frames: usize,
67 ffmpeg_frames: usize,
68 /// Engine samples not bit-equal to ffmpeg's, at that lag.
69 differing: usize,
70}
71
72/// The engine's first audio track, from the start, as interleaved f32.
73fn engine_head(path: &Path, seconds: f64) -> (u16, u32, Vec<f32>) {
74 let (meta, rx) = AudioSession::open_at(path, 0.0)
75 .expect("open")
76 .expect("the file has audio");
77 let want = (seconds * f64::from(meta.sample_rate) * f64::from(meta.channels)) as usize;
78 let mut out = Vec::with_capacity(want);
79 for chunk in rx {
80 out.extend_from_slice(&chunk.samples);
81 if out.len() >= want {
82 break;
83 }
84 }
85 (meta.channels, meta.sample_rate, out)
86}
87
88/// ffmpeg's first audio track over the first `seconds`, as interleaved f32.
89fn ffmpeg_head(path: &Path, channels: u16, rate: u32, seconds: f64) -> Vec<f32> {
90 let out = Command::new("ffmpeg")
91 .args(["-v", "error", "-nostdin", "-i"])
92 .arg(path)
93 .args([
94 "-map",
95 "0:a:0",
96 "-vn",
97 "-t",
98 &format!("{seconds}"),
99 "-f",
100 "f32le",
101 ])
102 .args(["-ar", &rate.to_string(), "-ac", &channels.to_string(), "-"])
103 .output()
104 .expect("run ffmpeg");
105 out.stdout
106 .as_chunks::<4>()
107 .0
108 .iter()
109 .map(|b| f32::from_le_bytes(*b))
110 .collect()
111}
112
113/// The lag in `-2048..=2048` (frames) at which the engine's head and ffmpeg's
114/// head correlate best on channel 0, with the correlation found there.
115fn best_lag(engine: &[f32], ffmpeg: &[f32], channels: usize) -> (i64, f64) {
116 let x: Vec<f64> = engine
117 .iter()
118 .step_by(channels)
119 .map(|v| f64::from(*v))
120 .collect();
121 let y: Vec<f64> = ffmpeg
122 .iter()
123 .step_by(channels)
124 .map(|v| f64::from(*v))
125 .collect();
126 let mut best = (0i64, f64::NEG_INFINITY);
127 for lag in -2048i64..=2048 {
128 let mut acc = Pearson::default();
129 for (i, a) in x.iter().enumerate() {
130 let j = i as i64 + lag;
131 if j >= 0 && (j as usize) < y.len() {
132 acc.add(*a, y[j as usize]);
133 }
134 }
135 if acc.n > 0.0 {
136 let r = acc.r();
137 if r > best.1 {
138 best = (lag, r);
139 }
140 }
141 }
142 best
143}
144
145/// Decodes the whole first audio track through the engine and through ffmpeg,
146/// at the lag the two line up at, and compares them frame by frame.
147fn compare(key: &str, path: &Path) -> Witness {
148 let (channels, rate, head) = engine_head(path, 2.0);
149 let reference = ffmpeg_head(path, channels, rate, 4.0);
150 let ch = usize::from(channels);
151 let (lag, score) = best_lag(&head, &reference, ch);
152 eprintln!("{key}: best alignment lag {lag} frames (correlation {score:.9})");
153
154 let (meta, rx) = AudioSession::open_at(path, 0.0)
155 .expect("open")
156 .expect("the file has audio");
157 assert_eq!((meta.channels, meta.sample_rate), (channels, rate));
158 // The engine is `lag` frames behind ffmpeg when `lag` is positive, so
159 // ffmpeg's first `lag` frames have no engine counterpart; a negative lag
160 // is the other way round.
161 let skip_engine = (-lag).max(0) as usize;
162 let skip_ffmpeg = lag.max(0) as usize;
163 let (mut child, mut ff) = ffmpeg_pipe(
164 &[
165 "-map",
166 "0:a:0",
167 "-vn",
168 "-f",
169 "f32le",
170 "-ar",
171 &rate.to_string(),
172 "-ac",
173 &channels.to_string(),
174 "-",
175 ],
176 path,
177 );
178 let mut discard = vec![0u8; 4 * skip_ffmpeg * ch];
179 fill(&mut ff, &mut discard);
180
181 let mut acc = vec![Pearson::default(); ch];
182 let (mut engine_frames, mut differing) = (0usize, 0usize);
183 let mut buf: Vec<u8> = Vec::new();
184 let mut expected_start = 0u64;
185 let mut to_skip = skip_engine * ch;
186 for chunk in rx {
187 assert_eq!(
188 chunk.start_sample, expected_start,
189 "{key}: engine chunks are not contiguous"
190 );
191 expected_start += (chunk.samples.len() / ch) as u64;
192 let samples = &chunk.samples[to_skip.min(chunk.samples.len())..];
193 to_skip -= (chunk.samples.len() - samples.len()).min(to_skip);
194 if samples.is_empty() {
195 continue;
196 }
197 buf.resize(samples.len() * 4, 0);
198 let got = fill(&mut ff, &mut buf);
199 let usable = got / 4;
200 for (i, s) in samples.iter().take(usable).enumerate() {
201 let r = f32::from_le_bytes(buf[4 * i..4 * i + 4].try_into().unwrap());
202 if s.to_bits() != r.to_bits() {
203 differing += 1;
204 }
205 acc[i % ch].add(f64::from(*s), f64::from(r));
206 }
207 engine_frames += usable / ch;
208 if usable < samples.len() {
209 break;
210 }
211 }
212 let mut rest = Vec::new();
213 ff.read_to_end(&mut rest).expect("drain ffmpeg");
214 let _ = child.wait();
215 let ffmpeg_frames = skip_ffmpeg + engine_frames + rest.len() / 4 / ch;
216 Witness {
217 lag,
218 r: acc.iter().map(Pearson::r).collect(),
219 engine_frames: engine_frames + skip_engine,
220 ffmpeg_frames,
221 differing,
222 }
223}
224
225/// The AAC claim, for one file: at lag 0, or at the engine's documented default
226/// priming, every channel correlates with ffmpeg at 0.999 or better.
227fn assert_aac(key: &str, path: &Path) {
228 let w = compare(key, path);
229 eprintln!(
230 "{key}: lag {} frames, per-channel correlation {:?}; {} engine vs {} ffmpeg frames",
231 w.lag, w.r, w.engine_frames, w.ffmpeg_frames
232 );
233 assert!(
234 w.lag == 0 || w.lag == DEFAULT_PRIMING_LAG,
235 "{key}: lag {} is neither 0 nor the engine's default priming",
236 w.lag
237 );
238 for (c, v) in w.r.iter().enumerate() {
239 assert!(
240 *v >= 0.999,
241 "{key} channel {c}: correlation {v} at lag {}",
242 w.lag
243 );
244 }
245}
246
247#[test]
248fn real_mp4_heaac_audio_correlates_with_ffmpeg() {
249 let Some(path) = engine::real_library::film("mp4_heaac") else {
250 return;
251 };
252 if !have("ffmpeg") {
253 eprintln!("skipped: no ffmpeg to decode the reference with");
254 return;
255 }
256 assert_aac("mp4_heaac (HE-AAC v1)", &path);
257}
258
259#[test]
260fn real_mp4_aac_lc_audio_correlates_with_ffmpeg() {
261 for key in ["mp4_h264_aac", "mp4_phone_h264"] {
262 let Some(path) = engine::real_library::film(key) else {
263 continue;
264 };
265 if !have("ffmpeg") {
266 eprintln!("skipped: no ffmpeg to decode the reference with");
267 return;
268 }
269 assert_aac(&format!("{key} (AAC-LC)"), &path);
270 }
271}
272
273#[test]
274fn real_wav_pcm16_is_sample_equal_to_ffmpeg() {
275 let Some(path) = engine::real_library::film("wav_pcm16") else {
276 return;
277 };
278 if !have("ffmpeg") {
279 eprintln!("skipped: no ffmpeg to decode the reference with");
280 return;
281 }
282 let w = compare("wav_pcm16", &path);
283 eprintln!(
284 "wav_pcm16: lag {}, {} engine vs {} ffmpeg frames, {} samples not bit-equal",
285 w.lag, w.engine_frames, w.ffmpeg_frames, w.differing
286 );
287 assert_eq!(w.lag, 0, "wav_pcm16: a WAV has no priming to trim");
288 assert_eq!(w.engine_frames, w.ffmpeg_frames, "wav_pcm16: frame count");
289 assert_eq!(w.differing, 0, "wav_pcm16: samples that differ from ffmpeg");
290}