forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

oldavi.rs399 lines, 16.8 KiBHistoryRawDownload
1//! MS-MPEG4 version 2 and 3 (DivX 3), uncompressed video (BGR24, YUY2, I420, ...) and DV type-1
2//! (`iavs`) in AVI, end to end: probe, every picture against ffmpeg's decode, mid-file seeks
3//! against a sequential decode, sound, an export. All media is synthetic, made by ffmpeg into a
4//! scratch directory at test time (the type-1 wrapper is built here from a `.dv` file, as
5//! `ec-riff`'s tests do); without ffmpeg (or the encoder a case needs) a case says so and passes.
6//! `VE_SW` is process-wide, so tests pin it through [`software`].
7//!
8//! Pictures are compared in BGRA against `ffmpeg -pix_fmt bgra` by PSNR (raw RGB goes through the
9//! engine's YCbCr and 4:2:0 chroma, which costs a few dB against ffmpeg's untouched bytes). A seek
10//! is compared exactly.
11//!
12//! ```text
13//! cargo test -p engine --release --test oldavi
14//! ```
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::sync::Mutex;
19use std::time::{Duration, Instant};
20
21use engine::audio::AudioSession;
22use engine::decode::DecodeSession;
23use engine::demux::{Codec, Demuxer};
24use engine::export::{ExportSettings, Format};
25use engine::PlaybackSession;
26
27/// Floor for the BGRA PSNR against ffmpeg's own conversion (dB). Chroma averaging and the 8-bit
28/// truncation cost a few dB on a sharp test card; measured 31 to 55 dB (4:4:4 lowest, MJPEG 4:2:0 highest); a wrong range or matrix lands around 24.
29const MIN_PSNR: f64 = 28.0;
30
31static SW: Mutex<()> = Mutex::new(());
32
33fn 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
41fn 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
61fn 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
68fn 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
73fn s(p: &Path) -> &str {
74 p.to_str().unwrap()
75}
76
77fn 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
87fn session_frames(path: &Path) -> Vec<engine::decode::Frame> {
88 software(|| DecodeSession::open(path).expect("open").1.into_iter().collect())
89}
90
91/// ffmpeg's decode of the picture, as BGRA at the file's size.
92fn ffmpeg_bgra(path: &Path, width: u32, height: u32) -> Vec<u8> {
93 // The engine reads an untagged picture as BT.601 up to 576 lines and BT.709 above.
94 // A stream that states its matrix is converted by ffmpeg as stated, as the engine does; an
95 // untagged one is BT.601 to ffmpeg's scaler, and the size rule's BT.709 above 576 lines here.
96 // A stated pixel aspect (a raw .dv states 8:9) widens the engine's picture; ffmpeg's decode
97 // is at the coded size and is scaled to the engine's.
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/// PSNR over the colour bytes of two BGRA frames.
110fn 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/// Row-to-row luma-ish difference of a BGRA frame: high for a combed (woven) picture.
124fn 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
131fn 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/// Raw RGB takes the engine's YCbCr round trip and 4:2:0 chroma: lower than a YUV source.
144const RAW_PSNR: f64 = 40.0;
145
146const SINE: &str = "sine=frequency=440:sample_rate=48000:duration=2.4";
147const CIF: &str = "testsrc2=size=352x288:rate=25:duration=2";
148const PCM: &[&str] = &["-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2"];
149
150struct Case {
151 name: &'static str,
152 vargs: &'static [&'static str],
153 codec: Codec,
154 profile: &'static str,
155 min_psnr: f64,
156}
157
158fn make(dir: &Path, case: &Case) -> PathBuf {
159 let out = dir.join(format!("{}.avi", case.name));
160 let mut args = vec!["-f", "lavfi", "-i", CIF, "-f", "lavfi", "-i", SINE, "-map", "0:v", "-map", "1:a"];
161 args.extend(case.vargs);
162 args.extend(PCM);
163 args.extend(["-shortest", s(&out)]);
164 ffmpeg(&args);
165 out
166}
167
168const FRAMES: u32 = 50;
169
170fn cases() -> Vec<Case> {
171 let c = |name, vargs, codec, profile, min_psnr| Case { name, vargs, codec, profile, min_psnr };
172 vec![
173 c("msmpeg4v3", &["-c:v", "msmpeg4", "-vtag", "DIV3", "-qscale:v", "3", "-g", "12"], Codec::MsMpeg4, "v3", MIN_PSNR),
174 c("msmpeg4v3-mp43", &["-c:v", "msmpeg4", "-vtag", "MP43", "-b:v", "400k", "-g", "25"], Codec::MsMpeg4, "v3", MIN_PSNR),
175 c("msmpeg4v2", &["-c:v", "msmpeg4v2", "-qscale:v", "4", "-g", "12"], Codec::MsMpeg4, "v2", MIN_PSNR),
176 c("raw-bgr24", &["-c:v", "rawvideo", "-pix_fmt", "bgr24"], Codec::Raw, "BGR24", RAW_PSNR),
177 c("raw-bgra", &["-c:v", "rawvideo", "-pix_fmt", "bgra"], Codec::Raw, "BGRA", RAW_PSNR),
178 c("raw-yuyv", &["-c:v", "rawvideo", "-pix_fmt", "yuyv422"], Codec::Raw, "YUY2", MIN_PSNR),
179 c("raw-uyvy", &["-c:v", "rawvideo", "-pix_fmt", "uyvy422"], Codec::Raw, "UYVY", MIN_PSNR),
180 c("raw-i420", &["-c:v", "rawvideo", "-pix_fmt", "yuv420p"], Codec::Raw, "I420", MIN_PSNR),
181 c("raw-yv12", &["-c:v", "rawvideo", "-pix_fmt", "yuv420p", "-vtag", "YV12"], Codec::Raw, "YV12", MIN_PSNR),
182 ]
183}
184
185/// Probe, decode and seek one case.
186fn check(dir: &Path, case: &Case) {
187 let name = case.name;
188 let path = make(dir, case);
189
190 // ---- probe
191 let facts = engine::probe_media(&path);
192 let video = facts.video.as_ref().unwrap_or_else(|| panic!("{name}: no picture"));
193 eprintln!("{name}: {video:?}");
194 assert_eq!(video.codec, case.codec, "{name}");
195 assert!((video.frame_rate.unwrap() - 25.0).abs() < 0.01, "{name}: {:?}", video.frame_rate);
196 assert_eq!(video.bit_depth, Some(8), "{name}");
197 assert_eq!(video.profile, Some(case.profile), "{name}");
198 let (meta, _) = Demuxer::open(&path).expect("open");
199 assert_eq!(meta.frame_count, FRAMES, "{name}");
200 assert_eq!(AudioSession::probe_streams(&path).expect("streams").len(), 1, "{name}");
201
202 // ---- pictures
203 let all = session_frames(&path);
204 assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..FRAMES).collect::<Vec<_>>(), "{name}");
205 let want = ffmpeg_bgra(&path, all[0].width, all[0].height);
206 let size = all[0].bgra.len();
207 assert_eq!(want.len(), size * all.len(), "{name}: frame count or size differs from ffmpeg's");
208 let mut worst = 99.0f64;
209 for (i, f) in all.iter().enumerate() {
210 worst = worst.min(psnr(&f.bgra, &want[i * size..(i + 1) * size]));
211 }
212 eprintln!("{name}: worst PSNR against ffmpeg {worst:.1} dB");
213 assert!(worst >= case.min_psnr, "{name}: PSNR {worst:.1} dB");
214
215 // ---- seeks: a frame after a seek is the frame a sequential decode gives
216 for target in [0, 1, 13, FRAMES / 2, FRAMES - 2, FRAMES - 1] {
217 let seeked = software(|| {
218 let (_, rx, _c) = DecodeSession::open_at(&path, target).expect("open_at");
219 rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"))
220 });
221 assert_eq!(seeked.index, target, "{name}");
222 assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential");
223 }
224 let (a, b) = (FRAMES / 4, FRAMES / 4 + 9);
225 let range = software(|| {
226 let (_, rx, _c) = DecodeSession::open_range(&path, a, b).expect("open_range");
227 rx.into_iter().collect::<Vec<_>>()
228 });
229 assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (a..b).collect::<Vec<_>>(), "{name}");
230 for f in &range {
231 assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index);
232 }
233
234 // ---- export
235 let out = dir.join(format!("{name}.export.mp4"));
236 software(|| export_mp4(&path, &out));
237 assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), FRAMES, "{name}");
238}
239
240fn run(filter: impl Fn(&Case) -> bool, encoders: &[&str], tag: &str) {
241 if !have(encoders) {
242 return;
243 }
244 let dir = scratch(tag);
245 for case in cases().iter().filter(|c| filter(c)) {
246 check(&dir, case);
247 }
248 let _ = std::fs::remove_dir_all(&dir);
249}
250
251#[test]
252fn ms_mpeg4_v2_and_v3_open_decode_seek_and_export_from_avi() {
253 run(|c| c.codec == Codec::MsMpeg4, &["msmpeg4", "msmpeg4v2", "pcm_s16le"], "msmpeg4");
254}
255
256#[test]
257fn raw_video_opens_decodes_seeks_and_exports_from_avi() {
258 run(|c| c.codec == Codec::Raw, &["rawvideo", "pcm_s16le"], "raw");
259}
260
261// ------------------------------------------------------------------ DV type-1
262
263fn chunk(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
264 let mut v = id.to_vec();
265 v.extend((body.len() as u32).to_le_bytes());
266 v.extend(body);
267 if body.len() & 1 == 1 {
268 v.push(0);
269 }
270 v
271}
272
273fn list(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
274 let mut inner = kind.to_vec();
275 inner.extend(body);
276 let mut v = b"LIST".to_vec();
277 v.extend((inner.len() as u32).to_le_bytes());
278 v.extend(inner);
279 v
280}
281
282/// Raw DV frames as a type-1 AVI (`iavs`, handler `dvsd`, one `00dc` chunk per frame).
283fn type1_avi(dv: &[u8], frame_size: usize, scale: u32, rate: u32) -> Vec<u8> {
284 let frames: Vec<&[u8]> = dv.chunks_exact(frame_size).collect();
285 let mut strh = b"iavsdvsd".to_vec();
286 strh.extend([0u8; 12]);
287 strh.extend(scale.to_le_bytes());
288 strh.extend(rate.to_le_bytes());
289 strh.extend(0u32.to_le_bytes());
290 strh.extend((frames.len() as u32).to_le_bytes());
291 strh.extend([0u8; 20]);
292 let strl = list(b"strl", &[chunk(b"strh", &strh), chunk(b"strf", &[0u8; 32])].concat());
293 let mut avih = vec![0u8; 56];
294 avih[0..4].copy_from_slice(&(1_000_000u32 * scale / rate).to_le_bytes());
295 avih[16..20].copy_from_slice(&(frames.len() as u32).to_le_bytes());
296 avih[24..28].copy_from_slice(&1u32.to_le_bytes());
297 let hdrl = list(b"hdrl", &[chunk(b"avih", &avih), strl].concat());
298 let (mut movi_body, mut idx1) = (Vec::new(), Vec::new());
299 for f in &frames {
300 idx1.extend(b"00dc");
301 idx1.extend(0x10u32.to_le_bytes());
302 idx1.extend((4 + movi_body.len() as u32).to_le_bytes());
303 idx1.extend((f.len() as u32).to_le_bytes());
304 movi_body.extend(chunk(b"00dc", f));
305 }
306 let mut body = b"AVI ".to_vec();
307 body.extend(hdrl);
308 body.extend(list(b"movi", &movi_body));
309 body.extend(chunk(b"idx1", &idx1));
310 let mut out = b"RIFF".to_vec();
311 out.extend((body.len() as u32).to_le_bytes());
312 out.extend(body);
313 out
314}
315
316fn sound(path: &Path) -> Vec<f32> {
317 let (meta, rx) = AudioSession::open_multi_streams(&[(path.to_path_buf(), 0)], &[(Some(0), 0.0, f64::INFINITY)])
318 .expect("open")
319 .expect("sound");
320 assert_eq!(meta.sample_rate, 48_000);
321 let mut got = Vec::new();
322 for chunk in rx {
323 got.extend_from_slice(&chunk.samples);
324 }
325 got
326}
327
328/// DV type-1: the picture and the sound `ec-riff` splits out of each frame, against the same frames
329/// as a raw `.dv` (picture exact, sound exact) and, for the weave, ffmpeg's decode.
330fn type1_case(dir: &Path, tag: &str, size: &str, rate: &str, scale_rate: (u32, u32), frame_size: usize, pix: &str) {
331 let dv = dir.join(format!("{tag}.dv"));
332 let video = format!("testsrc2=size={size}:rate={rate}:duration=1.2");
333 ffmpeg(&[
334 "-f", "lavfi", "-i", &video, "-f", "lavfi", "-i", SINE, "-map", "0:v", "-map", "1:a", "-c:v", "dvvideo", "-pix_fmt", pix,
335 "-ac", "2", "-c:a", "pcm_s16le", "-shortest", "-f", "dv", s(&dv),
336 ]);
337 let avi = dir.join(format!("{tag}.avi"));
338 let bytes = std::fs::read(&dv).unwrap();
339 let frames = (bytes.len() / frame_size) as u32;
340 assert!(frames >= 28, "{tag}: {frames} frames");
341 std::fs::write(&avi, type1_avi(&bytes, frame_size, scale_rate.0, scale_rate.1)).unwrap();
342
343 let facts = engine::probe_media(&avi);
344 let v = facts.video.as_ref().unwrap_or_else(|| panic!("{tag}: no picture"));
345 assert_eq!(v.codec, Codec::Dv, "{tag}");
346 assert_eq!(v.profile, Some("DV25"), "{tag}");
347 let (meta, _) = Demuxer::open(&avi).expect("open");
348 assert_eq!(meta.frame_count, frames, "{tag}");
349 assert_eq!(AudioSession::probe_streams(&avi).expect("streams").len(), 1, "{tag}");
350
351 let all = session_frames(&avi);
352 assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..frames).collect::<Vec<_>>(), "{tag}");
353 let raw = session_frames(&dv);
354 for (a, b) in all.iter().zip(&raw) {
355 assert!(a.bgra == b.bgra, "{tag}: frame {} differs from the same frames as a raw .dv", a.index);
356 }
357 let want = ffmpeg_bgra(&avi, all[0].width, all[0].height);
358 let size = all[0].bgra.len();
359 assert_eq!(want.len(), size * all.len(), "{tag}: frame count or size differs from ffmpeg's");
360 // Woven by the camera, deinterlaced by us: less row-to-row energy than ffmpeg's woven decode.
361 let w = all[0].width as usize;
362 let (mut woven, mut ours) = (0.0, 0.0);
363 for n in 3..(frames as usize - 3) {
364 woven += comb(&want[n * size..(n + 1) * size], w);
365 ours += comb(&all[n].bgra, w);
366 }
367 assert!(ours <= woven, "{tag}: the interlaced picture is not deinterlaced ({ours:.1} vs {woven:.1})");
368
369 // The sound is the DIF audio blocks, the same samples a raw .dv gives.
370 let (ours, theirs) = (sound(&avi), sound(&dv));
371 let peak = ours.iter().fold(0f32, |m, v| m.max(v.abs()));
372 assert!(ours.len() / 2 >= 48_000 * 9 / 10, "{tag}: {} frames of sound", ours.len() / 2);
373 assert!(peak > 0.05, "{tag}: silent");
374 let n = ours.len().min(theirs.len());
375 assert!(ours[..n] == theirs[..n], "{tag}: the sound differs from the raw .dv's");
376
377 for target in [0, 1, frames / 2, frames - 1] {
378 let seeked = software(|| {
379 let (_, rx, _c) = DecodeSession::open_at(&avi, target).expect("open_at");
380 rx.into_iter().next().unwrap_or_else(|| panic!("{tag}: no frame after seek to {target}"))
381 });
382 assert_eq!(seeked.index, target, "{tag}");
383 assert!(seeked.bgra == all[target as usize].bgra, "{tag}: seek to {target} differs from sequential");
384 }
385 let out = dir.join(format!("{tag}.export.mp4"));
386 software(|| export_mp4(&avi, &out));
387 assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), frames, "{tag}");
388}
389
390#[test]
391fn dv_type1_avi_opens_plays_seeks_and_exports_with_its_sound() {
392 if !have(&["dvvideo", "pcm_s16le"]) {
393 return;
394 }
395 let dir = scratch("iavs");
396 type1_case(&dir, "pal", "720x576", "25", (1, 25), 144_000, "yuv420p");
397 type1_case(&dir, "ntsc", "720x480", "30000/1001", (1001, 30000), 120_000, "yuv411p");
398 let _ = std::fs::remove_dir_all(&dir);
399}