forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

burn_subs.rs293 lines, 10.6 KiBHistoryRawDownload
1//! Burned-in captions: the cue on screen is drawn into the picture itself, so
2//! an export, a composed frame and anything decoded from the file all carry it,
3//! where a soft track is only there for a player that reads it.
4//!
5//! Witnesses: the decoded frame of an export made with and without the burn
6//! (the same timeline, the same encoder), and `compose_at_with` against
7//! `compose_at`. A frame with a caption must differ in the bottom quarter, and
8//! a frame with no caption on screen must not differ anywhere a caption could
9//! sit.
10//!
11//! ```text
12//! cargo test -p engine --release --test burn_subs -- --nocapture
13//! ```
14
15use std::path::PathBuf;
16use std::time::{Duration, Instant};
17
18use engine::ExportHandle;
19use engine::decode::{DecodeSession, Frame};
20use engine::export::{self, ExportSettings, Format};
21use engine::project::Project;
22use engine::scratch::Scratch;
23use engine::subtitle::{Cue, SubtitleTrack};
24use engine::captionanim::{CaptionAnim, CaptionStyle};
25use engine::text::{Outline, Place, TextStyle};
26
27/// Five seconds at 30 fps, a picture this box decodes with nothing installed.
28const MEDIA: &str = "test_av.mp4";
29const FRAMES: u32 = 150;
30/// The cue `test_subs.srt` puts on screen from 0.5 s to 1.5 s: timeline frames
31/// 15 to 44. Frame 20 is inside it, frame 5 well before it.
32const IN_CUE: u32 = 20;
33const BEFORE_CUE: u32 = 5;
34
35fn asset(name: &str) -> PathBuf {
36 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
37 .join("../../assets")
38 .join(name)
39}
40
41fn pin_software() {
42 engine::envcfg::set("VE_SW", "1");
43 engine::envcfg::set("VE_SW_ENC", "1");
44}
45
46fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
47 let started = Instant::now();
48 while !handle.is_finished() {
49 assert!(
50 started.elapsed() < limit,
51 "export did not finish in {limit:?}"
52 );
53 std::thread::sleep(Duration::from_millis(20));
54 }
55 handle.result().expect("a finished export has an outcome")
56}
57
58/// The first cue of `tests/data/test_subs.srt`, on the media's own clock.
59fn track() -> SubtitleTrack {
60 SubtitleTrack {
61 path: asset(MEDIA),
62 track: Some(2),
63 language: "eng".into(),
64 name: String::new(),
65 label: "eng".into(),
66 bitmap: false,
67 cues: vec![
68 Cue {
69 start_us: 500_000,
70 end_us: 1_500_000,
71 text: "first line".into(),
72 image: None,
73 words: Vec::new(),
74 karaoke: Vec::new(),
75 },
76 Cue {
77 start_us: 2_000_000,
78 end_us: 3_250_000,
79 text: "second line\nwith a break".into(),
80 image: None,
81 words: Vec::new(),
82 karaoke: Vec::new(),
83 },
84 ],
85 refused: None,
86 }
87}
88
89fn project() -> Project {
90 Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()])
91}
92
93fn style() -> TextStyle {
94 TextStyle {
95 outline: Outline::Thin,
96 boxed: true,
97 place: Place::Bottom,
98 ..TextStyle::default()
99 }
100}
101
102/// Pixels whose brightest channel moved by more than the noise an encoder
103/// leaves, counted inside the bottom quarter of the frame -- where a caption at
104/// [`Place::Bottom`] sits. Its height is the frame's own, so the answer does not
105/// depend on the output size.
106fn bottom_changes(a: &[u8], b: &[u8], w: u32, h: u32) -> usize {
107 let row = w as usize * 4;
108 let start = (h as usize * 3 / 4) * row;
109 a[start..]
110 .as_chunks::<4>().0.iter()
111 .zip(b[start..].as_chunks::<4>().0)
112 .filter(|(p, q)| {
113 p.iter()
114 .zip(q.iter())
115 .any(|(x, y)| (i32::from(*x) - i32::from(*y)).abs() > 64)
116 })
117 .count()
118}
119
120/// Exports one second of the project (frames 0 to 30) with `burn` set or not,
121/// and returns the file's frames at `want`, decoded back.
122fn exported(name: &str, burn: Option<(usize, TextStyle)>, want: &[u32]) -> Vec<Frame> {
123 pin_software();
124 let out = Scratch::file(&format!("ve_burn_{name}"), "mp4");
125 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
126 let handle = export::start(
127 project(),
128 meta,
129 &out,
130 &ExportSettings {
131 format: Format::Mp4,
132 range: Some((0, 30)),
133 burn_subtitles: burn,
134 ..Default::default()
135 },
136 None,
137 );
138 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
139 let (_, rx) = DecodeSession::open(&out).expect("decode the export back");
140 let mut frames = Vec::new();
141 for f in rx {
142 if want.contains(&f.index) {
143 frames.push(f);
144 }
145 if frames.len() == want.len() {
146 break;
147 }
148 }
149 assert_eq!(frames.len(), want.len(), "every wanted frame decodes");
150 // The decoder hands frames over in file order, which is not the order asked.
151 frames.sort_by_key(|f| want.iter().position(|w| *w == f.index));
152 frames
153}
154
155#[test]
156fn a_burned_caption_is_in_the_exported_picture_and_only_while_on_screen() {
157 let plain = exported("plain", None, &[IN_CUE, BEFORE_CUE]);
158 let burned = exported("burned", Some((0, style())), &[IN_CUE, BEFORE_CUE]);
159 let (w, h) = (plain[0].width, plain[0].height);
160 let in_cue = bottom_changes(&plain[0].bgra, &burned[0].bgra, w, h);
161 assert!(
162 in_cue > 200,
163 "the caption left no mark in the bottom quarter ({in_cue} pixels)"
164 );
165 // No caption is on screen at frame 5, so the picture must match the plain
166 // export in the very region a caption would have drawn into.
167 let before = bottom_changes(&plain[1].bgra, &burned[1].bgra, w, h);
168 assert_eq!(
169 before, 0,
170 "a frame with no caption on screen was changed ({before} pixels)"
171 );
172}
173
174#[test]
175fn compose_at_with_draws_the_cue_on_screen_and_nothing_else() {
176 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
177 let p = project();
178 let (w, h) = (640, 360);
179 let plain = export::compose_at(&p, &meta, IN_CUE, w, h).expect("compose");
180 let burned = export::compose_at_with(&p, &meta, IN_CUE, w, h, Some((0, style())))
181 .expect("compose with a burn");
182 let drawn = bottom_changes(&plain.bgra, &burned.bgra, w, h);
183 assert!(drawn > 200, "caption not drawn ({drawn} pixels)");
184 let quiet = export::compose_at_with(&p, &meta, BEFORE_CUE, w, h, Some((0, style())))
185 .expect("compose before the cue");
186 let plain_quiet = export::compose_at(&p, &meta, BEFORE_CUE, w, h).expect("compose");
187 assert!(
188 quiet.bgra == plain_quiet.bgra,
189 "no caption is on screen at frame {BEFORE_CUE}"
190 );
191}
192
193#[test]
194fn a_pick_that_is_not_a_track_is_named() {
195 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
196 let Err(err) = export::compose_at_with(&project(), &meta, IN_CUE, 640, 360, Some((7, style())))
197 else {
198 panic!("track 7 does not exist, yet a frame came back");
199 };
200 assert!(err.to_string().contains("no subtitle track 7"), "{err}");
201}
202
203/// A title past the last clip exports over black: the file runs on to the
204/// title's end, and the frame it shows is white letters on a dark picture.
205#[test]
206fn a_title_past_the_clip_is_exported_over_black() {
207 use engine::project::Title;
208 pin_software();
209 let mut p = Project::single(asset(MEDIA), FRAMES);
210 p.add_title(Title {
211 start: 150,
212 frames: 30,
213 text: "Episode 17".into(),
214 style: TextStyle {
215 place: Place::Centre,
216 boxed: false,
217 ..TextStyle::default()
218 },
219 fade_in: 0,
220 fade_out: 0,
221 in_anim: Default::default(),
222 out_anim: Default::default(),
223 anim_frames: 0,
224 keys: Vec::new(),
225 })
226 .expect("the title is added");
227 let out = Scratch::file("ve_title_gap", "mp4");
228 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
229 let handle = export::start(
230 p,
231 meta,
232 &out,
233 &ExportSettings {
234 format: Format::Mp4,
235 range: Some((150, 180)),
236 ..Default::default()
237 },
238 None,
239 );
240 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
241 let (_, rx) = DecodeSession::open(&out).expect("decode the export back");
242 let frame = rx
243 .into_iter()
244 .take(60)
245 .find(|f| f.index == 10)
246 .expect("the export holds the title's tenth frame");
247 let total = (frame.width * frame.height) as usize;
248 let white = frame
249 .bgra
250 .as_chunks::<4>().0.iter()
251 .filter(|px| px[0].max(px[1]).max(px[2]) > 200)
252 .count();
253 let lit = frame
254 .bgra
255 .as_chunks::<4>().0.iter()
256 .filter(|px| px[0].max(px[1]).max(px[2]) > 40)
257 .count();
258 assert!(white > 100, "no white text in the exported title ({white} pixels)");
259 assert!(lit * 4 < total, "the exported title is not over black ({lit} of {total})");
260}
261
262/// A caption set in a named family and animated (karaoke) is burned in that face: the same export in
263/// the bundled face differs inside the caption. Needs the `Noto Serif` family on the system. Set
264/// `EDITH_FONT_EXPORT` to keep the serif export's file for a frame grab.
265#[test]
266fn a_named_family_is_burned_into_an_animated_caption() {
267 pin_software();
268 let animated = |family: Option<&str>| TextStyle {
269 outline: Outline::Thick,
270 family: family.map(str::to_string),
271 caption: CaptionStyle { anim: CaptionAnim::Karaoke, ..CaptionStyle::default() },
272 ..style()
273 };
274 let run = |out: &std::path::Path, burn: TextStyle| {
275 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
276 let handle = export::start(
277 project(),
278 meta,
279 out,
280 &ExportSettings { format: Format::Mp4, range: Some((0, 30)), burn_subtitles: Some((0, burn)), ..Default::default() },
281 None,
282 );
283 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
284 let (_, rx) = DecodeSession::open(out).expect("decode the export back");
285 rx.into_iter().find(|f| f.index == IN_CUE).expect("the caption frame decodes")
286 };
287 let bundled = run(&Scratch::file("ve_burn_bundled", "mp4"), animated(None));
288 let scratch_serif = Scratch::file("ve_burn_serif", "mp4");
289 let serif_out = std::env::var_os("EDITH_FONT_EXPORT").map_or_else(|| scratch_serif.to_path_buf(), PathBuf::from);
290 let serif = run(&serif_out, animated(Some("Noto Serif")));
291 let changed = bottom_changes(&bundled.bgra, &serif.bgra, serif.width, serif.height);
292 assert!(changed > 100, "the named family draws different letters: {changed} pixels changed");
293}