forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

closed_captions.rs207 lines, 7.7 KiBHistoryRawDownload
1//! Embedded closed captions (CEA-608 CC1) come in as subtitle tracks, like a container's own.
2//!
3//! Synthetic clips only: ffmpeg encodes a 160x96 testsrc with B-frames, `ec_cc::synth` splices
4//! cc_data with known CC1 text into the coded pictures (SEI for H.264, user data for MPEG-2),
5//! and ffmpeg only re-wraps the bytes (mkv, mp4, ts). The engine must list a `CC1 (608)` track
6//! and import it with the right texts and the times of the picture's own timeline.
7//! Skipped without ffmpeg unless EC_REQUIRE_FIXTURES=1.
8
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_cc::synth::*;
13use ec_cc::{CcTriplet, TimedCc, decode_all};
14use engine::demux::captions::{self, TRACK_BASE};
15use engine::subtitle::{self, SubtitleTrack};
16
17const FRAMES: usize = 90;
18/// Millisecond container ticks and a 90 kHz clock, rounded.
19const SLACK_US: i64 = 2_000;
20
21fn have(tool: &str) -> bool {
22 Command::new(tool).arg("-version").output().is_ok_and(|o| o.status.success())
23}
24
25fn require() -> bool {
26 if have("ffmpeg") && have("ffprobe") {
27 return true;
28 }
29 assert!(std::env::var("EC_REQUIRE_FIXTURES").is_err(), "ffmpeg/ffprobe required");
30 eprintln!("skipping: no ffmpeg");
31 false
32}
33
34fn tmp(name: &str) -> PathBuf {
35 let d = std::env::temp_dir().join(format!("edith-cc-{}", std::process::id()));
36 std::fs::create_dir_all(&d).unwrap();
37 d.join(name)
38}
39
40fn caption_frames() -> Vec<Vec<CcTriplet>> {
41 let mut s = Script608::new();
42 s.rcl().enm().pac(14, 4, false).text("HELLO").pac(15, 4, false).text("WORLD").eoc();
43 s.idle(14);
44 s.edm().idle(2);
45 s.rcl().enm().pac(15, 4, false).text("SECOND CUE").eoc();
46 s.idle(10);
47 s.edm();
48 schedule(FRAMES, 3, &s.pairs)
49}
50
51fn run(c: &mut Command) {
52 assert!(c.status().unwrap().success(), "{c:?}");
53}
54
55/// Encode, return the raw elementary stream and the decode-order display indices.
56fn encode(codec: &[&str], fmt: &str, bsf: Option<&str>, name: &str) -> (PathBuf, Vec<usize>) {
57 let mkv = tmp(&format!("{name}.mkv"));
58 run(Command::new("ffmpeg")
59 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x96:rate=30"])
60 .args(["-frames:v", &FRAMES.to_string()])
61 .args(codec)
62 .arg(&mkv));
63 let out = Command::new("ffprobe")
64 .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts", "-of", "csv=p=0"])
65 .arg(&mkv)
66 .output()
67 .unwrap();
68 let pts: Vec<i64> =
69 String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| l.trim().parse().ok()).collect();
70 assert_eq!(pts.len(), FRAMES);
71 let mut sorted = pts.clone();
72 sorted.sort();
73 let idx = pts.iter().map(|p| sorted.iter().position(|q| q == p).unwrap()).collect();
74 let es = tmp(&format!("{name}.es"));
75 let mut c = Command::new("ffmpeg");
76 c.args(["-v", "error", "-y", "-i"]).arg(&mkv).args(["-c:v", "copy", "-an"]);
77 if let Some(b) = bsf {
78 c.args(["-bsf:v", b]);
79 }
80 run(c.args(["-f", fmt]).arg(&es));
81 (es, idx)
82}
83
84/// The elementary stream in `out`'s container. A bare stream carries no presentation order for
85/// B-frames (ffmpeg stamps its packets as if decode order were display order), so the real one --
86/// `idx`, the display index of each packet in decode order -- is stamped on with `setts`, with
87/// the dts two pictures behind, the way an encoder writes it. Through an mp4 first, because ffmpeg
88/// gives a bare stream no timestamps a Matroska or ts writer takes.
89fn wrap(es: &Path, input_fmt: &str, idx: &[usize], out: &str) -> PathBuf {
90 let table: Vec<String> = idx.iter().enumerate().map(|(n, i)| format!("eq(N,{n})*{i}")).collect();
91 let pts = format!("({})/30/TB", table.join("+"));
92 let dts = "(N-2)/30/TB";
93 let mp4 = tmp(&format!("{out}.step.mp4"));
94 run(Command::new("ffmpeg")
95 .args(["-v", "error", "-y", "-f", input_fmt, "-framerate", "30", "-i"])
96 .arg(es)
97 .args(["-c", "copy", "-bsf:v"])
98 .arg(format!("setts=pts='{pts}':dts='{dts}'"))
99 .arg(&mp4));
100 if out.ends_with(".mp4") {
101 return mp4;
102 }
103 let path = tmp(out);
104 run(Command::new("ffmpeg").args(["-v", "error", "-y", "-i"]).arg(&mp4).args(["-c", "copy"]).arg(&path));
105 path
106}
107
108/// What the first CC1 cues must be, from the same triplets decoded in display order.
109fn expected(caps: &[Vec<CcTriplet>]) -> Vec<(i64, i64, String)> {
110 let timed: Vec<TimedCc> = caps
111 .iter()
112 .enumerate()
113 .map(|(i, t)| TimedCc { time_us: i as i64 * 1_000_000 / 30, triplets: t.clone() })
114 .collect();
115 decode_all(&timed)
116 .cea608
117 .iter()
118 .filter(|c| c.channel == 1)
119 .map(|c| (c.cue.start_us, c.cue.end_us, ec_subs::plain_text(&c.cue.segments)))
120 .collect()
121}
122
123fn check(path: &Path, caps: &[Vec<CcTriplet>]) {
124 let want = expected(caps);
125 assert_eq!(want.len(), 2);
126 assert_eq!(want[0].2, "HELLO\nWORLD");
127 assert_eq!(want[1].2, "SECOND CUE");
128 // The cheap presence probe lists the track without cues.
129 let present = captions::present(path);
130 assert_eq!(present.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["CC1 (608)"]);
131 // The import door.
132 let tracks: Vec<SubtitleTrack> = engine::PlaybackSession::parse_subtitles(path).expect("imports");
133 assert_eq!(tracks.len(), 1, "{:?}", tracks.iter().map(|t| &t.label).collect::<Vec<_>>());
134 let t = &tracks[0];
135 assert_eq!(t.track, Some(TRACK_BASE + 1));
136 assert_eq!(t.label, "CC1 (608)");
137 assert!(t.refused.is_none() && !t.bitmap);
138 assert_eq!(t.cues.len(), want.len(), "{:?}", t.cues);
139 for (c, (s, e, text)) in t.cues.iter().zip(&want) {
140 assert_eq!(&c.text, text);
141 assert!((c.start_us - s).abs() <= SLACK_US, "start {} vs {s}", c.start_us);
142 assert!((c.end_us - e).abs() <= SLACK_US, "end {} vs {e}", c.end_us);
143 }
144 // A saved row names the track by number and finds it again, without the other tracks.
145 let again = subtitle::open(path, Some(TRACK_BASE + 1));
146 assert!(again.refused.is_none(), "{:?}", again.refused);
147 assert_eq!(again.cues, t.cues);
148}
149
150fn h264(wrapper: &str, input_fmt: &str) {
151 if !require() {
152 return;
153 }
154 let (es, idx) = encode(
155 &["-c:v", "libx264", "-bf", "2", "-g", "30", "-x264-params", "bframes=2:b-adapt=0"],
156 "h264",
157 Some("h264_mp4toannexb"),
158 &format!("h264-{wrapper}"),
159 );
160 let caps = caption_frames();
161 let order: Vec<_> = idx.iter().map(|&i| caps[i].clone()).collect();
162 let with = insert_sei(&std::fs::read(&es).unwrap(), false, &order);
163 std::fs::write(&es, with).unwrap();
164 let file = wrap(&es, input_fmt, &idx, &format!("cc-h264.{wrapper}"));
165 check(&file, &caps);
166}
167
168#[test]
169fn h264_captions_in_matroska() {
170 h264("mkv", "h264");
171}
172
173#[test]
174fn h264_captions_in_mp4() {
175 h264("mp4", "h264");
176}
177
178#[test]
179fn h264_captions_in_transport_stream() {
180 h264("ts", "h264");
181}
182
183#[test]
184fn mpeg2_captions_in_transport_stream() {
185 if !require() {
186 return;
187 }
188 let (es, idx) = encode(&["-c:v", "mpeg2video", "-bf", "2", "-g", "12"], "mpeg2video", None, "m2v");
189 let caps = caption_frames();
190 let order: Vec<_> = idx.iter().map(|&i| caps[i].clone()).collect();
191 let with = insert_mpeg2_user_data(&std::fs::read(&es).unwrap(), &order, false);
192 std::fs::write(&es, with).unwrap();
193 let file = wrap(&es, "mpegvideo", &idx, "cc-mpeg2.ts");
194 check(&file, &caps);
195}
196
197#[test]
198fn a_clip_without_captions_lists_none() {
199 if !require() {
200 return;
201 }
202 let (es, idx) = encode(&["-c:v", "libx264", "-bf", "2"], "h264", Some("h264_mp4toannexb"), "plain");
203 let file = wrap(&es, "h264", &idx, "plain.mp4");
204 assert!(captions::present(&file).is_empty());
205 assert!(captions::tracks(&file).is_empty());
206 assert!(subtitle::of_media(&file).unwrap().is_empty());
207}