| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | use crate::reallib; |
| 19 | |
| 20 | use std::io::Read; |
| 21 | use std::path::Path; |
| 22 | use std::process::Command; |
| 23 | |
| 24 | use engine::audio::AudioSession; |
| 25 | use reallib::{ffmpeg_pipe, fill, have}; |
| 26 | |
| 27 | |
| 28 | const DEFAULT_PRIMING_LAG: i64 = 1024; |
| 29 | |
| 30 | |
| 31 | #[derive(Default, Clone, Copy)] |
| 32 | struct Pearson { |
| 33 | n: f64, |
| 34 | sx: f64, |
| 35 | sy: f64, |
| 36 | sxx: f64, |
| 37 | syy: f64, |
| 38 | sxy: f64, |
| 39 | } |
| 40 | |
| 41 | impl 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 | |
| 60 | struct Witness { |
| 61 | |
| 62 | lag: i64, |
| 63 | |
| 64 | r: Vec<f64>, |
| 65 | |
| 66 | engine_frames: usize, |
| 67 | ffmpeg_frames: usize, |
| 68 | |
| 69 | differing: usize, |
| 70 | } |
| 71 | |
| 72 | |
| 73 | fn 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 | |
| 89 | fn 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 | |
| 114 | |
| 115 | fn 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 | |
| 146 | |
| 147 | fn 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 | |
| 159 | |
| 160 | |
| 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 | |
| 226 | |
| 227 | fn 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] |
| 248 | fn 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] |
| 260 | fn 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] |
| 274 | fn 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 | } |