| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::fs::File; |
| 9 | use std::io::BufReader; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | |
| 13 | use ec_core::{CodecId, Demuxer}; |
| 14 | use ec_matroska::MatroskaDemuxer; |
| 15 | use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length}; |
| 16 | |
| 17 | fn find_file() -> Option<PathBuf> { |
| 18 | fn walk(dir: &Path, out: &mut Vec<PathBuf>) { |
| 19 | let Ok(entries) = std::fs::read_dir(dir) else { |
| 20 | return; |
| 21 | }; |
| 22 | for e in entries.flatten() { |
| 23 | let p = e.path(); |
| 24 | if p.is_dir() { |
| 25 | walk(&p, out); |
| 26 | } else { |
| 27 | out.push(p); |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | let home = std::env::var("HOME").ok()?; |
| 32 | let mut all = Vec::new(); |
| 33 | walk(&PathBuf::from(home).join("Downloads"), &mut all); |
| 34 | all.into_iter().find(|p| { |
| 35 | p.file_name() |
| 36 | .and_then(|n| n.to_str()) |
| 37 | .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv")) |
| 38 | }) |
| 39 | } |
| 40 | |
| 41 | fn have_ffmpeg() -> bool { |
| 42 | Command::new("ffmpeg") |
| 43 | .arg("-version") |
| 44 | .output() |
| 45 | .map(|o| o.status.success()) |
| 46 | .unwrap_or(false) |
| 47 | } |
| 48 | |
| 49 | fn ffmpeg(args: &[&str]) -> Vec<u8> { |
| 50 | let out = Command::new("ffmpeg") |
| 51 | .args(["-v", "error", "-nostdin"]) |
| 52 | .args(args) |
| 53 | .output() |
| 54 | .expect("run ffmpeg"); |
| 55 | assert!( |
| 56 | out.status.success(), |
| 57 | "ffmpeg {args:?}: {}", |
| 58 | String::from_utf8_lossy(&out.stderr) |
| 59 | ); |
| 60 | out.stdout |
| 61 | } |
| 62 | |
| 63 | fn s32le(bytes: &[u8]) -> Vec<i32> { |
| 64 | bytes |
| 65 | .chunks_exact(4) |
| 66 | .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 67 | .collect() |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option<usize>) { |
| 73 | let n = ours.len().min(reference.len()); |
| 74 | let mut exact = 0; |
| 75 | let mut first = None; |
| 76 | for i in 0..n { |
| 77 | if ours[i] == reference[i] { |
| 78 | exact += 1; |
| 79 | } else if first.is_none() { |
| 80 | first = Some(i); |
| 81 | } |
| 82 | } |
| 83 | (exact, n, first) |
| 84 | } |
| 85 | |
| 86 | #[test] |
| 87 | fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { |
| 88 | let Some(path) = find_file() else { |
| 89 | eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); |
| 90 | return; |
| 91 | }; |
| 92 | if !have_ffmpeg() { |
| 93 | eprintln!("skip: ffmpeg not on PATH"); |
| 94 | return; |
| 95 | } |
| 96 | const SECONDS: usize = 60; |
| 97 | let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); |
| 98 | let track = demux |
| 99 | .streams() |
| 100 | .iter() |
| 101 | .find(|s| s.params.codec == CodecId::TrueHd) |
| 102 | .expect("a TrueHD track"); |
| 103 | let stream_index = track.index; |
| 104 | |
| 105 | let reference = s32le(&ffmpeg(&[ |
| 106 | "-i", |
| 107 | path.to_str().unwrap(), |
| 108 | "-map", |
| 109 | &format!("0:{stream_index}"), |
| 110 | "-t", |
| 111 | &SECONDS.to_string(), |
| 112 | "-f", |
| 113 | "s32le", |
| 114 | "-", |
| 115 | ])); |
| 116 | let channels = 8; |
| 117 | let wanted = SECONDS * 48_000 * channels; |
| 118 | |
| 119 | let mut decoder = TrueHdDecoder::new(); |
| 120 | let mut ours: Vec<i32> = Vec::with_capacity(wanted); |
| 121 | let mut aus = 0; |
| 122 | while ours.len() < wanted { |
| 123 | let packet = match demux.next_packet() { |
| 124 | Ok(p) => p, |
| 125 | Err(e) if e.is_eof() => break, |
| 126 | Err(e) => panic!("demux: {e}"), |
| 127 | }; |
| 128 | if packet.stream != stream_index { |
| 129 | continue; |
| 130 | } |
| 131 | let frame = decoder |
| 132 | .decode_access_unit(&packet.data) |
| 133 | .unwrap_or_else(|e| panic!("AU {aus}: {e}")); |
| 134 | aus += 1; |
| 135 | if let Some(f) = frame { |
| 136 | assert_eq!(f.channels(), channels); |
| 137 | ours.extend(s32le(&f.data[0])); |
| 138 | } |
| 139 | } |
| 140 | let (exact, total, first) = compare(&ours, &reference); |
| 141 | let stats = decoder.check_stats(); |
| 142 | for ch in 0..channels { |
| 143 | let n = total / channels; |
| 144 | let e = (0..n) |
| 145 | .filter(|&i| ours[i * channels + ch] == reference[i * channels + ch]) |
| 146 | .count(); |
| 147 | eprintln!("channel {ch}: {e}/{n} exact"); |
| 148 | } |
| 149 | eprintln!( |
| 150 | "{aus} access units, {total} samples compared ({} s), {exact} exact ({:.4}%), first mismatch {first:?}, {stats:?}", |
| 151 | total / channels / 48_000, |
| 152 | 100.0 * exact as f64 / total as f64 |
| 153 | ); |
| 154 | assert!( |
| 155 | total >= (SECONDS - 1) * 48_000 * channels, |
| 156 | "only {total} samples" |
| 157 | ); |
| 158 | assert_eq!(stats.lossless_check_failures, 0, "{stats:?}"); |
| 159 | assert_eq!(stats.parity_failures, 0, "{stats:?}"); |
| 160 | assert_eq!(stats.restart_crc_failures, 0, "{stats:?}"); |
| 161 | assert_eq!(stats.length_mismatches, 0, "{stats:?}"); |
| 162 | assert!( |
| 163 | exact as f64 >= 0.9999 * total as f64, |
| 164 | "{exact}/{total} exact, first mismatch {first:?}" |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | #[test] |
| 172 | fn externally_encoded_mlp_round_trips_bit_exact() { |
| 173 | if !have_ffmpeg() { |
| 174 | eprintln!("skip: ffmpeg not on PATH"); |
| 175 | return; |
| 176 | } |
| 177 | let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id())); |
| 178 | std::fs::create_dir_all(&dir).unwrap(); |
| 179 | let mut failures = Vec::new(); |
| 180 | for (codec, layout, channels) in [ |
| 181 | ("mlp", "mono", 1usize), |
| 182 | ("mlp", "stereo", 2), |
| 183 | ("mlp", "5.1", 6), |
| 184 | ("truehd", "mono", 1), |
| 185 | ("truehd", "stereo", 2), |
| 186 | ("truehd", "5.1", 6), |
| 187 | ] { |
| 188 | let name = format!("{codec}-{layout}"); |
| 189 | let mlp = dir.join(format!( |
| 190 | "{name}.{}", |
| 191 | if codec == "mlp" { "mlp" } else { "thd" } |
| 192 | )); |
| 193 | let src = format!( |
| 194 | "anoisesrc=color=pink:amplitude=0.3:seed=7:sample_rate=48000:duration=3,aformat=sample_fmts=s32:channel_layouts={layout}" |
| 195 | ); |
| 196 | ffmpeg(&[ |
| 197 | "-y", |
| 198 | "-f", |
| 199 | "lavfi", |
| 200 | "-i", |
| 201 | &src, |
| 202 | "-c:a", |
| 203 | codec, |
| 204 | "-strict", |
| 205 | "-2", |
| 206 | mlp.to_str().unwrap(), |
| 207 | ]); |
| 208 | let reference = s32le(&ffmpeg(&["-i", mlp.to_str().unwrap(), "-f", "s32le", "-"])); |
| 209 | let data = std::fs::read(&mlp).unwrap(); |
| 210 | |
| 211 | let mut decoder = TrueHdDecoder::new(); |
| 212 | let mut ours = Vec::new(); |
| 213 | let mut pos = 0; |
| 214 | while pos < data.len() { |
| 215 | let len = frame_length(&data[pos..]).unwrap(); |
| 216 | if let Some(f) = decoder.decode_access_unit(&data[pos..pos + len]).unwrap() { |
| 217 | assert_eq!(f.channels(), channels); |
| 218 | ours.extend(s32le(&f.data[0])); |
| 219 | } |
| 220 | pos += len; |
| 221 | } |
| 222 | let (exact, total, first) = compare(&ours, &reference); |
| 223 | let stats = decoder.check_stats(); |
| 224 | eprintln!( |
| 225 | "{name}: {exact}/{total} exact (ours {}, reference {}), first mismatch {first:?}, {stats:?}", |
| 226 | ours.len(), |
| 227 | reference.len() |
| 228 | ); |
| 229 | if stats.lossless_check_failures + stats.parity_failures + stats.restart_crc_failures != 0 |
| 230 | || exact != total |
| 231 | || total < 2 * 48_000 * channels |
| 232 | { |
| 233 | failures.push(format!( |
| 234 | "{name}: {exact}/{total}, first mismatch {first:?}, {stats:?}" |
| 235 | )); |
| 236 | } |
| 237 | } |
| 238 | let _ = std::fs::remove_dir_all(&dir); |
| 239 | assert!(failures.is_empty(), "{failures:#?}"); |
| 240 | } |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | #[test] |
| 249 | fn ffmpeg_decodes_our_encoder_bit_exact() { |
| 250 | if !have_ffmpeg() { |
| 251 | eprintln!("ffmpeg not found, skipping"); |
| 252 | return; |
| 253 | } |
| 254 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; |
| 255 | use ec_core::packet::Buf; |
| 256 | use ec_core::registry::Encoder; |
| 257 | |
| 258 | let n = 48_000usize; |
| 259 | let mut samples = Vec::with_capacity(n * 2); |
| 260 | let mut lcg: u32 = 0xC0FF_EE00; |
| 261 | for i in 0..n { |
| 262 | let l = ((i as f64 * 440.0 * std::f64::consts::TAU / 48_000.0).sin() * 3_000_000.0) as i32; |
| 263 | lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); |
| 264 | let r = l.wrapping_add((lcg >> 8) as i32 % 20_000 - 10_000); |
| 265 | samples.push(l.clamp(-8_388_608, 8_388_607)); |
| 266 | samples.push(r.clamp(-8_388_608, 8_388_607)); |
| 267 | } |
| 268 | let mut bytes = Vec::with_capacity(samples.len() * 4); |
| 269 | for &s in &samples { |
| 270 | bytes.extend_from_slice(&(s << 8).to_le_bytes()); |
| 271 | } |
| 272 | let reference = s32le(&bytes); |
| 273 | let frame = AudioFrame::try_new( |
| 274 | SampleFormat::S32, |
| 275 | false, |
| 276 | ChannelLayout::Stereo, |
| 277 | 48_000, |
| 278 | n, |
| 279 | vec![Buf::from_vec(bytes)], |
| 280 | ) |
| 281 | .unwrap(); |
| 282 | |
| 283 | let mut enc = TrueHdEncoder::new(48_000).unwrap(); |
| 284 | enc.send_frame(&Frame::Audio(frame)).unwrap(); |
| 285 | enc.flush().unwrap(); |
| 286 | let mut thd = Vec::new(); |
| 287 | while let Ok(pkt) = enc.receive_packet() { |
| 288 | thd.extend_from_slice(&pkt.data); |
| 289 | } |
| 290 | |
| 291 | let dir = std::env::temp_dir().join(format!("ec-truehd-enc-oracle-{}", std::process::id())); |
| 292 | std::fs::create_dir_all(&dir).unwrap(); |
| 293 | let path = dir.join("ours.thd"); |
| 294 | std::fs::write(&path, &thd).unwrap(); |
| 295 | let out = ffmpeg(&[ |
| 296 | "-f", |
| 297 | "truehd", |
| 298 | "-i", |
| 299 | path.to_str().unwrap(), |
| 300 | "-f", |
| 301 | "s32le", |
| 302 | "-", |
| 303 | ]); |
| 304 | let _ = std::fs::remove_dir_all(&dir); |
| 305 | |
| 306 | let decoded = s32le(&out); |
| 307 | let (exact, total, first) = compare(&decoded, &reference); |
| 308 | assert_eq!( |
| 309 | exact, total, |
| 310 | "ffmpeg vs our own PCM: first mismatch {first:?} of {total}" |
| 311 | ); |
| 312 | } |