forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

interlaced_h264.rs589 lines, 23.9 KiBHistoryRawDownload
1//! Interlaced H.264 (x264 MBAFF, 8-bit and High 10, mp4 and mkv) end to end:
2//! what the probe reports, that `ec-h264`'s woven pictures are ffmpeg's byte for
3//! byte, how close the engine's deinterlacer comes to ffmpeg's `bwdif` and
4//! `yadif` against the progressive original, that a mid-GOP seek equals a
5//! sequential decode, that a progressive source is untouched, that an export is
6//! progressive with its frame count, and that High 4:2:2 is still refused.
7//!
8//! Clips are synthetic (`testsrc2`, and a moving edge made with `geq`),
9//! interlaced by ffmpeg's `interlace` filter (two source moments per frame) and
10//! encoded by libx264 into the temp dir; without ffmpeg and libx264 each test
11//! says so and passes. `VE_SW` is process-wide, so tests that pin it hold [`SW`].
12
13use std::path::{Path, PathBuf};
14use std::process::Command;
15use std::sync::Mutex;
16use std::time::{Duration, Instant};
17
18use ec_core::frame::{Frame as CoreFrame, Interlace, PixelFormat};
19use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
20use ec_core::{Packet, TimeBase, VideoFrame};
21use ec_h264::H264Decoder;
22use engine::PlaybackSession;
23use engine::decode::DecodeSession;
24use engine::deinterlace::Deinterlacer;
25use engine::demux::Demuxer;
26use engine::export::{ExportSettings, Format};
27
28const W: usize = 352;
29const H: usize = 288;
30/// Interlaced frames; the source has twice as many progressive ones.
31const FRAMES: u32 = 30;
32
33static SW: Mutex<()> = Mutex::new(());
34
35fn software<T>(f: impl FnOnce() -> T) -> T {
36 let _guard = SW.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
37 engine::envcfg::set("VE_SW", "1");
38 let out = f();
39 engine::envcfg::unset("VE_SW");
40 out
41}
42
43fn have_x264() -> bool {
44 let tool = |t: &str, a: &str| Command::new(t).arg(a).output().is_ok_and(|o| o.status.success());
45 if !tool("ffmpeg", "-version") || !tool("ffprobe", "-version") {
46 return false;
47 }
48 Command::new("ffmpeg")
49 .args(["-hide_banner", "-encoders"])
50 .output()
51 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("libx264"))
52}
53
54fn scratch(name: &str) -> PathBuf {
55 let dir = std::env::temp_dir().join(format!("edith-{name}-{}", std::process::id()));
56 let _ = std::fs::remove_dir_all(&dir);
57 std::fs::create_dir_all(&dir).expect("scratch directory");
58 dir
59}
60
61fn ffmpeg(args: &[&str]) {
62 let out = Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).output().expect("run ffmpeg");
63 assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
64}
65
66/// What a clip is made of.
67#[derive(Clone, Copy)]
68struct Look {
69 /// A lavfi source at 50 progressive frames a second.
70 source: &'static str,
71 /// Top field first (else bottom).
72 tff: bool,
73 /// 10-bit High 10 (else 8-bit High).
74 deep: bool,
75 /// High 4:2:2 (else 4:2:0).
76 c422: bool,
77}
78
79const TESTSRC: &str = "testsrc2=size=352x288:rate=50";
80/// A hard vertical edge moving 8 pixels per source moment: the worst case for
81/// combing.
82const EDGE: &str = "nullsrc=size=352x288:rate=50,format=yuv420p,geq=lum='if(lt(X,20+8*N),230,25)':cb=128:cr=128";
83
84impl Look {
85 fn pix(self) -> &'static str {
86 match (self.c422, self.deep) {
87 (false, false) => "yuv420p",
88 (false, true) => "yuv420p10le",
89 (true, false) => "yuv422p",
90 (true, true) => "yuv422p10le",
91 }
92 }
93
94 /// Bytes of one raw frame.
95 fn frame_bytes(self) -> usize {
96 W * H * if self.c422 { 2 } else { 3 } / if self.c422 { 1 } else { 2 } * if self.deep { 2 } else { 1 }
97 }
98}
99
100/// The progressive original (`ref`, raw, every other source moment: the one the
101/// kept field belongs to) and the interlaced clip `name`.
102fn make(dir: &Path, name: &str, look: Look) -> (PathBuf, PathBuf) {
103 let src = dir.join(format!("{name}.src.y4m"));
104 ffmpeg(&[
105 "-f", "lavfi", "-i", look.source, "-frames:v", &(FRAMES * 2).to_string(), "-pix_fmt", if look.c422 { "yuv422p" } else { "yuv420p" },
106 src.to_str().unwrap(),
107 ]);
108 let reference = dir.join(format!("{name}.ref.yuv"));
109 // Source moment 2n belongs to interlaced frame n whichever field leads: a
110 // top-first frame is lines of 2n over lines of 2n+1, a bottom-first one the
111 // other way round, and the field that leads is the one a frame-rate
112 // deinterlacer keeps.
113 ffmpeg(&[
114 "-i",
115 src.to_str().unwrap(),
116 "-vf",
117 "select=not(mod(n\\,2))",
118 "-fps_mode",
119 "passthrough",
120 "-f",
121 "rawvideo",
122 "-pix_fmt",
123 look.pix(),
124 reference.to_str().unwrap(),
125 ]);
126 let clip = dir.join(name);
127 let scan = if look.tff { "tff" } else { "bff" };
128 let params = format!("interlaced=1:{}=1:keyint=10:min-keyint=10:bframes=2", scan);
129 let profile = match (look.c422, look.deep) {
130 (true, _) => "high422",
131 (false, true) => "high10",
132 (false, false) => "high",
133 };
134 ffmpeg(&[
135 "-i",
136 src.to_str().unwrap(),
137 "-vf",
138 &format!("interlace=scan={scan}"),
139 "-c:v",
140 "libx264",
141 "-profile:v",
142 profile,
143 "-pix_fmt",
144 look.pix(),
145 "-crf",
146 "10",
147 "-flags",
148 "+ildct+ilme",
149 "-x264-params",
150 &params,
151 clip.to_str().unwrap(),
152 ]);
153 (clip, reference)
154}
155
156/// Every picture ec-h264 releases for `clip`, woven, in display order.
157fn decode_all(clip: &Path) -> Vec<VideoFrame> {
158 let (_, mut demuxer) = Demuxer::open(clip).expect("open");
159 demuxer.seek_to_sync_at_or_before(0);
160 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("decoder");
161 let mut out = Vec::new();
162 let take = |decoder: &mut H264Decoder, out: &mut Vec<VideoFrame>| {
163 while let Ok(frame) = decoder.receive_frame() {
164 if let CoreFrame::Video(pic) = frame {
165 out.push(pic);
166 }
167 }
168 };
169 while let Some(au) = demuxer.next_access_unit().expect("demux") {
170 decoder.send_packet(&Packet::new(0, TimeBase::new(1, 1), au)).expect("decode");
171 take(&mut decoder, &mut out);
172 }
173 decoder.flush().expect("flush");
174 take(&mut decoder, &mut out);
175 out
176}
177
178fn raw(pics: &[VideoFrame]) -> Vec<u8> {
179 let mut out = Vec::new();
180 for pic in pics {
181 for plane in &pic.planes {
182 out.extend_from_slice(&plane.data);
183 }
184 }
185 out
186}
187
188fn ffmpeg_raw(args: &[&str], path: &Path, pix_fmt: &str) -> Vec<u8> {
189 let out = Command::new("ffmpeg")
190 .args(["-v", "error", "-i"])
191 .arg(path)
192 .args(args)
193 .args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt, "-"])
194 .output()
195 .expect("ffmpeg runs");
196 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
197 out.stdout
198}
199
200/// PSNR over every plane of every frame; `deep` reads 16-bit samples at 10 bits.
201fn psnr(a: &[u8], b: &[u8], deep: bool) -> f64 {
202 assert_eq!(a.len(), b.len(), "the same number of samples");
203 let (mut squared, n) = (0f64, if deep { a.len() / 2 } else { a.len() });
204 if deep {
205 for (x, y) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) {
206 let d = f64::from(u16::from_le_bytes(*x)) - f64::from(u16::from_le_bytes(*y));
207 squared += d * d;
208 }
209 } else {
210 for (x, y) in a.iter().zip(b) {
211 let d = f64::from(*x) - f64::from(*y);
212 squared += d * d;
213 }
214 }
215 if squared == 0.0 {
216 return f64::INFINITY;
217 }
218 let peak = if deep { 1023.0f64 } else { 255.0 };
219 10.0 * (peak * peak * n as f64 / squared).log10()
220}
221
222/// Combing: the share of luma pixels that are an extreme against both vertical
223/// neighbours, in the same direction, by more than 20 steps (a feather edge
224/// between two fields of a moving object does exactly this; a vertical edge
225/// and smooth shading do not).
226fn combing(luma: &[u8], width: usize, height: usize, deep: bool) -> f64 {
227 let sample = |x: usize, y: usize| -> i32 {
228 if deep {
229 let i = (y * width + x) * 2;
230 i32::from(u16::from_le_bytes([luma[i], luma[i + 1]])) >> 2
231 } else {
232 i32::from(luma[y * width + x])
233 }
234 };
235 let mut hits = 0u64;
236 for y in 1..height - 1 {
237 for x in 0..width {
238 let (a, b, c) = (sample(x, y - 1), sample(x, y), sample(x, y + 1));
239 if ((b - a) > 20 && (b - c) > 20) || ((a - b) > 20 && (c - b) > 20) {
240 hits += 1;
241 }
242 }
243 }
244 hits as f64 / (width * (height - 2)) as f64
245}
246
247/// The luma planes of a raw run of frames, one `Vec` per frame.
248fn lumas(raw: &[u8], look: Look) -> Vec<&[u8]> {
249 let bytes = if look.deep { 2 } else { 1 };
250 raw.chunks(look.frame_bytes()).map(|f| &f[..W * H * bytes]).collect()
251}
252
253fn combing_of(raw: &[u8], look: Look) -> f64 {
254 let l = lumas(raw, look);
255 l.iter().map(|y| combing(y, W, H, look.deep)).sum::<f64>() / l.len() as f64
256}
257
258fn deinterlaced(pics: Vec<VideoFrame>) -> Vec<VideoFrame> {
259 let mut stage = Deinterlacer::new(true, 0, Interlace::Progressive);
260 let mut out = Vec::new();
261 for (i, pic) in pics.into_iter().enumerate() {
262 out.extend(stage.push(i as i64, pic).map(|(_, f)| f));
263 }
264 out.extend(stage.finish().map(|(_, f)| f));
265 out
266}
267
268const LOOKS: [(&str, Look); 8] = [
269 ("t8-tff.mp4", Look { source: TESTSRC, tff: true, deep: false, c422: false }),
270 ("t8-bff.mkv", Look { source: TESTSRC, tff: false, deep: false, c422: false }),
271 ("t10-tff.mp4", Look { source: TESTSRC, tff: true, deep: true, c422: false }),
272 ("t10-bff.mkv", Look { source: TESTSRC, tff: false, deep: true, c422: false }),
273 ("t422-tff.mp4", Look { source: TESTSRC, tff: true, deep: false, c422: true }),
274 ("t422-10-bff.mkv", Look { source: TESTSRC, tff: false, deep: true, c422: true }),
275 ("t422-10-tff.mp4", Look { source: TESTSRC, tff: true, deep: true, c422: true }),
276 ("e8-tff.mp4", Look { source: EDGE, tff: true, deep: false, c422: false }),
277];
278
279#[test]
280fn probe_reports_interlace_and_field_order() {
281 if !have_x264() {
282 eprintln!("no ffmpeg with libx264: skipping");
283 return;
284 }
285 let dir = scratch("il-probe");
286 for (name, look) in LOOKS {
287 let (clip, _) = make(&dir, name, look);
288 let facts = engine::probe_media(&clip).video.expect("a picture track");
289 assert_eq!(facts.interlaced, Some(if look.tff { "tff" } else { "bff" }), "{name}");
290 assert_eq!(facts.bit_depth, look.deep.then_some(10), "{name}");
291 if look.c422 {
292 assert_eq!(facts.profile, Some("High 4:2:2"), "{name}");
293 }
294 let (meta, demuxer) = Demuxer::open(&clip).expect("interlaced opens, High 10 too");
295 assert_eq!(meta.frame_count, FRAMES, "{name}");
296 assert!(demuxer.h264_interlaced(), "{name}");
297 }
298 // A progressive stream says nothing.
299 let prog = dir.join("p.mp4");
300 ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25", "-frames:v", "10", "-c:v", "libx264", prog.to_str().unwrap()]);
301 assert_eq!(engine::probe_media(&prog).video.expect("video").interlaced, None);
302 let _ = std::fs::remove_dir_all(&dir);
303}
304
305#[test]
306fn software_pictures_are_ffmpegs_before_deinterlacing() {
307 if !have_x264() {
308 eprintln!("no ffmpeg with libx264: skipping");
309 return;
310 }
311 let dir = scratch("il-exact");
312 for (name, look) in LOOKS {
313 let (clip, _) = make(&dir, name, look);
314 let pics = decode_all(&clip);
315 assert_eq!(pics.len(), FRAMES as usize, "{name}");
316 let want_order = if look.tff { Interlace::TopFieldFirst } else { Interlace::BottomFieldFirst };
317 assert!(
318 pics.iter().all(|p| p.interlace == want_order || p.interlace == Interlace::Progressive),
319 "{name}: pictures state the wrong order"
320 );
321 let format = match (look.c422, look.deep) {
322 (false, false) => PixelFormat::I420,
323 (false, true) => PixelFormat::I010,
324 (true, false) => PixelFormat::I422,
325 (true, true) => PixelFormat::I210,
326 };
327 assert_eq!(pics[0].format, format, "{name}");
328 let want = ffmpeg_raw(&[], &clip, look.pix());
329 assert!(raw(&pics) == want, "{name}: woven pictures differ from ffmpeg's");
330 }
331 let _ = std::fs::remove_dir_all(&dir);
332}
333
334/// The PSNR table: woven, this engine's filter, ffmpeg's bwdif and yadif,
335/// each against the progressive original.
336#[test]
337fn deinterlaced_psnr_is_within_half_a_db_of_bwdif() {
338 if !have_x264() {
339 eprintln!("no ffmpeg with libx264: skipping");
340 return;
341 }
342 let dir = scratch("il-psnr");
343 for (name, look) in LOOKS {
344 let (clip, reference) = make(&dir, name, look);
345 let want = std::fs::read(&reference).expect("reference");
346 let pics = decode_all(&clip);
347 let woven = raw(&pics);
348 let ours = raw(&deinterlaced(pics));
349 let parity = if look.tff { "tff" } else { "bff" };
350 let bwdif = ffmpeg_raw(&["-vf", &format!("bwdif=mode=send_frame:parity={parity}:deint=all")], &clip, look.pix());
351 let yadif = ffmpeg_raw(&["-vf", &format!("yadif=mode=send_frame:parity={parity}:deint=all")], &clip, look.pix());
352 let p = |x: &[u8]| psnr(&want, x, look.deep);
353 let (pw, po, pb, py) = (p(&woven), p(&ours), p(&bwdif), p(&yadif));
354 let c = |x: &[u8]| combing_of(x, look);
355 eprintln!(
356 "PSNR {name}: woven {pw:.2} dB, ours {po:.2} dB, bwdif {pb:.2} dB, yadif {py:.2} dB | combing woven {:.5}, ours {:.5}, bwdif {:.5}, yadif {:.5}, original {:.5}",
357 c(&woven),
358 c(&ours),
359 c(&bwdif),
360 c(&yadif),
361 c(&want),
362 );
363 assert!(po > pb - 0.5, "{name}: ours {po:.2} dB is not within 0.5 dB of bwdif {pb:.2} dB");
364 assert!(po > pw + 1.0, "{name}: ours {po:.2} dB is not clearly above woven {pw:.2} dB");
365 assert!(c(&ours) < c(&woven) * 0.25 + 1e-6, "{name}: still combed");
366 }
367 let _ = std::fs::remove_dir_all(&dir);
368}
369
370#[test]
371fn session_frames_are_deinterlaced_and_seeks_match_a_sequential_decode() {
372 if !have_x264() {
373 eprintln!("no ffmpeg with libx264: skipping");
374 return;
375 }
376 let dir = scratch("il-seek");
377 for (name, look) in LOOKS {
378 let (clip, _) = make(&dir, name, look);
379 let (meta, all) = software(|| {
380 let (meta, rx) = DecodeSession::open(&clip).expect("open");
381 (meta, rx.into_iter().collect::<Vec<_>>())
382 });
383 assert_eq!(meta.frame_count, FRAMES, "{name}");
384 assert_eq!(
385 all.iter().map(|f| f.index).collect::<Vec<_>>(),
386 (0..FRAMES).collect::<Vec<_>>(),
387 "{name}: display order"
388 );
389 // The session's frames are the filter's, not the woven pictures: the
390 // BGRA of each is the conversion of the deinterlaced planes, so its
391 // combing (read off green, which carries most of the luma) is the
392 // filtered picture's, far under the woven one's on the moving edge.
393 if name.starts_with("e8") {
394 let green = |f: &engine::decode::Frame| -> Vec<u8> { f.bgra.chunks(4).map(|p| p[1]).collect() };
395 let session: f64 = all.iter().map(|f| combing(&green(f), W, H, false)).sum::<f64>() / all.len() as f64;
396 let woven = combing_of(&raw(&decode_all(&clip)), look);
397 assert!(session < woven * 0.25, "{name}: session combing {session:.5} vs woven {woven:.5}");
398 }
399 for target in [0, 1, 2, 5, 9, 10, 11, 13, 17, 20, 25, FRAMES - 1] {
400 let seeked = software(|| {
401 let (_, rx, _cancel) = DecodeSession::open_at(&clip, target).expect("open_at");
402 rx.into_iter().next().unwrap_or_else(|| panic!("{name}: no frame after seek to {target}"))
403 });
404 assert_eq!(seeked.index, target, "{name}");
405 assert!(seeked.bgra == all[target as usize].bgra, "{name}: seek to {target} differs from sequential");
406 }
407 // A range that ends mid-stream still has its last picture filtered
408 // against the one after it.
409 let range = software(|| {
410 let (_, rx, _cancel) = DecodeSession::open_range(&clip, 6, 14).expect("open_range");
411 rx.into_iter().collect::<Vec<_>>()
412 });
413 assert_eq!(range.iter().map(|f| f.index).collect::<Vec<_>>(), (6..14).collect::<Vec<_>>(), "{name}");
414 for f in &range {
415 assert!(f.bgra == all[f.index as usize].bgra, "{name}: range frame {} differs", f.index);
416 }
417 }
418 let _ = std::fs::remove_dir_all(&dir);
419}
420
421#[test]
422fn a_progressive_source_decodes_untouched() {
423 if !have_x264() {
424 eprintln!("no ffmpeg with libx264: skipping");
425 return;
426 }
427 let dir = scratch("il-prog");
428 let clip = dir.join("p.mp4");
429 ffmpeg(&[
430 "-f", "lavfi", "-i", "testsrc2=size=352x288:rate=30", "-frames:v", "30", "-c:v", "libx264", "-x264-params",
431 "keyint=10:min-keyint=10:bframes=2", clip.to_str().unwrap(),
432 ]);
433 let (_, demuxer) = Demuxer::open(&clip).expect("open");
434 assert!(!demuxer.h264_interlaced());
435 // The stage is a pass-through for it: the same picture back at once.
436 let pics = decode_all(&clip);
437 let mut stage = Deinterlacer::new(false, 0, Interlace::Progressive);
438 for (i, pic) in pics.iter().enumerate() {
439 let (tag, same) = stage.push(i as i64, pic.clone()).expect("no delay");
440 assert_eq!(tag, i as i64);
441 assert!(&same == pic);
442 }
443 // A hash of the whole decode, for comparing builds by hand.
444 let frames = software(|| DecodeSession::open(&clip).expect("open").1.into_iter().collect::<Vec<_>>());
445 let mut hash = 0xcbf29ce484222325u64;
446 for f in &frames {
447 for b in &f.bgra {
448 hash = (hash ^ u64::from(*b)).wrapping_mul(0x100000001b3);
449 }
450 }
451 eprintln!("progressive decode hash {hash:016x} over {} frames", frames.len());
452 let _ = std::fs::remove_dir_all(&dir);
453}
454
455fn ffprobe_field(path: &Path, field: &str) -> String {
456 let out = Command::new("ffprobe")
457 .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
458 .arg(format!("stream={field}"))
459 .args(["-of", "csv=p=0"])
460 .arg(path)
461 .output()
462 .expect("ffprobe runs");
463 assert!(out.status.success(), "ffprobe reads {}", path.display());
464 String::from_utf8_lossy(&out.stdout).trim().to_owned()
465}
466
467fn export_as(source: &Path, out: &Path, format: Format) {
468 let session = PlaybackSession::open(source).unwrap_or_else(|e| panic!("open {}: {e}", source.display()));
469 let settings = ExportSettings { format, ..Default::default() };
470 let handle = session.export_to_with(out, &settings);
471 let started = Instant::now();
472 while !handle.is_finished() {
473 assert!(started.elapsed() < Duration::from_secs(600), "the export did not finish in 600 s");
474 std::thread::sleep(Duration::from_millis(20));
475 }
476 handle.result().expect("an outcome").expect("the export");
477}
478
479#[test]
480fn an_interlaced_source_exports_progressive() {
481 if !have_x264() {
482 eprintln!("no ffmpeg with libx264: skipping");
483 return;
484 }
485 let dir = scratch("il-export");
486 for (name, look) in [LOOKS[0], LOOKS[1], LOOKS[2], LOOKS[4], LOOKS[5], LOOKS[7]] {
487 let (clip, reference) = make(&dir, name, look);
488 let want = std::fs::read(&reference).expect("reference");
489 for (format, ext) in [(Format::Mp4, "mp4"), (Format::HevcMp4, "hevc.mp4"), (Format::Hevc, "mkv")] {
490 let out = dir.join(format!("{name}-out.{ext}"));
491 software(|| export_as(&clip, &out, format));
492 let field = ffprobe_field(&out, "field_order");
493 assert!(field == "progressive" || field == "unknown" || field == "N/A", "{name}.{ext}: field_order {field}");
494 if look.deep && format != Format::Mp4 {
495 assert_eq!(ffprobe_field(&out, "pix_fmt"), "yuv420p10le", "{name}.{ext}: 10 bits kept");
496 }
497 let decoded = ffmpeg_raw(&[], &out, look.pix());
498 let frame = look.frame_bytes();
499 assert_eq!(decoded.len() / frame, FRAMES as usize, "{name}.{ext}: every frame, no more");
500 let secs: f64 = {
501 let o = Command::new("ffprobe")
502 .args(["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0"])
503 .arg(&out)
504 .output()
505 .expect("ffprobe runs");
506 String::from_utf8_lossy(&o.stdout).trim().parse().unwrap_or(0.0)
507 };
508 assert!((secs - f64::from(FRAMES) / 25.0).abs() < 0.1, "{name}.{ext}: {secs} s");
509 // Progressive in content too: far less combing than the woven
510 // source, and a good match to the original.
511 let woven = combing_of(&raw(&decode_all(&clip)), look);
512 let exported = combing_of(&decoded, look);
513 let db = psnr(&want, &decoded, look.deep);
514 eprintln!("export {name}.{ext}: field_order {field}, combing {exported:.5} (woven {woven:.5}), {db:.2} dB vs original");
515 assert!(exported <= woven * 0.5 + 1e-6, "{name}.{ext}: combing {exported:.5} vs woven {woven:.5}");
516 }
517 }
518 let _ = std::fs::remove_dir_all(&dir);
519}
520
521#[test]
522fn four_four_four_monochrome_and_lossless_open_and_keep_the_gpu_off() {
523 if !have_x264() {
524 eprintln!("no ffmpeg with libx264: skipping");
525 return;
526 }
527 let dir = scratch("il-open");
528 let cases: [(&str, &str, &str, &str, engine::colorspace::Chroma); 5] = [
529 ("a.mp4", "high444", "yuv444p", "interlaced=1:tff=1", engine::colorspace::Chroma::C444),
530 ("b.mkv", "high444", "yuv444p10le", "interlaced=1:tff=1", engine::colorspace::Chroma::C444),
531 ("c.mp4", "high444", "yuv444p10le", "keyint=5", engine::colorspace::Chroma::C444),
532 ("d.mp4", "high", "gray", "keyint=5", engine::colorspace::Chroma::Gray),
533 ("e.mkv", "high444", "yuv420p", "qp=0", engine::colorspace::Chroma::C420),
534 ];
535 for (name, profile, pix, params, chroma) in cases {
536 let clip = dir.join(name);
537 let out = Command::new("ffmpeg")
538 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=352x288:rate=25", "-frames:v", "10", "-c:v", "libx264"])
539 .args(["-profile:v", profile, "-pix_fmt", pix, "-x264-params", params])
540 .arg(&clip)
541 .output()
542 .expect("ffmpeg runs");
543 if !out.status.success() {
544 eprintln!("{name}: this libx264 cannot make {pix}: skipping the case");
545 continue;
546 }
547 let (meta, demuxer) = Demuxer::open(&clip).unwrap_or_else(|e| panic!("{name}: {e}"));
548 assert_eq!(meta.frame_count, 10, "{name}");
549 assert_eq!(demuxer.chroma(), Some(chroma), "{name}");
550 let (_, backend) = engine::decode::probe(&clip).expect("probe");
551 assert_eq!(backend, engine::decode::Backend::Software, "{name}: never offered to VA-API");
552 }
553 let _ = std::fs::remove_dir_all(&dir);
554}
555
556/// Speed of the filter alone at 1080 lines, for the report.
557#[test]
558fn deinterlace_speed_at_1080() {
559 let mut frames = Vec::new();
560 for k in 0..3usize {
561 let mut f = VideoFrame::alloc(PixelFormat::I420, 1920, 1080);
562 for (i, plane) in f.planes.iter_mut().enumerate() {
563 let stride = plane.stride;
564 let data: Vec<u8> = (0..plane.data.len())
565 .map(|n| (((n % stride) * 5 + (n / stride) * 3 + k * 17 + i * 31) ^ (((n / stride) & 1) * (k * 9))) as u8)
566 .collect();
567 *plane = ec_core::Plane::new(data, stride);
568 }
569 frames.push(f);
570 }
571 let run = |threads: usize| {
572 let n = 30;
573 let started = Instant::now();
574 let mut keep = 0usize;
575 for _ in 0..n {
576 let out = engine::deinterlace::filter_frame(
577 &frames[0],
578 &frames[1],
579 &frames[2],
580 engine::deinterlace::Keep::Top,
581 threads,
582 );
583 keep += usize::from(out.planes[0].data[1920 * 3]);
584 }
585 std::hint::black_box(keep);
586 f64::from(n) / started.elapsed().as_secs_f64()
587 };
588 eprintln!("deinterlace 1080: {:.1} fps on 1 thread, {:.1} fps on 4 threads", run(1), run(4));
589}