forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_seek.rs422 lines, 16.8 KiBHistoryRawDownload
1//! `AudioSession::open_at` must produce exactly the tail of a full run: same
2//! samples, same absolute `start_sample` numbering, no gaps at the splice.
3
4use std::path::PathBuf;
5
6use engine::audio::{AudioChunk, AudioSession};
7
8const RATE: u32 = 44100;
9const CHANNELS: usize = 2;
10
11fn asset(name: &str) -> PathBuf {
12 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
13 .join("../../assets")
14 .join(name)
15}
16
17/// Drains a session into one flat interleaved buffer, checking as it goes that
18/// chunks are contiguous and that the first one lands on `want_start`.
19fn drain(start_secs: f64, want_start: u64) -> Vec<f32> {
20 let (meta, rx) = AudioSession::open_at(asset("test_av.mp4"), start_secs)
21 .expect("open")
22 .expect("test_av.mp4 has an audio track");
23 assert_eq!((meta.sample_rate, meta.channels as usize), (RATE, CHANNELS));
24
25 let mut samples = Vec::new();
26 let mut next = want_start;
27 for (
28 i,
29 AudioChunk {
30 start_sample,
31 samples: s,
32 },
33 ) in rx.into_iter().enumerate()
34 {
35 assert_eq!(start_sample, next, "chunk {i} start at {start_secs}s");
36 assert!(!s.is_empty(), "empty chunk {i} at {start_secs}s");
37 next += (s.len() / CHANNELS) as u64;
38 samples.extend(s);
39 }
40 samples
41}
42
43/// Largest per-sample difference, and where it is.
44fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) {
45 a.iter()
46 .zip(b)
47 .enumerate()
48 .map(|(i, (x, y))| ((x - y).abs(), i))
49 .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m })
50}
51
52#[test]
53fn open_at_zero_matches_open() {
54 let (mut full, mut at_zero) = (Vec::new(), Vec::new());
55 for chunk in AudioSession::open(asset("test_av.mp4")).unwrap().unwrap().1 {
56 full.extend(chunk.samples);
57 }
58 for chunk in AudioSession::open_at(asset("test_av.mp4"), 0.0)
59 .unwrap()
60 .unwrap()
61 .1
62 {
63 at_zero.extend(chunk.samples);
64 }
65 assert_eq!(full.len(), at_zero.len());
66 assert_eq!(full, at_zero, "open() must be open_at(0.0)");
67}
68
69#[test]
70fn open_at_two_seconds_is_the_tail_of_a_full_run() {
71 let full = drain(0.0, 0);
72 let target = 2 * RATE as u64;
73 let tail = drain(2.0, target);
74
75 let want = &full[target as usize * CHANNELS..];
76 assert_eq!(tail.len(), want.len(), "seeked run is a different length");
77 if tail == want {
78 eprintln!("bit-exact: {} samples", tail.len());
79 return;
80 }
81 // Not bit-exact, and it never will be: perceptual noise substitution draws
82 // from an LCG seeded once per decoder (symphonia-codec-aac cpe.rs:32,44), so
83 // a run that skipped 86 packets draws different noise in PNS bands forever.
84 // The MDCT overlap the pre-roll exists for *is* exact — the first packets
85 // after the splice match sample for sample.
86 let (diff, at) = max_diff(&tail, want);
87 eprintln!("max abs diff {diff:e} at sample {at} of {}", tail.len());
88 assert!(diff < 1e-3, "max abs diff {diff} at sample {at}");
89}
90
91#[test]
92fn open_at_mid_first_packet_is_exact() {
93 // 500 samples in: inside packet 1, before any pre-roll exists to walk back
94 // to, and it forces the drain-inside-a-chunk trim path.
95 let full = drain(0.0, 0);
96 let start = 500u64;
97 let tail = drain(start as f64 / RATE as f64, start);
98 let want = &full[start as usize * CHANNELS..];
99 assert_eq!(tail.len(), want.len());
100 assert_eq!(tail, want, "no decoder state to diverge from at packet 1");
101}
102
103#[test]
104fn open_at_past_duration_ends_clean() {
105 let tail = drain(60.0, 60 * RATE as u64);
106 assert!(
107 tail.is_empty(),
108 "{} samples past the end of a 5 s file",
109 tail.len()
110 );
111}
112
113/// The seek lands on the second it was asked for, in *content*, ten and twenty
114/// seconds into a file that has a cue table.
115///
116/// That is not what one symphonia seek gives on a Matroska file: it goes
117/// through the cues and lands on the first frame at or past the *cluster* the
118/// cue names, which on this fixture is up to 4.99 s later than the request
119/// (asking 25.0 s landed the reader at 29.987 s) and on a 5.1 Opus film was
120/// 1.47 s at 600 s and 3.39 s at 610 s. Nothing downstream can recover samples
121/// the reader is already past, so the film simply played from there while the
122/// timeline said otherwise -- sound against picture, after every scrub.
123///
124/// The chirp is what makes that measurable without a reference decode: 200 Hz
125/// rising 160 Hz a second, so the frequency of a quarter second of audio names
126/// the second of the file it was cut from.
127#[test]
128fn a_seek_into_a_cued_matroska_lands_on_its_own_second() {
129 for start in [5.0, 12.5, 25.0] {
130 let (meta, rx) = AudioSession::open_at(asset("test_seek_chirp.mkv"), start)
131 .expect("open")
132 .expect("test_seek_chirp.mkv has an audio track");
133 let at = chirp_second(&meta, rx.into_iter().flat_map(|c| c.samples));
134 assert!(
135 (at - start).abs() < 0.1,
136 "asked {start}s of the chirp, heard {at:.3}s"
137 );
138 }
139}
140
141/// ...and the *second* segment of one session lands too. Two clips of one file
142/// is two seeks on one reader, which is where symphonia's mkv reader gives up
143/// altogether: it hands out the frames left over from the first landing and
144/// then reads on from wherever its iterator ended up -- measured on a film as
145/// the second seek playing the *first cluster* of it, 0.094 s in, whatever it
146/// was asked for.
147#[test]
148fn the_second_segment_of_a_session_lands_too() {
149 let (meta, rx) =
150 AudioSession::open_segments(asset("test_seek_chirp.mkv"), &[(5.0, 6.0), (22.5, 23.5)])
151 .expect("open")
152 .expect("test_seek_chirp.mkv has an audio track");
153 let channels = usize::from(meta.channels);
154 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
155 let second = meta.sample_rate as usize * channels;
156 assert_eq!(samples.len(), 2 * second, "two one-second segments");
157 for (want, cut) in [(5.0, &samples[..second]), (22.5, &samples[second..])] {
158 let at = chirp_second(&meta, cut.iter().copied());
159 assert!(
160 (at - want).abs() < 0.1,
161 "segment from {want}s of the chirp came out as {at:.3}s"
162 );
163 }
164}
165
166/// Where in `test_seek_chirp.mkv` a stream of samples was cut from, by the
167/// frequency of its first quarter second: the chirp starts at 200 Hz and rises
168/// 160 Hz a second, and zero crossings date it without a reference decode.
169fn chirp_second(meta: &engine::audio::AudioMeta, samples: impl Iterator<Item = f32>) -> f64 {
170 const WINDOW: f64 = 0.25;
171 let channels = usize::from(meta.channels);
172 let want = (WINDOW * f64::from(meta.sample_rate)) as usize * channels;
173 let first: Vec<f32> = samples.take(want).step_by(channels).collect();
174 assert_eq!(first.len(), want / channels, "short of a window to date");
175 let crossings = first
176 .windows(2)
177 .filter(|p| (p[0] < 0.0) != (p[1] < 0.0))
178 .count();
179 // The window's *midpoint* is what its mean frequency dates.
180 (crossings as f64 / 2.0 / WINDOW - 200.0) / 160.0 - WINDOW / 2.0
181}
182
183/// A real film, which is where the desync was measured and where the fixture
184/// cannot follow: a 5 GB AV1 remux with a 5.1 Opus track and a cue table, seeked
185/// to three seconds spread across two hours and correlated against ffmpeg's
186/// decode of the same window.
187///
188/// The chirp fixture above proves the rule on 30 seconds of one cluster layout.
189/// This proves it where it broke: `fix(audio): a seek into a Matroska lands on
190/// the second it asked for` measured +1.473 s at 600 s and +3.394 s at 610 s on
191/// this file and left no runnable check behind it, so a regression would come
192/// back the way the original did -- through the ears, after a scrub.
193///
194/// Skipped, not failed, without the film or without ffmpeg: a claim about a
195/// library cannot be made by a machine that does not have it.
196#[test]
197fn a_seek_into_real_film_lands_on_the_second_it_asked_for() {
198 let Some(film) = engine::real_library::film("av1_opus_51") else {
199 return;
200 };
201 if std::process::Command::new("ffmpeg")
202 .arg("-version")
203 .stdout(std::process::Stdio::null())
204 .stderr(std::process::Stdio::null())
205 .status()
206 .is_err()
207 {
208 eprintln!("skipped: no ffmpeg to decode the reference window with");
209 return;
210 }
211 // Five seconds either side of the request: the landings this exists to catch
212 // were +1.5 and +3.4 s, and a narrow search is a search that cannot pick the
213 // wrong repeat of a phrase.
214 const SEARCH: f64 = 5.0;
215 for want in [600.0, 610.0, 3600.0] {
216 let (meta, rx) = AudioSession::open_at(&film, want)
217 .expect("open")
218 .expect("the film has audio");
219 let rate = f64::from(meta.sample_rate);
220 let channels = usize::from(meta.channels);
221 // One second of what came out, summed to mono: what is being located is
222 // the content, and a fold's channel balance is not part of that. Taken a
223 // chunk at a time and then dropped -- this window is open-ended, and
224 // draining it is decoding the rest of a two-hour film.
225 let mut probe: Vec<f32> = Vec::with_capacity(meta.sample_rate as usize);
226 for chunk in &rx {
227 probe.extend(
228 chunk
229 .samples
230 .chunks_exact(channels)
231 .map(|f| f.iter().sum::<f32>() / channels as f32),
232 );
233 if probe.len() >= meta.sample_rate as usize {
234 break;
235 }
236 }
237 drop(rx);
238 probe.truncate(meta.sample_rate as usize);
239 assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate");
240
241 let from = want - SEARCH;
242 let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate);
243 let (lag, score) = best_lag(&probe, &reference);
244 let at = from + lag as f64 / rate;
245 eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})");
246 assert!(
247 score > 0.5,
248 "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \
249 the measurement, not the seek, is what failed"
250 );
251 assert!(
252 (at - want).abs() <= 0.05,
253 "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture",
254 at - want
255 );
256 }
257}
258
259/// The 5.1 **AAC** film: the multichannel seat `ec-aac` took over from
260/// `rusty_aac`, exercised on the kind of track it exists for -- a BluRay
261/// remux's 48 kHz AAC-LC 5.1, decoded, folded to the pair the timeline
262/// carries, seeked across the film, and correlated against ffmpeg's own decode
263/// of the same window. A wrong channel order, a wrong rate, or a fold that
264/// lost a side all move the correlation; a seat that refuses the track fails
265/// the open.
266///
267/// Skipped, not failed, where the film or ffmpeg is not -- it is a 4K remux
268/// named by the local `real_library.toml`, not a fixture in this repository.
269#[test]
270fn a_seek_into_real_five_one_aac_film_lands_on_the_second_it_asked_for() {
271 let Some(film) = engine::real_library::film("hevc_4k_pgs") else {
272 return;
273 };
274 if std::process::Command::new("ffmpeg")
275 .arg("-version")
276 .stdout(std::process::Stdio::null())
277 .stderr(std::process::Stdio::null())
278 .status()
279 .map(|s| !s.success())
280 .unwrap_or(true)
281 {
282 eprintln!("skipped: no ffmpeg to decode the reference window with");
283 return;
284 }
285 const SEARCH: f64 = 5.0;
286 for want in [600.0, 2400.0, 5400.0] {
287 let (meta, rx) = AudioSession::open_at(&film, want)
288 .expect("open")
289 .expect("the film has audio");
290 assert_eq!(meta.sample_rate, 48_000);
291 assert_eq!(meta.channels, 2, "5.1 reaches the timeline as a pair");
292 let rate = f64::from(meta.sample_rate);
293 let channels = usize::from(meta.channels);
294 let mut probe: Vec<f32> = Vec::with_capacity(meta.sample_rate as usize);
295 for chunk in &rx {
296 probe.extend(
297 chunk
298 .samples
299 .chunks_exact(channels)
300 .map(|f| f.iter().sum::<f32>() / channels as f32),
301 );
302 if probe.len() >= meta.sample_rate as usize {
303 break;
304 }
305 }
306 drop(rx);
307 probe.truncate(meta.sample_rate as usize);
308 assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate");
309
310 let from = want - SEARCH;
311 let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate);
312 let (lag, score) = best_lag(&probe, &reference);
313 let at = from + lag as f64 / rate;
314 eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})");
315 assert!(
316 score > 0.5,
317 "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \
318 the measurement, not the seek, is what failed"
319 );
320 assert!(
321 (at - want).abs() <= 0.05,
322 "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture",
323 at - want
324 );
325 }
326}
327
328/// `dur` seconds of `path`'s first audio track from `start`, decoded by ffmpeg,
329/// summed to mono at `rate`. The reference this engine's own landing is measured
330/// against, because a decoder cannot be its own witness about where it landed.
331fn ffmpeg_mono(path: &std::path::Path, start: f64, dur: f64, rate: u32) -> Vec<f32> {
332 let out = std::process::Command::new("ffmpeg")
333 .args(["-v", "error", "-ss"])
334 .arg(format!("{start}"))
335 .arg("-t")
336 .arg(format!("{dur}"))
337 .arg("-i")
338 .arg(path)
339 .args(["-map", "0:a:0", "-ac", "1", "-ar"])
340 .arg(rate.to_string())
341 .args(["-f", "f32le", "-"])
342 .output()
343 .expect("ffmpeg runs");
344 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
345 out.stdout
346 .as_chunks::<4>().0.iter()
347 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
348 .collect()
349}
350
351/// Where in `reference` the `probe` sits, and how well: the offset in samples of
352/// the best normalised cross-correlation, which is 1.0 for the same content and
353/// falls away fast for anything else.
354///
355/// Coarse then fine, because the naive product over a ten-second window at
356/// 48 kHz is 3e10 multiplies: both signals are averaged down by [`DECIMATE`]
357/// first -- a crude low-pass, and the peak of a correlation is broad -- then the
358/// winner is refined at full rate over the one block around it. The normalisation
359/// is what makes the two comparable at all, since this fold is 7.7 dB quieter
360/// than ffmpeg's.
361fn best_lag(probe: &[f32], reference: &[f32]) -> (usize, f64) {
362 const DECIMATE: usize = 32;
363 let down = |xs: &[f32]| -> Vec<f64> {
364 xs.as_chunks::<DECIMATE>().0.iter()
365 .map(|c| c.iter().map(|s| f64::from(*s)).sum::<f64>() / DECIMATE as f64)
366 .collect()
367 };
368 let (coarse, at) = scan(&down(probe), &down(reference), 1);
369 let from = (at * DECIMATE).saturating_sub(DECIMATE);
370 let span = 3 * DECIMATE + probe.len();
371 // The score reported is the coarse one, over the whole search window: the
372 // fine pass only sharpens the offset inside a block it has already chosen,
373 // and a score over a window that short says nothing about the match.
374 let (_, offset) = scan(
375 &probe.iter().map(|s| f64::from(*s)).collect::<Vec<f64>>(),
376 &reference[from.min(reference.len())..(from + span).min(reference.len())]
377 .iter()
378 .map(|s| f64::from(*s))
379 .collect::<Vec<f64>>(),
380 1,
381 );
382 (from + offset, coarse)
383}
384
385/// The best normalised cross-correlation of `probe` over `reference`, at `step`
386/// samples: `(score, offset)`. Both are mean-removed; the denominator is each
387/// window's own energy, so a level difference between the two decoders cannot
388/// move the peak.
389fn scan(probe: &[f64], reference: &[f64], step: usize) -> (f64, usize) {
390 if reference.len() <= probe.len() || probe.is_empty() {
391 return (0.0, 0);
392 }
393 let mean = |xs: &[f64]| xs.iter().sum::<f64>() / xs.len() as f64;
394 let p: Vec<f64> = {
395 let m = mean(probe);
396 probe.iter().map(|s| s - m).collect()
397 };
398 let pe = p.iter().map(|s| s * s).sum::<f64>().sqrt();
399 if pe <= 0.0 {
400 return (0.0, 0);
401 }
402 let (mut best, mut at) = (0.0, 0);
403 for offset in (0..reference.len() - p.len()).step_by(step) {
404 let window = &reference[offset..offset + p.len()];
405 let m = mean(window);
406 let (mut dot, mut energy) = (0.0, 0.0);
407 for (a, b) in p.iter().zip(window) {
408 let b = b - m;
409 dot += a * b;
410 energy += b * b;
411 }
412 let score = match energy > 0.0 {
413 true => dot / (pe * energy.sqrt()),
414 false => 0.0,
415 };
416 if score > best {
417 best = score;
418 at = offset;
419 }
420 }
421 (best, at)
422}