| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::process::Command; |
| 18 | |
| 19 | use ec_ac3::{Ac3Decoder, Options}; |
| 20 | use crate::common::have_ffmpeg; |
| 21 | |
| 22 | const MIN_CORR: f64 = 0.999; |
| 23 | |
| 24 | const SILENT_RMS: f64 = 1e-4; |
| 25 | |
| 26 | const SILENT_DELTA: f64 = 1e-6; |
| 27 | |
| 28 | fn library_toml() -> PathBuf { |
| 29 | if let Ok(p) = std::env::var("EC_REAL_LIBRARY") { |
| 30 | return PathBuf::from(p); |
| 31 | } |
| 32 | let home = std::env::var("HOME").unwrap_or_default(); |
| 33 | PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml") |
| 34 | } |
| 35 | |
| 36 | |
| 37 | |
| 38 | fn entries(toml: &Path) -> Vec<(String, PathBuf)> { |
| 39 | let Ok(text) = std::fs::read_to_string(toml) else { |
| 40 | return Vec::new(); |
| 41 | }; |
| 42 | text.lines() |
| 43 | .filter_map(|line| { |
| 44 | let line = line.trim(); |
| 45 | if line.starts_with('#') { |
| 46 | return None; |
| 47 | } |
| 48 | let (key, value) = line.split_once('=')?; |
| 49 | let value = value.trim().strip_prefix('"')?.strip_suffix('"')?; |
| 50 | Some((key.trim().to_string(), PathBuf::from(value))) |
| 51 | }) |
| 52 | .collect() |
| 53 | } |
| 54 | |
| 55 | |
| 56 | fn first_audio(path: &Path) -> Option<(String, usize)> { |
| 57 | let out = Command::new("ffprobe") |
| 58 | .args([ |
| 59 | "-v", |
| 60 | "error", |
| 61 | "-select_streams", |
| 62 | "a:0", |
| 63 | "-show_entries", |
| 64 | "stream=codec_name,channels", |
| 65 | "-of", |
| 66 | "csv=p=0", |
| 67 | ]) |
| 68 | .arg(path) |
| 69 | .output() |
| 70 | .ok()?; |
| 71 | let text = String::from_utf8_lossy(&out.stdout); |
| 72 | let mut parts = text.trim().split(','); |
| 73 | Some((parts.next()?.to_string(), parts.next()?.parse().ok()?)) |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | fn extract(path: &Path, codec: &str, seconds: u32, out: &Path) -> bool { |
| 79 | let muxer = if codec == "eac3" { "eac3" } else { "ac3" }; |
| 80 | Command::new("ffmpeg") |
| 81 | .args(["-v", "error", "-nostdin", "-y", "-i"]) |
| 82 | .arg(path) |
| 83 | .args(["-map", "0:a:0", "-t", &seconds.to_string(), "-c", "copy", "-f", muxer]) |
| 84 | .arg(out) |
| 85 | .status() |
| 86 | .map(|s| s.success()) |
| 87 | .unwrap_or(false) |
| 88 | } |
| 89 | |
| 90 | |
| 91 | fn reference(path: &Path) -> Vec<f32> { |
| 92 | let out = Command::new("ffmpeg") |
| 93 | .args(["-v", "error", "-nostdin", "-i"]) |
| 94 | .arg(path) |
| 95 | .args(["-f", "f32le", "-"]) |
| 96 | .output() |
| 97 | .expect("ffmpeg"); |
| 98 | out.stdout |
| 99 | .as_chunks::<4>() |
| 100 | .0 |
| 101 | .iter() |
| 102 | .map(|c| f32::from_le_bytes(*c)) |
| 103 | .collect() |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | fn decode(path: &Path) -> (Vec<f32>, usize) { |
| 109 | let data = std::fs::read(path).expect("extracted stream"); |
| 110 | let options = Options { |
| 111 | dither: false, |
| 112 | ..Options::default() |
| 113 | }; |
| 114 | let mut decoder = Ac3Decoder::with_options(options); |
| 115 | let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize); |
| 116 | while pos + 6 <= data.len() { |
| 117 | if data[pos] != 0x0B || data[pos + 1] != 0x77 { |
| 118 | pos += 1; |
| 119 | continue; |
| 120 | } |
| 121 | let Ok(size) = ec_ac3::frame_size(&data[pos..]) else { |
| 122 | break; |
| 123 | }; |
| 124 | if pos + size > data.len() { |
| 125 | break; |
| 126 | } |
| 127 | let frame = decoder |
| 128 | .decode_frame(&data[pos..pos + size]) |
| 129 | .unwrap_or_else(|e| panic!("{}: {e}", path.display())); |
| 130 | channels = frame.channels(); |
| 131 | out.extend( |
| 132 | frame |
| 133 | .data[0] |
| 134 | .as_chunks::<4>() |
| 135 | .0 |
| 136 | .iter() |
| 137 | .map(|c| f32::from_le_bytes(*c)), |
| 138 | ); |
| 139 | pos += size; |
| 140 | } |
| 141 | (out, channels) |
| 142 | } |
| 143 | |
| 144 | |
| 145 | fn compare(a: &[f32], b: &[f32]) -> (f64, f64, usize, usize) { |
| 146 | let n = a.len().min(b.len()); |
| 147 | let (mut sa, mut sb, mut saa, mut sbb, mut sab, mut sd) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); |
| 148 | let mut exact = 0; |
| 149 | for i in 0..n { |
| 150 | let (x, y) = (f64::from(a[i]), f64::from(b[i])); |
| 151 | if a[i] == b[i] { |
| 152 | exact += 1; |
| 153 | } |
| 154 | sa += x; |
| 155 | sb += y; |
| 156 | saa += x * x; |
| 157 | sbb += y * y; |
| 158 | sab += x * y; |
| 159 | sd += (x - y) * (x - y); |
| 160 | } |
| 161 | let nf = n.max(1) as f64; |
| 162 | let cov = sab / nf - (sa / nf) * (sb / nf); |
| 163 | let va = saa / nf - (sa / nf).powi(2); |
| 164 | let vb = sbb / nf - (sb / nf).powi(2); |
| 165 | let corr = if va <= 0.0 || vb <= 0.0 { |
| 166 | 1.0 |
| 167 | } else { |
| 168 | cov / (va * vb).sqrt() |
| 169 | }; |
| 170 | (corr, (sd / nf).sqrt(), exact, n) |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn real_library_ac3_and_eac3_match_ffmpeg() { |
| 175 | if !have_ffmpeg() { |
| 176 | eprintln!("skip: ffmpeg not on PATH"); |
| 177 | return; |
| 178 | } |
| 179 | let toml = library_toml(); |
| 180 | let seconds: u32 = std::env::var("EC_REAL_SECONDS") |
| 181 | .ok() |
| 182 | .and_then(|s| s.parse().ok()) |
| 183 | .unwrap_or(20); |
| 184 | let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("real-library-ac3"); |
| 185 | std::fs::create_dir_all(&work).expect("work dir"); |
| 186 | |
| 187 | let mut checked = 0; |
| 188 | for (key, path) in entries(&toml) { |
| 189 | if !path.exists() { |
| 190 | eprintln!("skip {key}: {} not on disk", path.display()); |
| 191 | continue; |
| 192 | } |
| 193 | let Some((codec, channels)) = first_audio(&path) else { |
| 194 | eprintln!("skip {key}: ffprobe found no audio track"); |
| 195 | continue; |
| 196 | }; |
| 197 | if codec != "ac3" && codec != "eac3" { |
| 198 | eprintln!("skip {key}: first audio track is {codec}, not AC-3 or E-AC-3"); |
| 199 | continue; |
| 200 | } |
| 201 | let raw = work.join(format!("{key}.{codec}")); |
| 202 | assert!(extract(&path, &codec, seconds, &raw), "{key}: extract failed"); |
| 203 | |
| 204 | let (ours, decoded_channels) = decode(&raw); |
| 205 | let theirs = reference(&raw); |
| 206 | assert_eq!(decoded_channels, channels, "{key}: channel count"); |
| 207 | assert_eq!(ours.len(), theirs.len(), "{key}: sample count vs ffmpeg"); |
| 208 | assert!(!ours.is_empty(), "{key}: nothing decoded"); |
| 209 | |
| 210 | let mut worst = 1.0f64; |
| 211 | let mut worst_rms = 0.0f64; |
| 212 | let mut exact_total = 0; |
| 213 | let mut total = 0; |
| 214 | for ch in 0..decoded_channels { |
| 215 | let a: Vec<f32> = ours[ch..].iter().step_by(decoded_channels).copied().collect(); |
| 216 | let b: Vec<f32> = theirs[ch..].iter().step_by(decoded_channels).copied().collect(); |
| 217 | let (corr, rms, exact, n) = compare(&a, &b); |
| 218 | eprintln!("{key} {codec} ch{ch}: corr {corr:.6} rms {rms:.3e} exact {exact}/{n}"); |
| 219 | |
| 220 | |
| 221 | |
| 222 | let ref_rms = (b.iter().map(|y| f64::from(*y).powi(2)).sum::<f64>() |
| 223 | / b.len().max(1) as f64) |
| 224 | .sqrt(); |
| 225 | if ref_rms < SILENT_RMS { |
| 226 | assert!(rms <= SILENT_DELTA, "{key} ch{ch}: silent-channel RMS delta {rms:.3e}"); |
| 227 | } else { |
| 228 | assert!(corr >= MIN_CORR, "{key} ch{ch}: correlation {corr:.6}"); |
| 229 | } |
| 230 | worst = worst.min(corr); |
| 231 | worst_rms = worst_rms.max(rms); |
| 232 | exact_total += exact; |
| 233 | total += n; |
| 234 | } |
| 235 | eprintln!( |
| 236 | "RESULT {key} {codec} {decoded_channels}ch {seconds}s: min corr {worst:.6}, max rms {worst_rms:.3e}, exact {:.4}%", |
| 237 | 100.0 * exact_total as f64 / total.max(1) as f64 |
| 238 | ); |
| 239 | checked += 1; |
| 240 | } |
| 241 | eprintln!("{checked} real-library AC-3/E-AC-3 entries checked"); |
| 242 | } |