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