forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

dvmpeg4.rs334 lines, 14.5 KiBHistoryRawDownload
1//! DV (DV25 NTSC 4:1:1 and PAL 4:2:0, DVCPRO50, DVCPRO HD) and MPEG-4 Part 2 / H.263 end to end:
2//! probe, every picture against ffmpeg's decode, mid-file seeks, sound, an export. Containers:
3//! QuickTime/MP4/3GP, Matroska, AVI (DV type-2, XviD / DivX FourCCs) and raw `.dv`. All media is
4//! synthetic, made by ffmpeg into a scratch directory at test time; without ffmpeg (or the
5//! encoder a case needs) a case says so and passes, as `procodecs` does. `VE_SW` is
6//! process-wide, so tests pin it through [`software`].
7//!
8//! Pictures are compared in BGRA against `ffmpeg -pix_fmt bgra` by PSNR (the engine averages
9//! 4:2:2 chroma down to 4:2:0 before converting, which ffmpeg's scaler does differently; the
10//! decoders are byte-exact against ffmpeg in their own crates). A seek is compared exactly.
11//!
12//! ```text
13//! cargo test -p engine --release --test dvmpeg4
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
143const SINE: &str = "sine=frequency=440:sample_rate=48000:duration=2.4";
144
145struct Case {
146 name: &'static str,
147 video: &'static str,
148 vargs: &'static [&'static str],
149 /// Audio arguments; `None` for a silent clip.
150 aargs: Option<&'static [&'static str]>,
151 ext: &'static str,
152 codec: Codec,
153 profile: Option<&'static str>,
154 frames: u32,
155 /// Frames per second the probe must read.
156 fps: f64,
157 /// Interlace the probe states.
158 interlaced: Option<&'static str>,
159}
160
161const NTSC: &str = "testsrc2=size=720x480:rate=30000/1001:duration=1.001";
162const PAL: &str = "testsrc2=size=720x576:rate=25:duration=1.2";
163const HD: &str = "testsrc2=size=1440x1080:rate=25:duration=1.2";
164const CIF: &str = "testsrc2=size=352x288:rate=25:duration=2";
165const PCM: &[&str] = &["-c:a", "pcm_s16le", "-ar", "48000", "-ac", "2"];
166const AAC: &[&str] = &["-c:a", "aac", "-b:a", "128k"];
167const SP: &[&str] = &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-pix_fmt", "yuv420p"];
168const ASP: &[&str] = &["-c:v", "mpeg4", "-qscale:v", "3", "-g", "12", "-bf", "2", "-flags", "+qpel+mv4", "-pix_fmt", "yuv420p"];
169
170fn 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
189fn 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/// Probe, decode and seek one case.
214fn check(dir: &Path, case: &Case) {
215 let name = case.name;
216 let path = make(dir, case);
217
218 // ---- probe
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 // ---- pictures
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 // Woven by the encoder, deinterlaced by us: less row-to-row energy than ffmpeg's woven decode.
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 // ---- seeks: a frame after a seek is the frame a sequential decode gives
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 // ---- export
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
285fn 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]
297fn 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]
302fn 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]
307fn 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]
312fn 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}