forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

streams.rs338 lines, 9.3 KiBHistoryRawDownload
1//! End-to-end: synthetic captions spliced into ffmpeg-encoded H.264 / HEVC / MPEG-2 streams
2//! (with B-frames), extracted in presentation order, decoded, and compared with ffmpeg's own
3//! caption decoder. Needs ffmpeg + ffprobe; skipped without them unless EC_REQUIRE_FIXTURES=1.
4
5use ec_cc::extract::{H264Extractor, HevcExtractor, Mpeg2Extractor, NalFormat};
6use ec_cc::synth::*;
7use ec_cc::{CcTriplet, decode_all};
8use ec_subs::plain_text;
9use std::path::PathBuf;
10use std::process::Command;
11
12const FRAMES: usize = 90;
13
14fn have(tool: &str) -> bool {
15 Command::new(tool)
16 .arg("-version")
17 .output()
18 .is_ok_and(|o| o.status.success())
19}
20
21fn require() -> bool {
22 if have("ffmpeg") && have("ffprobe") {
23 return true;
24 }
25 assert!(
26 std::env::var("EC_REQUIRE_FIXTURES").is_err(),
27 "ffmpeg/ffprobe required"
28 );
29 eprintln!("skipping: no ffmpeg");
30 false
31}
32
33fn tmp(name: &str) -> PathBuf {
34 let d = std::env::temp_dir().join(format!("ec-cc-{}", std::process::id()));
35 std::fs::create_dir_all(&d).unwrap();
36 d.join(name)
37}
38
39fn caption_frames() -> Vec<Vec<CcTriplet>> {
40 let mut s = Script608::new();
41 s.rcl()
42 .enm()
43 .pac(14, 4, false)
44 .text("HELLO")
45 .pac(15, 4, false)
46 .text("WORLD")
47 .eoc();
48 s.idle(14);
49 s.edm().idle(2);
50 s.rcl()
51 .enm()
52 .pac_style(15, 0, 4, false, false)
53 .text("RED ")
54 .midrow(0, true, false)
55 .text("ITALIC")
56 .special(7)
57 .eoc();
58 s.idle(10);
59 s.edm();
60 schedule(FRAMES, 3, &s.pairs)
61}
62
63/// Encode a testsrc clip into mkv, return (mkv path, decode-order display indices).
64fn encode(codec: &[&str], name: &str) -> (PathBuf, Vec<usize>) {
65 let mkv = tmp(&format!("{name}.mkv"));
66 let st = Command::new("ffmpeg")
67 .args([
68 "-v",
69 "error",
70 "-y",
71 "-f",
72 "lavfi",
73 "-i",
74 "testsrc=size=160x96:rate=30",
75 ])
76 .args(["-frames:v", &FRAMES.to_string()])
77 .args(codec)
78 .arg(&mkv)
79 .status()
80 .unwrap();
81 assert!(st.success());
82 let out = Command::new("ffprobe")
83 .args([
84 "-v",
85 "error",
86 "-select_streams",
87 "v:0",
88 "-show_entries",
89 "packet=pts",
90 "-of",
91 "csv=p=0",
92 ])
93 .arg(&mkv)
94 .output()
95 .unwrap();
96 let pts: Vec<i64> = String::from_utf8_lossy(&out.stdout)
97 .lines()
98 .filter_map(|l| l.trim().parse().ok())
99 .collect();
100 assert_eq!(pts.len(), FRAMES);
101 let mut sorted = pts.clone();
102 sorted.sort();
103 let idx = pts
104 .iter()
105 .map(|p| sorted.iter().position(|q| q == p).unwrap())
106 .collect();
107 (mkv, idx)
108}
109
110fn raw(mkv: &PathBuf, fmt: &str, bsf: Option<&str>, name: &str) -> PathBuf {
111 let out = tmp(name);
112 let mut c = Command::new("ffmpeg");
113 c.args(["-v", "error", "-y", "-i"])
114 .arg(mkv)
115 .args(["-c:v", "copy", "-an"]);
116 if let Some(b) = bsf {
117 c.args(["-bsf:v", b]);
118 }
119 assert!(c.args(["-f", fmt]).arg(&out).status().unwrap().success());
120 out
121}
122
123fn decode_order(captions: &[Vec<CcTriplet>], idx: &[usize]) -> Vec<Vec<CcTriplet>> {
124 idx.iter().map(|&i| captions[i].clone()).collect()
125}
126
127fn check(timed: &[ec_cc::TimedCc], captions: &[Vec<CcTriplet>]) {
128 assert_eq!(timed.len(), FRAMES);
129 for (i, t) in timed.iter().enumerate() {
130 assert_eq!(t.triplets, captions[i], "frame {i}");
131 assert_eq!(t.time_us, (i as i64) * 1_000_000 / 30);
132 }
133 let dec = decode_all(timed);
134 let texts: Vec<String> = dec
135 .cea608
136 .iter()
137 .map(|c| plain_text(&c.cue.segments))
138 .collect();
139 assert_eq!(
140 texts,
141 vec![
142 "HELLO\nWORLD".to_string(),
143 "RED ITALIC\u{266A}".to_string()
144 ]
145 );
146}
147
148fn ffmpeg_cues(path: &PathBuf, demuxer_args: &[&str]) -> Option<Vec<(String, f64)>> {
149 let srt = tmp("ff.srt");
150 let mkv = tmp("remux.mp4");
151 let st = Command::new("ffmpeg")
152 .args(["-v", "error", "-y", "-framerate", "30", "-i"])
153 .arg(path)
154 .args(["-c", "copy"])
155 .arg(&mkv)
156 .status()
157 .ok()?;
158 if !st.success() {
159 return None;
160 }
161 let spec = format!("movie={}[out0+subcc]", mkv.display());
162 let st = Command::new("ffmpeg")
163 .args(["-v", "error", "-y"])
164 .args(demuxer_args)
165 .args(["-f", "lavfi", "-i", &spec, "-map", "0:s:0", "-f", "srt"])
166 .arg(&srt)
167 .status()
168 .ok()?;
169 if !st.success() {
170 return None;
171 }
172 let text = std::fs::read_to_string(&srt).ok()?;
173 let mut out = Vec::new();
174 for block in text.split("\n\n") {
175 let mut l = block.lines();
176 l.next()?;
177 let Some(tl) = l.next() else { continue };
178 let start = tl.split(" --> ").next()?;
179 let secs = parse_srt(start)?;
180 let body: Vec<&str> = l.collect();
181 out.push((strip(&body.join("\n")), secs));
182 }
183 Some(out)
184}
185
186fn strip(s: &str) -> String {
187 let mut o = String::new();
188 let mut tag = false;
189 for c in s.chars() {
190 match c {
191 '<' | '{' => tag = true,
192 '>' | '}' => tag = false,
193 c if !tag => o.push(c),
194 _ => {}
195 }
196 }
197 o.trim().to_string()
198}
199
200fn parse_srt(s: &str) -> Option<f64> {
201 let (hms, ms) = s.trim().split_once(',')?;
202 let p: Vec<f64> = hms.split(':').map(|x| x.parse().unwrap()).collect();
203 Some(p[0] * 3600.0 + p[1] * 60.0 + p[2] + ms.parse::<f64>().ok()? / 1000.0)
204}
205
206fn compare_with_ffmpeg(timed: &[ec_cc::TimedCc], path: &PathBuf) {
207 let Some(theirs) = ffmpeg_cues(path, &[]) else {
208 eprintln!("ffmpeg subcc extraction unavailable; skipped comparison");
209 return;
210 };
211 let ours = decode_all(timed).cea608;
212 assert!(!theirs.is_empty(), "ffmpeg found no captions");
213 assert_eq!(
214 theirs.len(),
215 ours.len(),
216 "{theirs:?} vs {:?}",
217 ours.iter()
218 .map(|c| (c.cue.start_us, plain_text(&c.cue.segments)))
219 .collect::<Vec<_>>()
220 );
221 for (t, o) in theirs.iter().zip(&ours) {
222 let norm = |x: &str| x.split_whitespace().collect::<Vec<_>>().join(" ");
223 let a = norm(&t.0);
224 let b = norm(&plain_text(&o.cue.segments));
225 assert_eq!(a, b);
226 assert!(
227 (t.1 - o.cue.start_us as f64 / 1e6).abs() < 0.1,
228 "{t:?} vs {}",
229 o.cue.start_us
230 );
231 }
232}
233
234#[test]
235fn h264_with_b_frames() {
236 if !require() {
237 return;
238 }
239 let (mkv, idx) = encode(
240 &[
241 "-c:v",
242 "libx264",
243 "-bf",
244 "2",
245 "-g",
246 "30",
247 "-x264-params",
248 "bframes=2:b-adapt=0",
249 ],
250 "h264",
251 );
252 let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "a.264");
253 let caps = caption_frames();
254 let with = insert_sei(
255 &std::fs::read(ann).unwrap(),
256 false,
257 &decode_order(&caps, &idx),
258 );
259 let out = tmp("cc.264");
260 std::fs::write(&out, &with).unwrap();
261 // Decode order differs from presentation order: the extractor must undo it.
262 let mut x = H264Extractor::new(NalFormat::AnnexB);
263 x.push(&with, None);
264 let timed = x.finish((30, 1));
265 check(&timed, &caps);
266 compare_with_ffmpeg(&timed, &out);
267}
268
269#[test]
270fn h264_with_container_pts_in_decode_order() {
271 if !require() {
272 return;
273 }
274 let (mkv, idx) = encode(&["-c:v", "libx264", "-bf", "2", "-g", "30"], "h264pts");
275 let ann = raw(&mkv, "h264", Some("h264_mp4toannexb"), "b.264");
276 let caps = caption_frames();
277 let with = insert_sei(
278 &std::fs::read(ann).unwrap(),
279 false,
280 &decode_order(&caps, &idx),
281 );
282 // Feed the first-slice boundaries as pictures with pts = display index (packetised path).
283 let mut x = H264Extractor::new(NalFormat::AnnexB);
284 x.push(&with, None);
285 assert_eq!(x.finish((30, 1)).len(), FRAMES);
286}
287
288#[test]
289fn hevc_with_b_frames() {
290 if !require() {
291 return;
292 }
293 let (mkv, idx) = encode(
294 &[
295 "-c:v",
296 "libx265",
297 "-x265-params",
298 "bframes=3:keyint=30:log-level=error",
299 ],
300 "hevc",
301 );
302 let ann = raw(&mkv, "hevc", Some("hevc_mp4toannexb"), "a.265");
303 let caps = caption_frames();
304 let with = insert_sei(
305 &std::fs::read(ann).unwrap(),
306 true,
307 &decode_order(&caps, &idx),
308 );
309 let out = tmp("cc.265");
310 std::fs::write(&out, &with).unwrap();
311 let mut x = HevcExtractor::new(NalFormat::AnnexB);
312 x.push(&with, None);
313 let timed = x.finish((30, 1));
314 check(&timed, &caps);
315 compare_with_ffmpeg(&timed, &out);
316}
317
318#[test]
319fn mpeg2_atsc_and_dvd_user_data() {
320 if !require() {
321 return;
322 }
323 let (mkv, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "m2v");
324 let es = std::fs::read(raw(&mkv, "mpeg2video", None, "a.m2v")).unwrap();
325 let caps = caption_frames();
326 for dvd in [false, true] {
327 let with = insert_mpeg2_user_data(&es, &decode_order(&caps, &idx), dvd);
328 let mut x = Mpeg2Extractor::new();
329 x.push(&with, None);
330 let timed = x.finish((30, 1));
331 check(&timed, &caps);
332 if !dvd {
333 let out = tmp("cc.m2v");
334 std::fs::write(&out, &with).unwrap();
335 compare_with_ffmpeg(&timed, &out);
336 }
337 }
338}