| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | use std::process::Command; |
| 19 | use std::sync::Mutex; |
| 20 | use std::time::{Duration, Instant}; |
| 21 | |
| 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-rawmov-{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 | fn export_mp4(source: &Path, out: &Path) { |
| 124 | let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display())); |
| 125 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 126 | let handle = session.export_to_with(out, &settings); |
| 127 | let started = Instant::now(); |
| 128 | while !handle.is_finished() { |
| 129 | assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); |
| 130 | std::thread::sleep(Duration::from_millis(20)); |
| 131 | } |
| 132 | handle.result().expect("an outcome").expect("the export"); |
| 133 | } |
| 134 | |
| 135 | const FRAMES: u32 = 50; |
| 136 | |
| 137 | struct Case { |
| 138 | name: &'static str, |
| 139 | ext: &'static str, |
| 140 | size: (u32, u32), |
| 141 | vargs: &'static [&'static str], |
| 142 | profile: &'static str, |
| 143 | bit_depth: u8, |
| 144 | min_psnr: f64, |
| 145 | } |
| 146 | |
| 147 | |
| 148 | const RGB_PSNR: f64 = 38.0; |
| 149 | const CIF: (u32, u32) = (352, 288); |
| 150 | const ODD: (u32, u32) = (203, 151); |
| 151 | |
| 152 | fn cases() -> Vec<Case> { |
| 153 | let c = |name, ext, size, vargs, profile, bit_depth, min_psnr| Case { name, ext, size, vargs, profile, bit_depth, min_psnr }; |
| 154 | let raw = |p: &'static str| -> &'static [&'static str] { |
| 155 | match p { |
| 156 | "uyvy422" => &["-c:v", "rawvideo", "-pix_fmt", "uyvy422"], |
| 157 | "yuyv422" => &["-c:v", "rawvideo", "-pix_fmt", "yuyv422"], |
| 158 | "rgb24" => &["-c:v", "rawvideo", "-pix_fmt", "rgb24"], |
| 159 | "argb" => &["-c:v", "rawvideo", "-pix_fmt", "argb"], |
| 160 | "rgb555be" => &["-c:v", "rawvideo", "-pix_fmt", "rgb555be"], |
| 161 | "gray16be" => &["-c:v", "rawvideo", "-pix_fmt", "gray16be"], |
| 162 | "nv12" => &["-c:v", "rawvideo", "-pix_fmt", "nv12"], |
| 163 | "gray" => &["-c:v", "rawvideo", "-pix_fmt", "gray"], |
| 164 | "rgb555le" => &["-c:v", "rawvideo", "-pix_fmt", "rgb555le"], |
| 165 | _ => &["-c:v", "rawvideo", "-pix_fmt", "pal8"], |
| 166 | } |
| 167 | }; |
| 168 | vec![ |
| 169 | c("mov-uyvy", "mov", CIF, raw("uyvy422"), "UYVY", 8, MIN_PSNR), |
| 170 | c("mov-uyvy-odd", "mov", ODD, raw("uyvy422"), "UYVY", 8, MIN_PSNR), |
| 171 | c("mov-yuvs", "mov", CIF, raw("yuyv422"), "YUY2", 8, MIN_PSNR), |
| 172 | c("mov-rgb24", "mov", CIF, raw("rgb24"), "RGB24", 8, RGB_PSNR), |
| 173 | c("mov-rgb24-odd", "mov", ODD, raw("rgb24"), "RGB24", 8, RGB_PSNR), |
| 174 | c("mov-argb", "mov", CIF, raw("argb"), "ARGB", 8, RGB_PSNR), |
| 175 | c("mov-rgb555", "mov", CIF, raw("rgb555be"), "RGB555", 8, 30.0), |
| 176 | c("mov-v210", "mov", CIF, &["-c:v", "v210"], "v210", 10, MIN_PSNR), |
| 177 | c("mov-v210-odd", "mov", ODD, &["-c:v", "v210"], "v210", 10, MIN_PSNR), |
| 178 | c("mov-v410", "mov", CIF, &["-c:v", "v410"], "v410", 10, 28.0), |
| 179 | c("mov-b16g", "mov", CIF, raw("gray16be"), "Gray16", 10, MIN_PSNR), |
| 180 | c("avi-nv12", "avi", CIF, raw("nv12"), "NV12", 8, MIN_PSNR), |
| 181 | c("avi-nv12-odd", "avi", ODD, raw("nv12"), "NV12", 8, MIN_PSNR), |
| 182 | c("avi-gray", "avi", CIF, raw("gray"), "Y800", 8, MIN_PSNR), |
| 183 | c("avi-rgb555", "avi", CIF, raw("rgb555le"), "RGB555", 8, 30.0), |
| 184 | c("avi-pal8", "avi", CIF, raw("pal8"), "PAL8", 8, 28.0), |
| 185 | c("avi-v210", "avi", CIF, &["-c:v", "v210"], "v210", 10, MIN_PSNR), |
| 186 | ] |
| 187 | } |
| 188 | |
| 189 | fn make(dir: &Path, case: &Case) -> PathBuf { |
| 190 | let out = dir.join(format!("{}.{}", case.name, case.ext)); |
| 191 | let src = format!("testsrc2=size={}x{}:rate=25:duration=2", case.size.0, case.size.1); |
| 192 | let mut args = vec!["-f", "lavfi", "-i", &src]; |
| 193 | args.extend(case.vargs); |
| 194 | args.extend(["-an", s(&out)]); |
| 195 | ffmpeg(&args); |
| 196 | out |
| 197 | } |
| 198 | |
| 199 | |
| 200 | fn check(dir: &Path, case: &Case) { |
| 201 | let name = case.name; |
| 202 | let path = make(dir, case); |
| 203 | |
| 204 | |
| 205 | let facts = engine::probe_media(&path); |
| 206 | let video = facts.video.as_ref().unwrap_or_else(|| panic!("{name}: no picture: {facts:?}")); |
| 207 | eprintln!("{name}: {video:?}"); |
| 208 | assert_eq!(video.codec, Codec::Raw, "{name}"); |
| 209 | assert!((video.frame_rate.unwrap() - 25.0).abs() < 0.01, "{name}: {:?}", video.frame_rate); |
| 210 | assert_eq!(video.bit_depth, Some(case.bit_depth), "{name}"); |
| 211 | assert_eq!(video.profile, Some(case.profile), "{name}"); |
| 212 | |
| 213 | assert_eq!((video.width, video.height), (case.size.0 & !1, case.size.1 & !1), "{name}"); |
| 214 | let (meta, _) = Demuxer::open(&path).expect("open"); |
| 215 | assert_eq!(meta.frame_count, FRAMES, "{name}"); |
| 216 | |
| 217 | |
| 218 | let all = session_frames(&path); |
| 219 | assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..FRAMES).collect::<Vec<_>>(), "{name}"); |
| 220 | let want = ffmpeg_bgra(&path, all[0].width, all[0].height); |
| 221 | let size = all[0].bgra.len(); |
| 222 | assert_eq!(want.len(), size * all.len(), "{name}: frame count or size differs from ffmpeg's"); |
| 223 | let mut worst = 99.0f64; |
| 224 | for (i, f) in all.iter().enumerate() { |
| 225 | worst = worst.min(psnr(&f.bgra, &want[i * size..(i + 1) * size])); |
| 226 | } |
| 227 | eprintln!("{name}: worst PSNR against ffmpeg {worst:.1} dB"); |
| 228 | assert!(worst >= case.min_psnr, "{name}: PSNR {worst:.1} dB"); |
| 229 | |
| 230 | |
| 231 | for target in [0, 1, 13, FRAMES / 2, FRAMES - 2, FRAMES - 1] { |
| 232 | let seeked = software(|| { |
| 233 | let (_, rx, _c) = DecodeSession::open_at(&path, target).expect("open_at"); |
| 234 | rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}")) |
| 235 | }); |
| 236 | assert_eq!(seeked.index, target, "{name}"); |
| 237 | assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential"); |
| 238 | } |
| 239 | let (a, b) = (FRAMES / 4, FRAMES / 4 + 9); |
| 240 | let range = software(|| { |
| 241 | let (_, rx, _c) = DecodeSession::open_range(&path, a, b).expect("open_range"); |
| 242 | rx.into_iter().collect::<Vec<_>>() |
| 243 | }); |
| 244 | assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (a..b).collect::<Vec<_>>(), "{name}"); |
| 245 | for f in &range { |
| 246 | assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index); |
| 247 | } |
| 248 | |
| 249 | |
| 250 | let out = dir.join(format!("{name}.export.mp4")); |
| 251 | software(|| export_mp4(&path, &out)); |
| 252 | assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), FRAMES, "{name}"); |
| 253 | |
| 254 | |
| 255 | |
| 256 | if case.bit_depth == 10 { |
| 257 | let ten = dir.join(format!("{name}.ten.mp4")); |
| 258 | software(|| export_with(&path, &ten, Format::Av1Mp4, None)); |
| 259 | assert_eq!(ffprobe(&ten, "stream=pix_fmt", "v:0"), "yuv420p10le", "{name}: a 10-bit source exports 10-bit"); |
| 260 | assert_eq!(ffprobe(&ten, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), FRAMES, "{name}"); |
| 261 | let back = ffmpeg_bgra(&ten, all[0].width, all[0].height); |
| 262 | assert_eq!(back.len(), want.len(), "{name}: export size"); |
| 263 | let mid = (FRAMES / 2) as usize; |
| 264 | let p = psnr(&back[mid * size..(mid + 1) * size], &want[mid * size..(mid + 1) * size]); |
| 265 | eprintln!("{name}: 10-bit export against ffmpeg's decode of the source {p:.1} dB"); |
| 266 | assert!(p >= 24.0, "{name}: 10-bit export PSNR {p:.1} dB"); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | fn export_with(source: &Path, out: &Path, format: Format, depth: Option<u8>) { |
| 271 | let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display())); |
| 272 | let settings = ExportSettings { format, video_bit_depth: depth, ..Default::default() }; |
| 273 | let handle = session.export_to_with(out, &settings); |
| 274 | let started = Instant::now(); |
| 275 | while !handle.is_finished() { |
| 276 | assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s"); |
| 277 | std::thread::sleep(Duration::from_millis(20)); |
| 278 | } |
| 279 | handle.result().expect("an outcome").expect("the export"); |
| 280 | } |
| 281 | |
| 282 | fn run(filter: impl Fn(&Case) -> bool, tag: &str) { |
| 283 | if !have(&["rawvideo", "v210", "v410"]) { |
| 284 | return; |
| 285 | } |
| 286 | let dir = scratch(tag); |
| 287 | for case in cases().iter().filter(|c| filter(c)) { |
| 288 | check(&dir, case); |
| 289 | } |
| 290 | let _ = std::fs::remove_dir_all(&dir); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn raw_video_in_mov_opens_decodes_seeks_and_exports() { |
| 295 | run(|c| c.ext == "mov", "mov"); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn newer_raw_layouts_in_avi_open_decode_seek_and_export() { |
| 300 | run(|c| c.ext == "avi", "avi"); |
| 301 | } |
| 302 | |
| 303 | |
| 304 | |
| 305 | #[test] |
| 306 | fn raw_layouts_the_decoder_refuses_are_refused_by_name() { |
| 307 | if !have(&["rawvideo"]) { |
| 308 | return; |
| 309 | } |
| 310 | let dir = scratch("refused"); |
| 311 | for (name, ext, pix) in [("mov-pal8", "mov", "pal8"), ("avi-mono", "avi", "monow")] { |
| 312 | let path = dir.join(format!("{name}.{ext}")); |
| 313 | ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=64x48:rate=25:duration=1", "-c:v", "rawvideo", "-pix_fmt", pix, "-an", s(&path)]); |
| 314 | let err = Demuxer::open(&path).err().unwrap_or_else(|| panic!("{name}: opened")).to_string(); |
| 315 | eprintln!("{name}: {err}"); |
| 316 | assert!((err.contains("not supported") || err.contains("unsupported")) && err.contains("ffmpeg -i"), "{name}: {err}"); |
| 317 | } |
| 318 | let _ = std::fs::remove_dir_all(&dir); |
| 319 | } |