| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::process::Command; |
| 16 | use std::time::{Duration, Instant}; |
| 17 | |
| 18 | use engine::PlaybackSession; |
| 19 | use engine::export::{ExportSettings, Format, ProResProfile}; |
| 20 | |
| 21 | use crate::seat; |
| 22 | |
| 23 | const WIDTH: u32 = 320; |
| 24 | const HEIGHT: u32 = 240; |
| 25 | const FPS: u32 = 25; |
| 26 | const SECONDS: u32 = 2; |
| 27 | |
| 28 | fn scratch(name: &str) -> PathBuf { |
| 29 | let dir = std::env::temp_dir().join(format!("edith-{name}-{}", std::process::id())); |
| 30 | let _ = std::fs::remove_dir_all(&dir); |
| 31 | std::fs::create_dir_all(&dir).expect("scratch directory"); |
| 32 | dir |
| 33 | } |
| 34 | |
| 35 | fn have(tool: &str) -> bool { |
| 36 | Command::new(tool).arg("-version").output().is_ok_and(|o| o.status.success()) |
| 37 | } |
| 38 | |
| 39 | fn tools() -> bool { |
| 40 | have("ffmpeg") && have("ffprobe") |
| 41 | } |
| 42 | |
| 43 | |
| 44 | fn make_source(out: &Path, width: u32, height: u32, seconds: u32) { |
| 45 | let status = Command::new("ffmpeg") |
| 46 | .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) |
| 47 | .arg(format!("testsrc2=size={width}x{height}:rate={FPS}:duration={seconds}")) |
| 48 | .args(["-f", "lavfi", "-i"]) |
| 49 | .arg(format!("sine=frequency=440:sample_rate=48000:duration={seconds}")) |
| 50 | .args(["-c:v", "libx264", "-preset", "ultrafast", "-crf", "10", "-pix_fmt", "yuv420p"]) |
| 51 | .args(["-c:a", "aac", "-b:a", "192k", "-shortest"]) |
| 52 | .arg(out) |
| 53 | .status() |
| 54 | .expect("ffmpeg runs"); |
| 55 | assert!(status.success(), "ffmpeg makes the source"); |
| 56 | } |
| 57 | |
| 58 | |
| 59 | fn probe(path: &Path, stream: &str, field: &str) -> String { |
| 60 | let out = Command::new("ffprobe") |
| 61 | .args(["-v", "error", "-select_streams", stream, "-show_entries"]) |
| 62 | .arg(format!("stream={field}")) |
| 63 | .args(["-of", "csv=p=0"]) |
| 64 | .arg(path) |
| 65 | .output() |
| 66 | .expect("ffprobe runs"); |
| 67 | assert!(out.status.success(), "ffprobe reads {}", path.display()); |
| 68 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 69 | } |
| 70 | |
| 71 | fn frame_count(path: &Path) -> usize { |
| 72 | let out = Command::new("ffprobe") |
| 73 | .args(["-v", "error", "-count_frames", "-select_streams", "v:0"]) |
| 74 | .args(["-show_entries", "stream=nb_read_frames", "-of", "csv=p=0"]) |
| 75 | .arg(path) |
| 76 | .output() |
| 77 | .expect("ffprobe runs"); |
| 78 | String::from_utf8_lossy(&out.stdout).trim().parse().expect("a frame count") |
| 79 | } |
| 80 | |
| 81 | fn format_duration(path: &Path) -> f64 { |
| 82 | let out = Command::new("ffprobe") |
| 83 | .args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"]) |
| 84 | .arg(path) |
| 85 | .output() |
| 86 | .expect("ffprobe runs"); |
| 87 | String::from_utf8_lossy(&out.stdout).trim().parse().expect("a duration") |
| 88 | } |
| 89 | |
| 90 | fn decoded_video(path: &Path, pix_fmt: &str) -> Vec<u8> { |
| 91 | let out = Command::new("ffmpeg") |
| 92 | .args(["-v", "error", "-i"]) |
| 93 | .arg(path) |
| 94 | .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"]) |
| 95 | .output() |
| 96 | .expect("ffmpeg runs"); |
| 97 | assert!(out.status.success(), "ffmpeg decodes {}: {}", path.display(), String::from_utf8_lossy(&out.stderr)); |
| 98 | out.stdout |
| 99 | } |
| 100 | |
| 101 | fn decoded_audio(path: &Path) -> Vec<i16> { |
| 102 | let out = Command::new("ffmpeg") |
| 103 | .args(["-v", "error", "-i"]) |
| 104 | .arg(path) |
| 105 | .args(["-vn", "-ac", "1", "-ar", "48000", "-f", "s16le", "-"]) |
| 106 | .output() |
| 107 | .expect("ffmpeg runs"); |
| 108 | assert!(out.status.success(), "ffmpeg decodes the sound of {}", path.display()); |
| 109 | out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() |
| 110 | } |
| 111 | |
| 112 | fn psnr_10(a: &[u8], b: &[u8]) -> f64 { |
| 113 | assert_eq!(a.len(), b.len(), "the same number of samples"); |
| 114 | let mut squared = 0f64; |
| 115 | for (x, y) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) { |
| 116 | let d = f64::from(u16::from_le_bytes(*x)) - f64::from(u16::from_le_bytes(*y)); |
| 117 | squared += d * d; |
| 118 | } |
| 119 | if squared == 0.0 { |
| 120 | return f64::INFINITY; |
| 121 | } |
| 122 | 10.0 * (1023.0f64 * 1023.0 * (a.len() / 2) as f64 / squared).log10() |
| 123 | } |
| 124 | |
| 125 | fn export(source: &Path, out: &Path, settings: &ExportSettings) { |
| 126 | let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display())); |
| 127 | let handle = session.export_to_with(out, settings); |
| 128 | let started = Instant::now(); |
| 129 | while !handle.is_finished() { |
| 130 | assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); |
| 131 | std::thread::sleep(Duration::from_millis(20)); |
| 132 | } |
| 133 | handle.result().expect("an outcome").expect("the export"); |
| 134 | } |
| 135 | |
| 136 | #[test] |
| 137 | fn every_profile_exports_a_prores_mov_that_decodes_back() { |
| 138 | if !tools() { |
| 139 | eprintln!("no ffmpeg/ffprobe: skipping the ProRes export test"); |
| 140 | return; |
| 141 | } |
| 142 | let _seat = seat::software(); |
| 143 | let dir = scratch("prores"); |
| 144 | let source = dir.join("source.mp4"); |
| 145 | make_source(&source, WIDTH, HEIGHT, SECONDS); |
| 146 | let reference_y = decoded_video(&source, "gray10le"); |
| 147 | let reference_420 = decoded_video(&source, "yuv420p10le"); |
| 148 | let source_audio = decoded_audio(&source); |
| 149 | let frames = (FPS * SECONDS) as usize; |
| 150 | |
| 151 | assert_eq!(Format::ProRes.ext(), "mov"); |
| 152 | |
| 153 | let table = [ |
| 154 | (ProResProfile::Proxy, "Proxy", "yuv422p10le", 32.0, 30.0), |
| 155 | (ProResProfile::Lt, "LT", "yuv422p10le", 36.0, 33.0), |
| 156 | (ProResProfile::Standard, "Standard", "yuv422p10le", 38.0, 35.0), |
| 157 | (ProResProfile::Hq, "HQ", "yuv422p10le", 40.0, 36.0), |
| 158 | |
| 159 | |
| 160 | (ProResProfile::P4444, "4444", "yuv444p12le", 40.0, 33.0), |
| 161 | (ProResProfile::P4444Xq, "XQ", "yuv444p12le", 40.0, 33.0), |
| 162 | ]; |
| 163 | for (profile, name, pix_fmt, luma_floor, all_floor) in table { |
| 164 | let out = dir.join(format!("{}.mov", name.replace(' ', "_"))); |
| 165 | let settings = ExportSettings { format: Format::ProRes, prores_profile: profile, ..Default::default() }; |
| 166 | export(&source, &out, &settings); |
| 167 | |
| 168 | assert_eq!(probe(&out, "v:0", "codec_name"), "prores", "{name}"); |
| 169 | assert_eq!(probe(&out, "v:0", "profile"), name, "{name}: the profile"); |
| 170 | assert_eq!(probe(&out, "v:0", "pix_fmt"), pix_fmt, "{name}: the pixel format"); |
| 171 | assert_eq!(probe(&out, "a:0", "codec_name"), "pcm_s24be", "{name}: the sound is 24-bit PCM"); |
| 172 | assert_eq!(probe(&out, "a:0", "channel_layout"), "mono", "{name}: the layout"); |
| 173 | assert_eq!(probe(&out, "a:0", "sample_rate"), "48000", "{name}"); |
| 174 | assert_eq!(frame_count(&out), frames, "{name}: every picture is there"); |
| 175 | let duration = format_duration(&out); |
| 176 | assert!((duration - f64::from(SECONDS)).abs() < 0.05, "{name}: duration {duration}"); |
| 177 | |
| 178 | |
| 179 | |
| 180 | let luma = psnr_10(&reference_y, &decoded_video(&out, "gray10le")); |
| 181 | let all = psnr_10(&reference_420, &decoded_video(&out, "yuv420p10le")); |
| 182 | eprintln!("{name}: luma {luma:.2} dB, all planes (4:2:0 view) {all:.2} dB"); |
| 183 | assert!(luma >= luma_floor, "{name}: luma PSNR {luma:.2} dB < {luma_floor}"); |
| 184 | assert!(all >= all_floor, "{name}: PSNR {all:.2} dB < {all_floor}"); |
| 185 | |
| 186 | |
| 187 | |
| 188 | let audio = decoded_audio(&out); |
| 189 | assert!( |
| 190 | (audio.len() as i64 - source_audio.len() as i64).abs() <= 2048, |
| 191 | "{name}: sound length {} vs {}", |
| 192 | audio.len(), |
| 193 | source_audio.len() |
| 194 | ); |
| 195 | let (lag, corr) = best_lag(&source_audio, &audio); |
| 196 | assert!(lag.abs() <= 48, "{name}: A/V lag of {lag} samples"); |
| 197 | assert!(corr > 0.99, "{name}: sound correlation {corr:.4}"); |
| 198 | } |
| 199 | let _ = std::fs::remove_dir_all(&dir); |
| 200 | } |
| 201 | |
| 202 | |
| 203 | |
| 204 | fn best_lag(a: &[i16], b: &[i16]) -> (i64, f64) { |
| 205 | let start = 24_000usize; |
| 206 | let len = 12_000usize; |
| 207 | let mut best = (0i64, f64::MIN); |
| 208 | for lag in -96i64..=96 { |
| 209 | let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); |
| 210 | for i in start..start + len { |
| 211 | let x = f64::from(a[i]); |
| 212 | let y = f64::from(b[(i as i64 + lag) as usize]); |
| 213 | ab += x * y; |
| 214 | aa += x * x; |
| 215 | bb += y * y; |
| 216 | } |
| 217 | let c = ab / (aa.sqrt() * bb.sqrt()).max(1.0); |
| 218 | if c > best.1 { |
| 219 | best = (lag, c); |
| 220 | } |
| 221 | } |
| 222 | best |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn cancelling_a_prores_export_leaves_no_file() { |
| 227 | if !tools() { |
| 228 | eprintln!("no ffmpeg/ffprobe: skipping the ProRes cancel test"); |
| 229 | return; |
| 230 | } |
| 231 | let _seat = seat::software(); |
| 232 | let dir = scratch("prores-cancel"); |
| 233 | let source = dir.join("source.mp4"); |
| 234 | make_source(&source, 1920, 1080, 12); |
| 235 | let out = dir.join("cancel.mov"); |
| 236 | let session = PlaybackSession::open(&source).expect("open"); |
| 237 | let settings = ExportSettings { format: Format::ProRes, prores_profile: ProResProfile::Hq, ..Default::default() }; |
| 238 | let handle = session.export_to_with(&out, &settings); |
| 239 | let started = Instant::now(); |
| 240 | while handle.progress() < 0.1 { |
| 241 | assert!(started.elapsed() < Duration::from_secs(120), "export never got going"); |
| 242 | assert!(!handle.is_finished(), "export finished before it was cancelled"); |
| 243 | std::thread::sleep(Duration::from_millis(10)); |
| 244 | } |
| 245 | handle.cancel(); |
| 246 | let started = Instant::now(); |
| 247 | while !handle.is_finished() { |
| 248 | assert!(started.elapsed() < Duration::from_secs(60), "the cancel never landed"); |
| 249 | std::thread::sleep(Duration::from_millis(10)); |
| 250 | } |
| 251 | assert!(handle.result().expect("an outcome").is_err(), "a cancelled export is an error"); |
| 252 | assert!(!out.exists(), "no partial file survives a cancel"); |
| 253 | let mut part = out.clone().into_os_string(); |
| 254 | part.push(".part"); |
| 255 | assert!(!Path::new(&part).exists(), "the .part is cleaned up too"); |
| 256 | let _ = std::fs::remove_dir_all(&dir); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn every_other_format_keeps_its_extension() { |
| 261 | assert_eq!(Format::Mp4.ext(), "mp4"); |
| 262 | assert_eq!(Format::Hevc.ext(), "mkv"); |
| 263 | assert_eq!(Format::HevcMp4.ext(), "mp4"); |
| 264 | assert_eq!(ExportSettings::default().prores_profile, ProResProfile::Hq); |
| 265 | } |
| 266 | |
| 267 | |
| 268 | fn decoded_f32(path: &Path, channels: usize) -> Vec<f32> { |
| 269 | let out = Command::new("ffmpeg") |
| 270 | .args(["-v", "error", "-i"]) |
| 271 | .arg(path) |
| 272 | .args(["-vn", "-ac", &channels.to_string(), "-ar", "48000", "-f", "f32le", "-"]) |
| 273 | .output() |
| 274 | .expect("ffmpeg runs"); |
| 275 | assert!(out.status.success(), "ffmpeg decodes the sound of {}", path.display()); |
| 276 | out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() |
| 277 | } |
| 278 | |
| 279 | |
| 280 | fn make_source_layout(out: &Path, layout: &str) { |
| 281 | let status = Command::new("ffmpeg") |
| 282 | .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) |
| 283 | .arg(format!("testsrc2=size=320x240:rate={FPS}:duration=1")) |
| 284 | .args(["-f", "lavfi", "-i"]) |
| 285 | .arg(format!("sine=frequency=440:sample_rate=48000:duration=1,volume=0.5,aformat=channel_layouts={layout}")) |
| 286 | .args(["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"]) |
| 287 | .args(["-c:a", "aac", "-b:a", "256k", "-shortest"]) |
| 288 | .arg(out) |
| 289 | .status() |
| 290 | .expect("ffmpeg runs"); |
| 291 | assert!(status.success(), "ffmpeg makes the {layout} source"); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn prores_sound_is_a_real_24_bit_mix_with_its_channel_layout() { |
| 296 | if !tools() { |
| 297 | eprintln!("no ffmpeg/ffprobe: skipping the ProRes 24-bit sound test"); |
| 298 | return; |
| 299 | } |
| 300 | let _seat = seat::software(); |
| 301 | let dir = scratch("prores-24"); |
| 302 | |
| 303 | for (layout, name, channels) in [("mono", "mono", 1usize), ("stereo", "stereo", 2)] { |
| 304 | let source = dir.join(format!("source-{name}.mp4")); |
| 305 | make_source_layout(&source, layout); |
| 306 | let out = dir.join(format!("{name}.mov")); |
| 307 | let settings = ExportSettings { format: Format::ProRes, prores_profile: ProResProfile::Proxy, ..Default::default() }; |
| 308 | export(&source, &out, &settings); |
| 309 | assert_eq!(probe(&out, "a:0", "codec_name"), "pcm_s24be", "{name}"); |
| 310 | assert_eq!(probe(&out, "a:0", "bits_per_sample"), "24", "{name}"); |
| 311 | assert_eq!(probe(&out, "a:0", "channels"), channels.to_string(), "{name}"); |
| 312 | assert_eq!(probe(&out, "a:0", "channel_layout"), layout, "{name}: the channel layout"); |
| 313 | |
| 314 | |
| 315 | |
| 316 | let reference = decoded_f32(&source, channels); |
| 317 | let got = decoded_f32(&out, channels); |
| 318 | let scale = 8_388_608.0f64; |
| 319 | let n = reference.len().min(got.len()); |
| 320 | assert!(n >= 40_000 * channels, "{name}: {n} samples"); |
| 321 | let mut worst = 0f64; |
| 322 | let mut distinct = std::collections::HashSet::new(); |
| 323 | for i in 4_800 * channels..n - 4_800 * channels { |
| 324 | let r = (f64::from(reference[i]) * 8_388_607.0).round(); |
| 325 | let g = f64::from(got[i]) * scale; |
| 326 | worst = worst.max((r - g).abs()); |
| 327 | distinct.insert((g as i64) & 0xFF); |
| 328 | } |
| 329 | eprintln!("{name}: worst difference {worst} LSB, {} distinct low bytes", distinct.len()); |
| 330 | assert!(worst <= 1.0, "{name}: {worst} LSB from the 24-bit reference"); |
| 331 | assert!(distinct.len() > 128, "{name}: the low byte is used, so this is not a widened 16-bit mix"); |
| 332 | } |
| 333 | |
| 334 | let source = dir.join("source-stereo.mp4"); |
| 335 | let out = dir.join("sixteen.mov"); |
| 336 | let settings = ExportSettings { |
| 337 | format: Format::ProRes, |
| 338 | prores_profile: ProResProfile::Proxy, |
| 339 | audio_bit_depth: Some(16), |
| 340 | ..Default::default() |
| 341 | }; |
| 342 | export(&source, &out, &settings); |
| 343 | assert_eq!(probe(&out, "a:0", "codec_name"), "pcm_s16le"); |
| 344 | let _ = std::fs::remove_dir_all(&dir); |
| 345 | } |