forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ffmpeg_parity.rs164 lines, 5.8 KiBHistoryRawDownload
1//! Our DVB subtitle decode against ffmpeg's (sub2video frames: `[0:s:0]` out as raw RGBA).
2//!
3//! Fixtures are tiny files made by `scripts/gen-bitmap-sub-fixtures.sh` from a synthetic
4//! 720x576 PGS source (four cues). ffmpeg is the oracle; without it the tests skip loudly, and
5//! with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg fails.
6
7use std::fs::File;
8use std::io::BufReader;
9use std::path::PathBuf;
10use std::process::Command;
11
12use ec_core::{Decoder, Demuxer, Error};
13use ec_dvbsub::DvbSubDecoder;
14
15fn data(name: &str) -> PathBuf {
16 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name)
17}
18
19struct Oracle {
20 /// (pts seconds, rgba) per ffmpeg frame, blank ones included.
21 frames: Vec<(f64, Vec<u8>)>,
22}
23
24fn oracle(path: &PathBuf, w: usize, h: usize) -> Option<Oracle> {
25 let out = Command::new("ffmpeg")
26 .args(["-v", "info", "-nostdin", "-canvas_size", &format!("{w}x{h}"), "-i"])
27 .arg(path)
28 .args([
29 "-filter_complex",
30 "[0:s:0]showinfo[s]",
31 "-map",
32 "[s]",
33 "-fps_mode",
34 "passthrough",
35 "-f",
36 "rawvideo",
37 "-pix_fmt",
38 "rgba",
39 "-",
40 ])
41 .output();
42 let out = match out {
43 Ok(o) => o,
44 Err(_) => {
45 assert!(
46 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
47 "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
48 );
49 eprintln!("SKIP: ffmpeg not installed");
50 return None;
51 }
52 };
53 assert!(out.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
54 let text = String::from_utf8_lossy(&out.stderr);
55 let times: Vec<f64> = text
56 .lines()
57 .filter(|l| l.contains("showinfo") && l.contains(" n:"))
58 .filter_map(|l| l.split("pts_time:").nth(1)?.split_whitespace().next()?.parse().ok())
59 .collect();
60 let fsize = w * h * 4;
61 assert_eq!(out.stdout.len(), times.len() * fsize, "frame count mismatch");
62 Some(Oracle {
63 frames: times
64 .iter()
65 .enumerate()
66 .map(|(i, &t)| (t, out.stdout[i * fsize..(i + 1) * fsize].to_vec()))
67 .collect(),
68 })
69}
70
71fn blank(f: &[u8]) -> bool {
72 f.chunks(4).all(|p| p[3] == 0)
73}
74
75
76/// (rgba, start s, end s) per non-empty display set.
77fn run_packets(d: &mut dyn Demuxer, stream: u32) -> Vec<(Vec<u8>, f64, Option<f64>)> {
78 let mut dec = DvbSubDecoder::new();
79 let mut out = Vec::new();
80 loop {
81 match d.next_packet() {
82 Ok(p) if p.stream == stream => {
83 let pts = p.pts.expect("subtitle packets carry pts") as f64 * p.time_base.num() as f64
84 / p.time_base.den() as f64;
85 dec.send_packet(&p).unwrap();
86 while let Some(c) = dec.take_cue() {
87 if c.empty {
88 continue;
89 }
90 out.push((
91 c.frame.planes[0].data.to_vec(),
92 pts,
93 Some(pts + f64::from(c.timeout_ms) / 1000.0),
94 ));
95 }
96 }
97 Ok(_) => {}
98 Err(Error::Eof) => break,
99 Err(e) => panic!("{e}"),
100 }
101 }
102 out
103}
104
105/// Our non-empty sets against ffmpeg's non-blank frames. Times are compared as offsets from the
106/// first cue (the files differ in muxing delay); ends only when the oracle shows a following
107/// frame, with ffmpeg's own clear-frame time (it also applies the page timeout).
108fn compare(ours: &[(Vec<u8>, f64, Option<f64>)], o: &Oracle, what: &str) {
109 let mut shown: Vec<usize> = Vec::new();
110 for i in 0..o.frames.len() {
111 // sub2video repeats the current picture; one cue is the first frame of a run.
112 let repeat = i > 0 && o.frames[i].1 == o.frames[i - 1].1;
113 if !blank(&o.frames[i].1) && !repeat {
114 shown.push(i);
115 }
116 }
117 assert_eq!(shown.len(), ours.len(), "{what}: cue count");
118 assert!(ours.len() >= 4, "{what}: expected the four fixture cues");
119 let off = ours[0].1 - o.frames[shown[0]].0;
120 for (k, &i) in shown.iter().enumerate() {
121 let (px, start, _end) = &ours[k];
122 let (t, theirs) = &o.frames[i];
123 assert!((start - off - t).abs() < 0.002, "{what}: cue {k} start {start} vs ffmpeg {t}");
124 let mut diff = 0;
125 let mut maxd = 0i32;
126 for (a, b) in px.chunks(4).zip(theirs.chunks(4)) {
127 if a[3] != b[3] {
128 diff += 1;
129 } else if a[3] != 0 {
130 let d = (0..3).map(|c| (i32::from(a[c]) - i32::from(b[c])).abs()).max().unwrap();
131 maxd = maxd.max(d);
132 if d != 0 {
133 diff += 1;
134 }
135 }
136 }
137 eprintln!("{what}: cue {k}: {diff} differing pixels, max channel delta {maxd}");
138 assert_eq!(diff, 0, "{what}: cue {k} differs in {diff} pixels (max delta {maxd})");
139 }
140}
141
142#[test]
143fn mkv_dvbsub_matches_ffmpeg() {
144 let path = data("dvb.mkv");
145 let Some(o) = oracle(&path, 720, 576) else { return };
146 let mut d = ec_matroska::MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
147 assert_eq!(d.streams()[0].params.codec, ec_core::CodecId::DvbSub);
148 let ours = run_packets(&mut d, 0);
149 compare(&ours, &o, "mkv");
150}
151
152#[test]
153fn ts_private_pes_matches_ffmpeg() {
154 let path = data("dvb.ts");
155 let Some(o) = oracle(&path, 720, 576) else { return };
156 let mut d = ec_mpegts::TsDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();
157 let sub = d
158 .streams()
159 .iter()
160 .position(|s| s.params.codec == ec_core::CodecId::DvbSub)
161 .expect("the 0x06 + subtitling-descriptor stream is a DvbSub stream") as u32;
162 let ours = run_packets(&mut d, sub);
163 compare(&ours, &o, "ts");
164}