| 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 | use std::sync::Mutex; |
| 19 | use std::time::{Duration, Instant}; |
| 20 | |
| 21 | use engine::audio::AudioSession; |
| 22 | use engine::decode::DecodeSession; |
| 23 | use engine::demux::{Codec, Demuxer}; |
| 24 | use engine::export::{ExportSettings, Format}; |
| 25 | use engine::PlaybackSession; |
| 26 | |
| 27 | |
| 28 | |
| 29 | const MIN_PSNR: f64 = 28.0; |
| 30 | |
| 31 | static SW: Mutex<()> = Mutex::new(()); |
| 32 | |
| 33 | fn software<T>(f: impl FnOnce() -> T) -> T { |
| 34 | let _guard = SW.lock().unwrap_or_else(|p| p.into_inner()); |
| 35 | engine::envcfg::set("VE_SW", "1"); |
| 36 | let out = f(); |
| 37 | engine::envcfg::unset("VE_SW"); |
| 38 | out |
| 39 | } |
| 40 | |
| 41 | fn have(encoders: &[&str]) -> bool { |
| 42 | let tool = |t: &str| Command::new(t).arg("-version").output().is_ok_and(|o| o.status.success()); |
| 43 | if !tool("ffmpeg") || !tool("ffprobe") { |
| 44 | eprintln!("no ffmpeg: skipping"); |
| 45 | return false; |
| 46 | } |
| 47 | let list = Command::new("ffmpeg") |
| 48 | .args(["-hide_banner", "-encoders"]) |
| 49 | .output() |
| 50 | .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) |
| 51 | .unwrap_or_default(); |
| 52 | for e in encoders { |
| 53 | if !list.split_whitespace().any(|w| w == *e) { |
| 54 | eprintln!("ffmpeg has no {e} encoder: skipping"); |
| 55 | return false; |
| 56 | } |
| 57 | } |
| 58 | true |
| 59 | } |
| 60 | |
| 61 | fn scratch(name: &str) -> PathBuf { |
| 62 | let dir = std::env::temp_dir().join(format!("edith-dvmpeg4-{name}-{}", std::process::id())); |
| 63 | let _ = std::fs::remove_dir_all(&dir); |
| 64 | std::fs::create_dir_all(&dir).expect("scratch directory"); |
| 65 | dir |
| 66 | } |
| 67 | |
| 68 | fn ffmpeg(args: &[&str]) { |
| 69 | let out = Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).output().expect("run ffmpeg"); |
| 70 | assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); |
| 71 | } |
| 72 | |
| 73 | fn s(p: &Path) -> &str { |
| 74 | p.to_str().unwrap() |
| 75 | } |
| 76 | |
| 77 | fn ffprobe(path: &Path, entries: &str, select: &str) -> String { |
| 78 | let out = Command::new("ffprobe") |
| 79 | .args(["-v", "error", "-select_streams", select, "-show_entries", entries, "-of", "csv=p=0"]) |
| 80 | .arg(path) |
| 81 | .output() |
| 82 | .expect("ffprobe runs"); |
| 83 | assert!(out.status.success(), "ffprobe reads {}", path.display()); |
| 84 | String::from_utf8_lossy(&out.stdout).trim().to_owned() |
| 85 | } |
| 86 | |
| 87 | fn session_frames(path: &Path) -> Vec<engine::decode::Frame> { |
| 88 | software(|| DecodeSession::open(path).expect("open").1.into_iter().collect()) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | fn ffmpeg_bgra(path: &Path, width: u32, height: u32) -> Vec<u8> { |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | let vf = if width > 854 { format!("scale={width}:{height}:in_color_matrix=bt709:out_color_matrix=bt709") } else { format!("scale={width}:{height}") }; |
| 99 | let out = Command::new("ffmpeg") |
| 100 | .args(["-v", "error", "-i"]) |
| 101 | .arg(path) |
| 102 | .args(["-an", "-vf", &vf, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "bgra", "-"]) |
| 103 | .output() |
| 104 | .expect("ffmpeg runs"); |
| 105 | assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); |
| 106 | out.stdout |
| 107 | } |
| 108 | |
| 109 | |
| 110 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 111 | assert_eq!(a.len(), b.len()); |
| 112 | let (mut sq, mut n) = (0f64, 0f64); |
| 113 | for (p, q) in a.chunks(4).zip(b.chunks(4)) { |
| 114 | for k in 0..3 { |
| 115 | let d = f64::from(p[k]) - f64::from(q[k]); |
| 116 | sq += d * d; |
| 117 | n += 1.0; |
| 118 | } |
| 119 | } |
| 120 | if sq == 0.0 { 99.0 } else { 10.0 * (255.0 * 255.0 * n / sq).log10() } |
| 121 | } |
| 122 | |
| 123 | |
| 124 | fn comb(frame: &[u8], width: usize) -> f64 { |
| 125 | let row = width * 4; |
| 126 | let rows: Vec<&[u8]> = frame.chunks(row).collect(); |
| 127 | let total: u64 = rows.windows(2).map(|w| w[0].iter().zip(w[1]).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::<u64>()).sum(); |
| 128 | total as f64 / frame.len() as f64 |
| 129 | } |
| 130 | |
| 131 | fn export_mp4(source: &Path, out: &Path) { |
| 132 | let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display())); |
| 133 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 134 | let handle = session.export_to_with(out, &settings); |
| 135 | let started = Instant::now(); |
| 136 | while !handle.is_finished() { |
| 137 | assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); |
| 138 | std::thread::sleep(Duration::from_millis(20)); |
| 139 | } |
| 140 | handle.result().expect("an outcome").expect("the export"); |
| 141 | } |
| 142 | |
| 143 | const SINE: &str = "sine=frequency=440:sample_rate=48000:duration=2.4"; |
| 144 | |
| 145 | struct Case { |
| 146 | name: &'static str, |
| 147 | video: &'static str, |
| 148 | vargs: &'static [&'static str], |
| 149 | |
| 150 | aargs: Option<&'static [&'static str]>, |
| 151 | ext: &'static str, |
| 152 | codec: Codec, |
| 153 | profile: Option<&'static str>, |
| 154 | frames: u32, |
| 155 | |
| 156 | fps: f64, |
| 157 | |
| 158 | interlaced: Option<&'static str>, |
| 159 | } |
| 160 | |
| 161 | const NTSC: &str = "testsrc2=size=720x480:rate=30000/1001:duration=1.001"; |
| 162 | const PAL: &str = "testsrc2=size=720x576:rate=25:duration=1.2"; |
| 163 | const HD: &str = "testsrc2=size=1440x1080:rate=25:duration=1.2"; |
| 164 | const CIF: &str = "testsrc2=size=352x288:rate=25:duration=2"; |
| 165 | const PCM: &[&str] = &["-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2"]; |
| 166 | const AAC: &[&str] = &["-c:a", "aac", "-b:a", "128k"]; |
| 167 | const SP: &[&str] = &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-pix_fmt", "yuv420p"]; |
| 168 | const ASP: &[&str] = &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-bf", "2", "-flags", "+qpel+mv4", "-pix_fmt", "yuv420p"]; |
| 169 | |
| 170 | fn make(dir: &Path, case: &Case) -> PathBuf { |
| 171 | let out = dir.join(format!("{}.{}", case.name, case.ext)); |
| 172 | let mut args = vec!["-f", "lavfi", "-i", case.video]; |
| 173 | if case.aargs.is_some() { |
| 174 | args.extend(["-f", "lavfi", "-i", SINE]); |
| 175 | } |
| 176 | args.extend(["-map", "0:v"]); |
| 177 | if case.aargs.is_some() { |
| 178 | args.extend(["-map", "1:a"]); |
| 179 | } |
| 180 | args.extend(case.vargs); |
| 181 | if let Some(a) = case.aargs { |
| 182 | args.extend(a); |
| 183 | } |
| 184 | args.extend(["-shortest", s(&out)]); |
| 185 | ffmpeg(&args); |
| 186 | out |
| 187 | } |
| 188 | |
| 189 | fn cases() -> Vec<Case> { |
| 190 | let c = |name, video, vargs, aargs, ext, codec, profile, frames, fps, interlaced| Case { |
| 191 | name, video, vargs, aargs, ext, codec, profile, frames, fps, interlaced, |
| 192 | }; |
| 193 | let dv25 = Some("DV25"); |
| 194 | let ntsc = 30000.0 / 1001.0; |
| 195 | vec![ |
| 196 | c("dv25-ntsc-mov", NTSC, &["-c:v", "dvvideo", "-pix_fmt", "yuv411p"], Some(PCM), "mov", Codec::Dv, dv25, 30, ntsc, Some("bff")), |
| 197 | c("dv25-ntsc-avi", NTSC, &["-c:v", "dvvideo", "-pix_fmt", "yuv411p"], Some(PCM), "avi", Codec::Dv, dv25, 30, ntsc, Some("bff")), |
| 198 | c("dv25-ntsc-raw", NTSC, &["-c:v", "dvvideo", "-pix_fmt", "yuv411p", "-f", "dv"], Some(PCM), "dv", Codec::Dv, dv25, 29, ntsc, Some("bff")), |
| 199 | c("dv25-pal-mov", PAL, &["-c:v", "dvvideo", "-pix_fmt", "yuv420p"], Some(PCM), "mov", Codec::Dv, dv25, 30, 25.0, Some("bff")), |
| 200 | c("dvcpro50-mov", PAL, &["-c:v", "dvvideo", "-pix_fmt", "yuv422p", "-b:v", "50M"], Some(PCM), "mov", Codec::Dv, Some("DVCPRO50"), 30, 25.0, Some("bff")), |
| 201 | c("dvcprohd-mov", HD, &["-c:v", "dvvideo", "-pix_fmt", "yuv422p", "-b:v", "100M", "-s", "1440x1080"], None, "mov", Codec::Dv, Some("DVCPRO HD"), 30, 25.0, Some("bff")), |
| 202 | c("sp-mp4", CIF, SP, Some(AAC), "mp4", Codec::Mpeg4, Some("Simple"), 50, 25.0, None), |
| 203 | c("asp-mp4", CIF, ASP, Some(AAC), "mp4", Codec::Mpeg4, Some("Advanced Simple"), 50, 25.0, None), |
| 204 | c("asp-mov", CIF, ASP, Some(AAC), "mov", Codec::Mpeg4, Some("Advanced Simple"), 50, 25.0, None), |
| 205 | c("asp-mkv", CIF, ASP, Some(PCM), "mkv", Codec::Mpeg4, Some("Advanced Simple"), 50, 25.0, None), |
| 206 | c("sp-avi-xvid", CIF, &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-vtag", "xvid", "-pix_fmt", "yuv420p"], Some(PCM), "avi", Codec::Mpeg4, None, 50, 25.0, None), |
| 207 | c("asp-avi-divx", CIF, &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-bf", "2", "-vtag", "DIVX", "-pix_fmt", "yuv420p"], Some(PCM), "avi", Codec::Mpeg4, None, 50, 25.0, None), |
| 208 | c("h263-3gp", CIF, &["-c:v", "h263", "-s", "352x288", "-g", "12"], Some(&["-c:a", "aac", "-b:a", "64k", "-ar", "16000", "-ac", "1"]), "3gp", Codec::Mpeg4, Some("H.263"), 50, 25.0, None), |
| 209 | c("h263-3g2", CIF, &["-c:v", "h263", "-s", "352x288", "-g", "12"], None, "3g2", Codec::Mpeg4, Some("H.263"), 50, 25.0, None), |
| 210 | ] |
| 211 | } |
| 212 | |
| 213 | |
| 214 | fn check(dir: &Path, case: &Case) { |
| 215 | let name = case.name; |
| 216 | let path = make(dir, case); |
| 217 | |
| 218 | |
| 219 | let facts = engine::probe_media(&path); |
| 220 | let video = facts.video.as_ref().unwrap_or_else(|| panic!("{name}: no picture")); |
| 221 | eprintln!("{name}: {video:?}"); |
| 222 | assert_eq!(video.codec, case.codec, "{name}"); |
| 223 | assert!((video.frame_rate.unwrap() - case.fps).abs() < 0.01, "{name}: {:?}", video.frame_rate); |
| 224 | assert_eq!(video.bit_depth, Some(8), "{name}"); |
| 225 | assert_eq!(video.profile, case.profile, "{name}"); |
| 226 | assert_eq!(video.interlaced, case.interlaced, "{name}"); |
| 227 | let (meta, _) = Demuxer::open(&path).expect("open"); |
| 228 | assert_eq!(meta.frame_count, case.frames, "{name}"); |
| 229 | if case.aargs.is_some() { |
| 230 | let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 231 | assert_eq!(streams.len(), 1, "{name}"); |
| 232 | } |
| 233 | |
| 234 | |
| 235 | let all = session_frames(&path); |
| 236 | assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..case.frames).collect::<Vec<_>>(), "{name}"); |
| 237 | let want = ffmpeg_bgra(&path, all[0].width, all[0].height); |
| 238 | let size = all[0].bgra.len(); |
| 239 | assert_eq!(want.len(), size * all.len(), "{name}: frame count or size differs from ffmpeg's"); |
| 240 | if case.interlaced.is_none() { |
| 241 | let mut worst = 99.0f64; |
| 242 | for (i, f) in all.iter().enumerate() { |
| 243 | worst = worst.min(psnr(&f.bgra, &want[i * size..(i + 1) * size])); |
| 244 | } |
| 245 | eprintln!("{name}: worst PSNR against ffmpeg {worst:.1} dB"); |
| 246 | assert!(worst >= MIN_PSNR, "{name}: PSNR {worst:.1} dB"); |
| 247 | } else { |
| 248 | |
| 249 | let w = all[0].width as usize; |
| 250 | let (mut woven, mut ours) = (0.0, 0.0); |
| 251 | for n in 3..(case.frames as usize - 3) { |
| 252 | woven += comb(&want[n * size..(n + 1) * size], w); |
| 253 | ours += comb(&all[n].bgra, w); |
| 254 | } |
| 255 | eprintln!("{name}: comb woven {woven:.1}, deinterlaced {ours:.1}"); |
| 256 | assert!(ours <= woven, "{name}: the interlaced picture is not deinterlaced"); |
| 257 | } |
| 258 | |
| 259 | |
| 260 | let n = case.frames; |
| 261 | for target in [0, 1, 13, n / 2, n - 2, n - 1] { |
| 262 | let seeked = software(|| { |
| 263 | let (_, rx, _c) = DecodeSession::open_at(&path, target).expect("open_at"); |
| 264 | rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}")) |
| 265 | }); |
| 266 | assert_eq!(seeked.index, target, "{name}"); |
| 267 | assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential"); |
| 268 | } |
| 269 | let (a, b) = (n / 4, n / 4 + 9); |
| 270 | let range = software(|| { |
| 271 | let (_, rx, _c) = DecodeSession::open_range(&path, a, b).expect("open_range"); |
| 272 | rx.into_iter().collect::<Vec<_>>() |
| 273 | }); |
| 274 | assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (a..b).collect::<Vec<_>>(), "{name}"); |
| 275 | for f in &range { |
| 276 | assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index); |
| 277 | } |
| 278 | |
| 279 | |
| 280 | let out = dir.join(format!("{name}.export.mp4")); |
| 281 | software(|| export_mp4(&path, &out)); |
| 282 | assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), case.frames, "{name}"); |
| 283 | } |
| 284 | |
| 285 | fn run(filter: impl Fn(&Case) -> bool, encoders: &[&str], tag: &str) { |
| 286 | if !have(encoders) { |
| 287 | return; |
| 288 | } |
| 289 | let dir = scratch(tag); |
| 290 | for case in cases().iter().filter(|c| filter(c)) { |
| 291 | check(&dir, case); |
| 292 | } |
| 293 | let _ = std::fs::remove_dir_all(&dir); |
| 294 | } |
| 295 | |
| 296 | #[test] |
| 297 | fn dv_opens_decodes_seeks_and_exports_from_mov_avi_and_raw() { |
| 298 | run(|c| c.codec == Codec::Dv, &["dvvideo", "pcm_s16le"], "dv"); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn mpeg4_part2_opens_decodes_seeks_and_exports_from_mp4_mov_mkv_and_avi() { |
| 303 | run(|c| c.codec == Codec::Mpeg4 && !c.name.starts_with("h263"), &["mpeg4", "aac", "pcm_s16le"], "mpeg4"); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn h263_opens_decodes_seeks_and_exports_from_3gp_and_3g2() { |
| 308 | run(|c| c.name.starts_with("h263"), &["h263", "aac"], "h263"); |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn raw_dv_carries_its_sound() { |
| 313 | if !have(&["dvvideo", "pcm_s16le"]) { |
| 314 | return; |
| 315 | } |
| 316 | let dir = scratch("dvaudio"); |
| 317 | let case = &cases()[2]; |
| 318 | let path = make(&dir, case); |
| 319 | let streams = AudioSession::probe_streams(&path).expect("streams"); |
| 320 | assert_eq!(streams.len(), 1); |
| 321 | let (meta, rx) = AudioSession::open_multi_streams(&[(path.clone(), 0)], &[(Some(0), 0.0, f64::INFINITY)]) |
| 322 | .expect("open") |
| 323 | .expect("sound"); |
| 324 | assert_eq!(meta.sample_rate, 48_000); |
| 325 | let width = usize::from(meta.channels); |
| 326 | let mut got = Vec::new(); |
| 327 | for chunk in rx { |
| 328 | got.extend_from_slice(&chunk.samples); |
| 329 | } |
| 330 | let peak = got.iter().fold(0f32, |m, v| m.max(v.abs())); |
| 331 | assert!(got.len() / width >= 48_000 * 9 / 10, "{} frames of sound", got.len() / width); |
| 332 | assert!(peak > 0.05, "silent: {peak}"); |
| 333 | let _ = std::fs::remove_dir_all(&dir); |
| 334 | } |