forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

procodecs.rs635 lines, 27.1 KiBHistoryRawDownload
1//! ProRes, DNxHD/DNxHR and Motion JPEG (QuickTime/MP4 and Matroska) end to end: probe, every
2//! picture against ffmpeg's decode, mid-file seeks, picture/sound sync after open and seek, and
3//! an export. All media is synthetic, made by ffmpeg into a scratch directory at test time;
4//! without ffmpeg (or the encoder a case needs) a case says so and passes, as `mpegts` does.
5//! `VE_SW` is process-wide, so tests pin it through [`software`].
6//!
7//! Pictures are compared in BGRA against `ffmpeg -pix_fmt bgra` by PSNR: the engine averages
8//! 4:2:2 / 4:4:4 chroma down to 4:2:0 and drops 10/12-bit to 8 before converting, which ffmpeg's
9//! scaler does differently, so exactness is not the claim (the decoders are byte-exact against
10//! ffmpeg in their own crates); a wrong matrix, range, plane or off-by-one frame lands far below
11//! [`MIN_PSNR`]. A seek, and the same stream in the other container, are compared exactly.
12//!
13//! ```text
14//! cargo test -p engine --release --test procodecs
15//! ```
16
17use std::path::{Path, PathBuf};
18use std::process::Command;
19use std::sync::Mutex;
20use std::time::{Duration, Instant};
21
22use engine::audio::AudioSession;
23use engine::decode::DecodeSession;
24use engine::demux::{Codec, Demuxer};
25use engine::export::{ExportSettings, Format};
26use engine::PlaybackSession;
27
28/// Floor for the BGRA PSNR against ffmpeg's own conversion (dB). Chroma averaging and the 8-bit
29/// 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.
30const MIN_PSNR: f64 = 28.0;
31
32static SW: Mutex<()> = Mutex::new(());
33
34fn software<T>(f: impl FnOnce() -> T) -> T {
35 let _guard = SW.lock().unwrap_or_else(|p| p.into_inner());
36 engine::envcfg::set("VE_SW", "1");
37 let out = f();
38 engine::envcfg::unset("VE_SW");
39 out
40}
41
42fn have(encoders: &[&str]) -> bool {
43 let tool = |t: &str| Command::new(t).arg("-version").output().is_ok_and(|o| o.status.success());
44 if !tool("ffmpeg") || !tool("ffprobe") {
45 eprintln!("no ffmpeg: skipping");
46 return false;
47 }
48 let list = Command::new("ffmpeg")
49 .args(["-hide_banner", "-encoders"])
50 .output()
51 .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
52 .unwrap_or_default();
53 for e in encoders {
54 if !list.split_whitespace().any(|w| w == *e) {
55 eprintln!("ffmpeg has no {e} encoder: skipping");
56 return false;
57 }
58 }
59 true
60}
61
62fn scratch(name: &str) -> PathBuf {
63 let dir = std::env::temp_dir().join(format!("edith-procodecs-{name}-{}", std::process::id()));
64 let _ = std::fs::remove_dir_all(&dir);
65 std::fs::create_dir_all(&dir).expect("scratch directory");
66 dir
67}
68
69fn ffmpeg(args: &[&str]) {
70 let out = Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).output().expect("run ffmpeg");
71 assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
72}
73
74fn s(p: &Path) -> &str {
75 p.to_str().unwrap()
76}
77
78fn ffprobe(path: &Path, entries: &str, select: &str) -> String {
79 let out = Command::new("ffprobe")
80 .args(["-v", "error", "-select_streams", select, "-show_entries", entries, "-of", "csv=p=0"])
81 .arg(path)
82 .output()
83 .expect("ffprobe runs");
84 assert!(out.status.success(), "ffprobe reads {}", path.display());
85 String::from_utf8_lossy(&out.stdout).trim().to_owned()
86}
87
88const SINE: &str = "sine=frequency=440:sample_rate=48000:duration=2.4";
89/// Black with a white flash from 1.0 s to 1.2 s (frames 25..30), 2.4 s long.
90const FLASH: &str = "color=c=black:s=352x288:r=25:d=2.4,drawbox=x=0:y=0:w=352:h=288:color=white:t=fill:enable='between(t,1,1.2)'";
91/// A 1 kHz beep over the same 1.0 s to 1.2 s.
92const BEEP: &str = "aevalsrc=exprs='0.8*sin(2*PI*1000*t)*between(t,1,1.2)|0.8*sin(2*PI*1000*t)*between(t,1,1.2)':s=48000:d=2.4";
93
94/// One clip to make and check.
95struct Case {
96 name: &'static str,
97 /// lavfi video source, then the encoder arguments.
98 video: &'static str,
99 vargs: &'static [&'static str],
100 /// `.mov` or `.mkv`.
101 ext: &'static str,
102 codec: Codec,
103 profile: Option<&'static str>,
104 depth: u8,
105 width: u32,
106 frames: u32,
107 /// `Some("tff")` for an interlaced clip, which is deinterlaced and so not compared to ffmpeg.
108 interlaced: Option<&'static str>,
109}
110
111const CARD: &str = "testsrc2=size=352x288:rate=25:duration=2";
112const CARD_TFF: &str = "testsrc2=size=352x288:rate=50:duration=2,interlace=scan=tff";
113const HD: &str = "testsrc2=size=1920x1080:rate=25:duration=1";
114const HD_TFF: &str = "testsrc2=size=1920x1080:rate=50:duration=1,interlace=scan=tff";
115
116const fn prores(name: &'static str, profile: &'static str, args: &'static [&'static str], depth: u8) -> Case {
117 Case { name, video: CARD, vargs: args, ext: "mov", codec: Codec::ProRes, profile: Some(profile), depth, width: 352, frames: 50, interlaced: None }
118}
119
120fn prores_cases() -> Vec<Case> {
121 vec![
122 prores("proxy", "422 Proxy", &["-c:v", "prores_ks", "-profile:v", "0", "-pix_fmt", "yuv422p10le"], 10),
123 prores("lt", "422 LT", &["-c:v", "prores_ks", "-profile:v", "1", "-pix_fmt", "yuv422p10le"], 10),
124 prores("standard", "422", &["-c:v", "prores_ks", "-profile:v", "2", "-pix_fmt", "yuv422p10le"], 10),
125 prores("hq", "422 HQ", &["-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le"], 10),
126 prores("4444", "4444", &["-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", "yuv444p10le"], 12),
127 prores("4444xq", "4444 XQ", &["-c:v", "prores_ks", "-profile:v", "5", "-pix_fmt", "yuv444p10le"], 12),
128 // The alpha plane is dropped (the engine has no alpha path for a video clip); the colour
129 // planes must come out as the opaque 4444 does.
130 prores("4444-alpha", "4444", &["-vf", "format=yuva444p10le", "-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", "yuva444p10le"], 12),
131 Case {
132 name: "hq-interlaced",
133 video: CARD_TFF,
134 vargs: &["-c:v", "prores_ks", "-profile:v", "3", "-flags", "+ildct", "-pix_fmt", "yuv422p10le"],
135 ext: "mov",
136 codec: Codec::ProRes,
137 profile: Some("422 HQ"),
138 depth: 10,
139 width: 352,
140 frames: 50,
141 interlaced: Some("tff"),
142 },
143 ]
144}
145
146fn dnxhd_cases() -> Vec<Case> {
147 let hd = |name, rate: &'static [&'static str], profile, depth| Case {
148 name,
149 video: HD,
150 vargs: rate,
151 ext: "mov",
152 codec: Codec::Dnxhd,
153 profile: Some(profile),
154 depth,
155 width: 1920,
156 frames: 25,
157 interlaced: None,
158 };
159 let hr = |name, args: &'static [&'static str], profile, depth, ext| Case {
160 name,
161 video: CARD,
162 vargs: args,
163 ext,
164 codec: Codec::Dnxhd,
165 profile: Some(profile),
166 depth,
167 width: 352,
168 frames: 50,
169 interlaced: None,
170 };
171 vec![
172 hd("dnxhd-120", &["-c:v", "dnxhd", "-b:v", "120M", "-pix_fmt", "yuv422p"], "DNxHD 120", 8),
173 hd("dnxhd-185x", &["-c:v", "dnxhd", "-b:v", "185M", "-pix_fmt", "yuv422p10le"], "DNxHD 185x", 10),
174 hd("dnxhd-36", &["-c:v", "dnxhd", "-b:v", "36M", "-pix_fmt", "yuv422p"], "DNxHD 36", 8),
175 hr("dnxhr-lb", &["-c:v", "dnxhd", "-profile:v", "dnxhr_lb", "-pix_fmt", "yuv422p"], "DNxHR LB", 8, "mov"),
176 hr("dnxhr-sq", &["-c:v", "dnxhd", "-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"], "DNxHR SQ", 8, "mov"),
177 hr("dnxhr-hq", &["-c:v", "dnxhd", "-profile:v", "dnxhr_hq", "-pix_fmt", "yuv422p"], "DNxHR HQ", 8, "mov"),
178 hr("dnxhr-hqx", &["-c:v", "dnxhd", "-profile:v", "dnxhr_hqx", "-pix_fmt", "yuv422p10le"], "DNxHR HQX", 10, "mov"),
179 hr("dnxhr-444", &["-c:v", "dnxhd", "-profile:v", "dnxhr_444", "-pix_fmt", "yuv444p10le"], "DNxHR 444", 10, "mov"),
180 hr("dnxhr-sq-mkv", &["-c:v", "dnxhd", "-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"], "DNxHR SQ", 8, "mkv"),
181 hr("dnxhr-hqx-mkv", &["-c:v", "dnxhd", "-profile:v", "dnxhr_hqx", "-pix_fmt", "yuv422p10le"], "DNxHR HQX", 10, "mkv"),
182 Case {
183 name: "dnxhd-interlaced",
184 video: HD_TFF,
185 vargs: &["-c:v", "dnxhd", "-b:v", "120M", "-flags", "+ildct", "-pix_fmt", "yuv422p"],
186 ext: "mov",
187 codec: Codec::Dnxhd,
188 profile: Some("DNxHD 120"),
189 depth: 8,
190 width: 1920,
191 frames: 25,
192 interlaced: Some("tff"),
193 },
194 ]
195}
196
197fn mjpeg_cases() -> Vec<Case> {
198 let c = |name, pix: &'static [&'static str], ext| Case {
199 name,
200 video: CARD,
201 vargs: pix,
202 ext,
203 codec: Codec::Mjpeg,
204 profile: None,
205 depth: 8,
206 width: 352,
207 frames: 50,
208 interlaced: None,
209 };
210 vec![
211 c("mjpeg-420-mov", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p"], "mov"),
212 c("mjpeg-422-mov", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj422p"], "mov"),
213 c("mjpeg-420-mkv", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p"], "mkv"),
214 c("mjpeg-422-mkv", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj422p"], "mkv"),
215 ]
216}
217
218/// Makes `case` with a sine track.
219fn make(dir: &Path, case: &Case) -> PathBuf {
220 let out = dir.join(format!("{}.{}", case.name, case.ext));
221 let mut args = vec!["-f", "lavfi", "-i", case.video, "-f", "lavfi", "-i", SINE, "-map", "0:v", "-map", "1:a"];
222 args.extend(case.vargs);
223 args.extend(["-c:a", "aac", "-b:a", "128k", "-shortest", s(&out)]);
224 ffmpeg(&args);
225 out
226}
227
228fn session_frames(path: &Path) -> Vec<engine::decode::Frame> {
229 software(|| DecodeSession::open(path).expect("open").1.into_iter().collect())
230}
231
232/// ffmpeg's decode of the picture, as BGRA at the file's size.
233fn ffmpeg_bgra(path: &Path, width: u32) -> Vec<u8> {
234 // The engine reads an untagged picture as BT.601 up to 576 lines and BT.709 above.
235 // A stream that states its matrix is converted by ffmpeg as stated, as the engine does; an
236 // untagged one is BT.601 to ffmpeg's scaler, and the size rule's BT.709 above 576 lines here.
237 let vf = if width > 854 { "scale=in_color_matrix=bt709:out_color_matrix=bt709" } else { "null" };
238 let out = Command::new("ffmpeg")
239 .args(["-v", "error", "-i"])
240 .arg(path)
241 .args(["-an", "-vf", vf, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "bgra", "-"])
242 .output()
243 .expect("ffmpeg runs");
244 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
245 out.stdout
246}
247
248/// PSNR over the colour bytes of two BGRA frames.
249fn psnr(a: &[u8], b: &[u8]) -> f64 {
250 assert_eq!(a.len(), b.len());
251 let (mut sq, mut n) = (0f64, 0f64);
252 for (p, q) in a.chunks(4).zip(b.chunks(4)) {
253 for k in 0..3 {
254 let d = f64::from(p[k]) - f64::from(q[k]);
255 sq += d * d;
256 n += 1.0;
257 }
258 }
259 if sq == 0.0 { 99.0 } else { 10.0 * (255.0 * 255.0 * n / sq).log10() }
260}
261
262/// Row-to-row luma-ish difference of a BGRA frame: high for a combed (woven) picture.
263fn comb(frame: &[u8], width: usize) -> f64 {
264 let row = width * 4;
265 let rows: Vec<&[u8]> = frame.chunks(row).collect();
266 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();
267 total as f64 / frame.len() as f64
268}
269
270fn export_mp4(source: &Path, out: &Path) {
271 let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display()));
272 let settings = ExportSettings { format: Format::Mp4, ..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/// Probe, decode, seek and export one case.
283fn check(dir: &Path, case: &Case) {
284 let name = case.name;
285 let path = make(dir, case);
286 let fps = 25.0;
287
288 // ---- probe
289 let facts = engine::probe_media(&path);
290 let video = facts.video.as_ref().unwrap_or_else(|| panic!("{name}: no picture"));
291 assert_eq!(video.codec, case.codec, "{name}");
292 assert_eq!(video.width, case.width, "{name}");
293 assert!((video.frame_rate.unwrap() - fps).abs() < 0.01, "{name}: {:?}", video.frame_rate);
294 assert_eq!(video.bit_depth, Some(case.depth), "{name}");
295 assert_eq!(video.profile, case.profile, "{name}");
296 assert_eq!(video.interlaced, case.interlaced, "{name}");
297 let want_secs = f64::from(case.frames) / fps;
298 let secs = facts.duration_secs.expect("a length");
299 assert!((secs - want_secs).abs() <= 1.0 / fps + 1e-6, "{name}: {secs} s");
300 let (meta, demuxer) = Demuxer::open(&path).expect("open");
301 assert_eq!(meta.frame_count, case.frames, "{name}");
302 assert_eq!(demuxer.bit_depth(), case.depth, "{name}");
303 // Every frame is a sync sample.
304 assert_eq!(engine::demux::sync_points(&path).len() as u32, case.frames, "{name}");
305 let streams = AudioSession::probe_streams(&path).expect("streams");
306 assert_eq!(streams.len(), 1, "{name}");
307
308 // ---- pictures
309 let all = session_frames(&path);
310 assert_eq!(all.iter().map(|f| f.index).collect::<Vec<_>>(), (0..case.frames).collect::<Vec<_>>(), "{name}");
311 if case.interlaced.is_none() {
312 let want = ffmpeg_bgra(&path, case.width);
313 let size = all[0].bgra.len();
314 assert_eq!(want.len(), size * all.len(), "{name}: frame count or size differs from ffmpeg's");
315 let mut worst = 99.0f64;
316 for (i, f) in all.iter().enumerate() {
317 worst = worst.min(psnr(&f.bgra, &want[i * size..(i + 1) * size]));
318 }
319 eprintln!("{name}: worst PSNR against ffmpeg {worst:.1} dB");
320 assert!(worst >= MIN_PSNR, "{name}: PSNR {worst:.1} dB");
321 } else {
322 // Woven by the encoder, deinterlaced by us: less row-to-row energy than ffmpeg's woven decode.
323 let want = ffmpeg_bgra(&path, case.width);
324 let size = all[0].bgra.len();
325 let w = all[0].width as usize;
326 let (mut woven, mut ours) = (0.0, 0.0);
327 for n in 5..(case.frames as usize - 5) {
328 woven += comb(&want[n * size..(n + 1) * size], w);
329 ours += comb(&all[n].bgra, w);
330 }
331 eprintln!("{name}: comb woven {woven:.1}, deinterlaced {ours:.1}");
332 assert!(ours < woven, "{name}: the interlaced picture is not deinterlaced");
333 }
334
335 // ---- seeks
336 let n = case.frames;
337 for target in [0, 1, 2, n / 3, n / 2, n - 2, n - 1] {
338 let seeked = software(|| {
339 let (_, rx, _c) = DecodeSession::open_at(&path, target).expect("open_at");
340 rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"))
341 });
342 assert_eq!(seeked.index, target, "{name}");
343 assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential");
344 }
345 let (a, b) = (n / 4, n / 4 + 9);
346 let range = software(|| {
347 let (_, rx, _c) = DecodeSession::open_range(&path, a, b).expect("open_range");
348 rx.into_iter().collect::<Vec<_>>()
349 });
350 assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (a..b).collect::<Vec<_>>(), "{name}");
351 for f in &range {
352 assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index);
353 }
354
355 // ---- export
356 let out = dir.join(format!("{name}.export.mp4"));
357 software(|| export_mp4(&path, &out));
358 let secs: f64 = ffprobe(&out, "format=duration", "v:0").parse().unwrap_or(0.0);
359 assert!((secs - want_secs).abs() < 0.1, "{name}: exported {secs} s");
360 assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), case.frames, "{name}");
361}
362
363#[test]
364fn prores_every_profile_opens_decodes_seeks_and_exports() {
365 if !have(&["prores_ks", "aac"]) {
366 return;
367 }
368 let dir = scratch("prores");
369 for case in prores_cases() {
370 check(&dir, &case);
371 }
372 let _ = std::fs::remove_dir_all(&dir);
373}
374
375#[test]
376fn dnxhd_and_dnxhr_open_decode_seek_and_export() {
377 if !have(&["dnxhd", "aac"]) {
378 return;
379 }
380 let dir = scratch("dnxhd");
381 for case in dnxhd_cases() {
382 check(&dir, &case);
383 }
384 let _ = std::fs::remove_dir_all(&dir);
385}
386
387#[test]
388fn mjpeg_full_range_opens_decodes_seeks_and_exports_from_mov_and_mkv() {
389 if !have(&["mjpeg", "aac"]) {
390 return;
391 }
392 let dir = scratch("mjpeg");
393 for case in mjpeg_cases() {
394 check(&dir, &case);
395 }
396 // The same JPEGs in the two containers are the same pictures.
397 let mov = session_frames(&dir.join("mjpeg-420-mov.mov"));
398 let mkv = session_frames(&dir.join("mjpeg-420-mkv.mkv"));
399 assert_eq!(mov.len(), mkv.len());
400 assert!(psnr(&mov[10].bgra, &mkv[10].bgra) > 40.0, "mov and mkv differ (same source, same encoder)");
401 let _ = std::fs::remove_dir_all(&dir);
402}
403
404// ------------------------------------------------------------ interlaced MJPEG
405
406fn le(v: &[u32]) -> Vec<u8> {
407 v.iter().flat_map(|x| x.to_le_bytes()).collect()
408}
409
410fn chunk(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
411 let mut out = id.to_vec();
412 out.extend((body.len() as u32).to_le_bytes());
413 out.extend(body);
414 if body.len() % 2 == 1 {
415 out.push(0);
416 }
417 out
418}
419
420fn list(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
421 let mut inner = kind.to_vec();
422 inner.extend(body);
423 chunk(b"LIST", &inner)
424}
425
426/// A minimal AVI holding `packets` as MJPG frames at 25 fps: the carrier the two-field packets are
427/// stream-copied out of (ffmpeg's mjpeg encoder cannot make them itself).
428fn write_avi(path: &Path, w: u32, h: u32, packets: &[Vec<u8>]) {
429 let avih = le(&[40_000, 0, 0, 0x10, packets.len() as u32, 0, 1, 1 << 20, w, h, 0, 0, 0, 0]);
430 let mut strh = b"vidsMJPG".to_vec();
431 strh.extend(le(&[0, 0, 0, 1, 25, 0, packets.len() as u32, 1 << 20, 0xffff_ffff, 0]));
432 for v in [0u16, 0, w as u16, h as u16] {
433 strh.extend(v.to_le_bytes());
434 }
435 let mut strf = le(&[40, w, h]);
436 strf.extend(1u16.to_le_bytes());
437 strf.extend(24u16.to_le_bytes());
438 strf.extend(b"MJPG");
439 strf.extend(le(&[w * h * 3, 0, 0, 0, 0]));
440 let mut strl = chunk(b"strh", &strh);
441 strl.extend(chunk(b"strf", &strf));
442 let mut hdrl = chunk(b"avih", &avih);
443 hdrl.extend(list(b"strl", &strl));
444 let mut movi = b"movi".to_vec();
445 let mut idx = Vec::new();
446 for p in packets {
447 idx.extend(b"00dc");
448 idx.extend(le(&[0x10, movi.len() as u32 - 4, p.len() as u32]));
449 movi.extend(chunk(b"00dc", p));
450 }
451 let mut body = b"AVI ".to_vec();
452 body.extend(list(b"hdrl", &hdrl));
453 body.extend(chunk(b"LIST", &movi));
454 body.extend(chunk(b"idx1", &idx));
455 let mut file = b"RIFF".to_vec();
456 file.extend((body.len() as u32).to_le_bytes());
457 file.extend(body);
458 std::fs::write(path, file).unwrap();
459}
460
461/// Two-field MJPEG (one packet = two JPEGs, one per field) in `.mov` (`mjpa`) and `.mkv`: probed
462/// as interlaced, deinterlaced, frame-exact, seekable, and the sound stays with the picture.
463#[test]
464fn interlaced_mjpeg_two_field_packets_open_deinterlace_and_seek() {
465 if !have(&["mjpeg", "aac"]) {
466 return;
467 }
468 let dir = scratch("mjpeg-fields");
469 let fields = dir.join("fields.mjpg");
470 // 25 half-height JPEGs per second from a 50 fields/s card; 60 fields = 30 frames.
471 ffmpeg(&[
472 "-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25", "-frames:v", "60", "-vf", "separatefields",
473 "-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p", "-f", "mjpeg", s(&fields),
474 ]);
475 let raw = std::fs::read(&fields).unwrap();
476 let starts: Vec<usize> = (0..raw.len() - 2).filter(|&i| raw[i..i + 3] == [0xff, 0xd8, 0xff]).collect();
477 assert_eq!(starts.len(), 60);
478 let jpegs: Vec<Vec<u8>> = starts
479 .iter()
480 .enumerate()
481 .map(|(n, &a)| raw[a..starts.get(n + 1).copied().unwrap_or(raw.len())].to_vec())
482 .collect();
483 let packets: Vec<Vec<u8>> = jpegs.chunks(2).map(|c| [c[0].clone(), c[1].clone()].concat()).collect();
484 let avi = dir.join("fields.avi");
485 write_avi(&avi, 352, 288, &packets);
486 for (ext, tag) in [("mov", Some("mjpa")), ("mkv", None)] {
487 let path = dir.join(format!("fields.{ext}"));
488 let mut a = vec!["-i", s(&avi), "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=1.2", "-c:v", "copy", "-c:a", "aac"];
489 if let Some(t) = tag {
490 a.extend(["-tag:v", t]);
491 }
492 a.extend(["-shortest", s(&path)]);
493 ffmpeg(&a);
494 let facts = engine::probe_media(&path);
495 let video = facts.video.as_ref().expect("a picture");
496 assert_eq!(video.codec, Codec::Mjpeg, "{ext}");
497 assert_eq!((video.width, video.height), (352, 288), "{ext}");
498 assert_eq!(video.interlaced, Some("tff"), "{ext}");
499 assert_eq!(video.bit_depth, Some(8), "{ext}");
500 let all = session_frames(&path);
501 assert_eq!(all.len(), 30, "{ext}");
502 assert_eq!((all[0].width, all[0].height), (352, 288), "{ext}");
503 // Deinterlaced: less row-to-row energy than ffmpeg's woven decode.
504 let want = ffmpeg_bgra(&path, 352);
505 let size = all[0].bgra.len();
506 let (mut woven, mut ours) = (0.0, 0.0);
507 for n in 5..25 {
508 woven += comb(&want[n * size..(n + 1) * size], 352);
509 ours += comb(&all[n].bgra, 352);
510 }
511 assert!(ours < woven, "{ext}: not deinterlaced ({ours:.1} vs {woven:.1})");
512 for target in [0u32, 1, 7, 15, 29] {
513 let seeked = software(|| {
514 let (_, rx, _c) = DecodeSession::open_at(&path, target).expect("open_at");
515 rx.into_iter().next().expect("a frame")
516 });
517 assert_eq!(seeked.index, target, "{ext}");
518 assert!(seeked.bgra == all[target as usize].bgra, "{ext}: seek to {target} differs");
519 }
520 let out = dir.join(format!("fields-{ext}.mp4"));
521 software(|| export_mp4(&path, &out));
522 assert_eq!(ffprobe(&out, "stream=nb_frames", "v:0").parse::<u32>().unwrap_or(0), 30, "{ext}");
523 }
524 let _ = std::fs::remove_dir_all(&dir);
525}
526
527// ------------------------------------------------------------ sync
528
529fn sound(path: &Path, from: f64, frames: usize) -> (u32, usize, Vec<f32>) {
530 let (meta, rx) = AudioSession::open_multi_streams(&[(path.to_path_buf(), 0)], &[(Some(0), from, f64::INFINITY)])
531 .expect("open")
532 .expect("the file has sound");
533 let width = usize::from(meta.channels);
534 let mut out = Vec::new();
535 for chunk in rx {
536 out.extend_from_slice(&chunk.samples);
537 if out.len() >= frames * width {
538 break;
539 }
540 }
541 out.truncate(frames * width);
542 (meta.sample_rate, width, out)
543}
544
545fn first_loud(samples: &[f32], width: usize) -> Option<usize> {
546 samples.chunks(width).position(|f| f.iter().any(|s| s.abs() > 0.2))
547}
548
549fn flash_frame(frames: &[engine::decode::Frame]) -> Option<u32> {
550 frames
551 .iter()
552 .find(|f| f.bgra.chunks(4).map(|p| u64::from(p[1])).sum::<u64>() > 128 * (f.bgra.len() as u64 / 4))
553 .map(|f| f.index)
554}
555
556/// The flash is at 1.0 s in the picture and the beep at 1.0 s in the sound, from open, after a
557/// seek in either, and in the export.
558#[test]
559fn picture_and_sound_stay_in_sync_after_open_and_seek() {
560 if !have(&["prores_ks", "dnxhd", "mjpeg", "aac"]) {
561 return;
562 }
563 let dir = scratch("sync");
564 let clips: [(&str, &str, &[&str]); 7] = [
565 ("prores.mov", "mov", &["-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le"]),
566 ("prores-4444.mov", "mov", &["-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", "yuv444p10le"]),
567 ("dnxhr.mov", "mov", &["-c:v", "dnxhd", "-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"]),
568 ("dnxhr.mkv", "mkv", &["-c:v", "dnxhd", "-profile:v", "dnxhr_sq", "-pix_fmt", "yuv422p"]),
569 ("mjpeg.mov", "mov", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p"]),
570 ("mjpeg.mkv", "mkv", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj420p"]),
571 ("mjpeg-422.mov", "mov", &["-c:v", "mjpeg", "-q:v", "3", "-pix_fmt", "yuvj422p"]),
572 ];
573 for (name, _, vargs) in clips {
574 let path = dir.join(name);
575 let mut args = vec!["-f", "lavfi", "-i", FLASH, "-f", "lavfi", "-i", BEEP, "-map", "0:v", "-map", "1:a"];
576 args.extend(vargs);
577 // PCM in Matroska, so a seek lands on the sample and not on an AAC frame boundary (21 ms).
578 let audio: &[&str] = if name.ends_with("mkv") { &["-c:a", "pcm_s16le"] } else { &["-c:a", "aac", "-b:a", "128k"] };
579 args.extend(audio);
580 args.push(s(&path));
581 ffmpeg(&args);
582 let frames = session_frames(&path);
583 assert_eq!(frames.len(), 60, "{name}");
584 assert_eq!(flash_frame(&frames), Some(25), "{name}: the flash is at 1.0 s");
585 let (rate, width, all) = sound(&path, 0.0, 48_000 * 3);
586 let beep = first_loud(&all, width).expect("a beep") as f64 / f64::from(rate);
587 assert!(beep > 0.99 && beep < 1.065, "{name}: the beep is at {beep:.3} s");
588 let (_, _, tail) = sound(&path, 0.8, 48_000);
589 let again = 0.8 + first_loud(&tail, width).expect("a beep after a seek") as f64 / f64::from(rate);
590 assert!((again - beep).abs() < 0.002, "{name}: {again} vs {beep}");
591 let at = software(|| {
592 let (_, rx, _c) = DecodeSession::open_at(&path, 25).expect("seek");
593 rx.into_iter().next().map(|f| f.index)
594 });
595 assert_eq!(at, Some(25), "{name}");
596 // The export keeps them together.
597 let out = dir.join(format!("{name}.mp4"));
598 software(|| export_mp4(&path, &out));
599 let video = Command::new("ffmpeg")
600 .args(["-v", "error", "-i"])
601 .arg(&out)
602 .args(["-an", "-vf", "scale=8:8,format=gray", "-fps_mode", "passthrough", "-f", "rawvideo", "-"])
603 .output()
604 .expect("ffmpeg");
605 let flash = video.stdout.chunks(64).position(|f| f.iter().map(|&b| u32::from(b)).sum::<u32>() > 128 * 64).expect("a flash");
606 let pcm = Command::new("ffmpeg")
607 .args(["-v", "error", "-i"])
608 .arg(&out)
609 .args(["-vn", "-ac", "2", "-ar", "48000", "-f", "f32le", "-"])
610 .output()
611 .expect("ffmpeg");
612 let samples: Vec<f32> = pcm.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
613 let beep_out = first_loud(&samples, 2).expect("a beep") as f64 / 48_000.0;
614 let flash_at = flash as f64 / 25.0;
615 assert!((flash_at - 1.0).abs() < 0.045, "{name}: exported flash at {flash_at}");
616 assert!((beep_out - flash_at).abs() < 0.09, "{name}: exported beep {beep_out} vs flash {flash_at}");
617 }
618 let _ = std::fs::remove_dir_all(&dir);
619}
620
621/// ProRes cannot ride in Matroska here (ec-matroska maps no ProRes id): the gap is a named
622/// refusal, not a mis-decode. DNxHD and MJPEG do open from both containers (above).
623#[test]
624fn prores_in_matroska_is_a_named_gap() {
625 if !have(&["prores_ks"]) {
626 return;
627 }
628 let dir = scratch("prores-mkv");
629 let path = dir.join("p.mkv");
630 ffmpeg(&["-f", "lavfi", "-i", CARD, "-c:v", "prores_ks", "-profile:v", "3", s(&path)]);
631 let err = Demuxer::open(&path).err().map(|e| e.to_string()).unwrap_or_default();
632 eprintln!("prores in mkv: {err}");
633 assert!(!err.is_empty(), "ProRes in Matroska opened, update the capability matrix");
634 let _ = std::fs::remove_dir_all(&dir);
635}