forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

compose_at.rs512 lines, 20.1 KiBHistoryRawDownload
1//! `PlaybackSession::compose_at`: the composed picture at an exact timeline
2//! frame, headless. Silent (`VE_NO_AO`), no clock, no UI.
3//!
4//! ```text
5//! cargo test -p engine --release --test compose_at -- --nocapture
6//! ```
7
8use std::path::{Path, PathBuf};
9use std::time::Instant;
10
11use engine::PlaybackSession;
12use engine::decode::{Frame, to_png, to_png_bytes};
13use engine::project::{Lane, LaneKind, Title};
14use engine::text::{Place, TextStyle};
15
16fn asset(name: &str) -> PathBuf {
17 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
18 .join("../../assets")
19 .join(name)
20}
21
22/// Opens a session silently. `VE_NO_AO` keeps the audio device out of the test.
23fn open(path: impl AsRef<Path>) -> PlaybackSession {
24 engine::ao::set_silent_output();
25 PlaybackSession::open(path).expect("open")
26}
27
28/// `test_av.mp4` is 1280x720, 30 fps, 150 frames.
29const W: u32 = 640;
30const H: u32 = 360;
31
32#[test]
33fn size_follows_the_project_aspect_inside_the_box() {
34 let session = open(asset("test_av.mp4"));
35 let f = session.compose_at(0, W, H).expect("frame 0");
36 assert_eq!((f.width, f.height), (640, 360));
37 assert_eq!(f.index, 0);
38 assert_eq!(f.bgra.len(), 640 * 360 * 4);
39
40 // A 16:9 project asked for a square box comes back 16:9, fitted.
41 let g = session.compose_at(0, 500, 500).expect("square box");
42 assert_eq!((g.width, g.height), (500, 281));
43}
44
45#[test]
46fn frames_differ_and_repeat_byte_identically() {
47 let session = open(asset("test_av.mp4"));
48 let a = session.compose_at(0, W, H).expect("frame 0");
49 let b = session.compose_at(60, W, H).expect("frame 60");
50 assert_ne!(a.bgra, b.bgra, "frame 0 and frame 60 should differ");
51
52 let b2 = session.compose_at(60, W, H).expect("frame 60 again");
53 assert!(b.bgra == b2.bgra, "two calls at the same frame must match");
54 assert_eq!(b2.index, 60);
55}
56
57#[test]
58fn a_gap_is_black() {
59 let mut session = open(asset("test_av.mp4"));
60 // Moving the only video clip to frame 100 leaves frames 0..100 a gap.
61 assert!(session.move_clip_to(Lane::V1, 0, Lane::V1, 100));
62
63 let gap = session.compose_at(60, W, H).expect("gap frame");
64 assert_eq!(gap.bgra.len(), 640 * 360 * 4);
65 let worst = gap
66 .bgra
67 .as_chunks::<4>().0.iter()
68 .map(|px| px[0].max(px[1]).max(px[2]))
69 .max()
70 .unwrap_or(0);
71 assert!(worst <= 2, "gap frame is not black (max channel {worst})");
72
73 // The clip itself still composes after the gap.
74 let clip = session.compose_at(120, W, H).expect("clip frame");
75 let clip_max = clip
76 .bgra
77 .as_chunks::<4>().0.iter()
78 .map(|px| px[0].max(px[1]).max(px[2]))
79 .max()
80 .unwrap_or(0);
81 assert!(clip_max > 16, "frame after the gap is black");
82}
83
84#[test]
85fn past_the_end_is_an_error() {
86 let mut session = open(asset("test_av.mp4"));
87 assert!(session.compose_at(150, W, H).is_err(), "frame 150 of 150");
88 assert!(session.move_clip_to(Lane::V1, 0, Lane::V1, 100));
89 // 100 + 150 frames of timeline now; 250 is the first past the end.
90 assert!(session.compose_at(249, W, H).is_ok());
91 assert!(session.compose_at(250, W, H).is_err());
92}
93
94#[test]
95fn png_roundtrip_matches_the_pixels() {
96 let session = open(asset("test_av.mp4"));
97 let f = session.compose_at(60, W, H).expect("frame 60");
98 let bytes = to_png_bytes(&f).expect("encode");
99 assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
100
101 let decoded = ec_image::decode(&bytes).expect("decode png");
102 assert_eq!((decoded.width, decoded.height), (f.width, f.height));
103 let expected: Vec<u8> = f
104 .bgra
105 .as_chunks::<4>().0.iter()
106 .flat_map(|px| [px[2], px[1], px[0], px[3]])
107 .collect();
108 assert!(decoded.to_rgba8() == expected, "png pixels differ");
109
110 let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
111 .join(format!("compose_at_{}", std::process::id()));
112 std::fs::create_dir_all(&dir).expect("mkdir");
113 let path = dir.join("frame60.png");
114 to_png(&f, &path).expect("write");
115 assert_eq!(std::fs::read(&path).expect("read back"), bytes);
116 let _ = std::fs::remove_dir_all(&dir);
117}
118
119#[test]
120fn timing() {
121 let session = open(asset("test_av.mp4"));
122 let _ = session.compose_at(60, W, H).expect("warm");
123 let n = 10u32;
124 let t = Instant::now();
125 for i in 0..n {
126 let _: Frame = session.compose_at(i * 10, W, H).expect("frame");
127 }
128 let per = t.elapsed().as_secs_f64() * 1000.0 / n as f64;
129 eprintln!("compose_at 640x360: {per:.1} ms per frame (mean of {n}, varied frames)");
130}
131
132/// A title card or caption at `start` for `frames`, set with the default look
133/// and no box, so the only pixels it changes are its own letters.
134fn title(start: u32, frames: u32, place: Place) -> Title {
135 Title {
136 start,
137 frames,
138 text: "Episode 17".into(),
139 style: TextStyle {
140 place,
141 boxed: false,
142 ..TextStyle::default()
143 },
144 fade_in: 0,
145 fade_out: 0,
146 in_anim: Default::default(),
147 out_anim: Default::default(),
148 anim_frames: 0,
149 keys: Vec::new(),
150 }
151}
152
153/// The rows in which any byte of `a` and `b` differs: the rows a title drew in.
154fn changed_rows(a: &[u8], b: &[u8], w: u32, h: u32) -> Vec<u32> {
155 let row = w as usize * 4;
156 (0..h)
157 .filter(|&y| {
158 let s = y as usize * row;
159 a[s..s + row] != b[s..s + row]
160 })
161 .collect()
162}
163
164/// The brightest channel summed over the whole frame: how much of it is lit.
165fn light(f: &Frame) -> u64 {
166 f.bgra
167 .as_chunks::<4>().0.iter()
168 .map(|px| u64::from(px[0].max(px[1]).max(px[2])))
169 .sum()
170}
171
172#[test]
173fn a_title_draws_in_its_centre_band_and_its_frames_only() {
174 let mut session = open(asset("test_av.mp4"));
175 let before_in = session.compose_at(60, W, H).expect("frame 60");
176 let before_out = session.compose_at(70, W, H).expect("frame 70");
177 session
178 .add_title(title(50, 20, Place::Centre))
179 .expect("a title is added");
180 let after_in = session.compose_at(60, W, H).expect("frame 60 with the title");
181 let after_out = session.compose_at(70, W, H).expect("frame 70, after the title");
182
183 let (w, h) = (after_in.width, after_in.height);
184 let rows = changed_rows(&before_in.bgra, &after_in.bgra, w, h);
185 assert!(!rows.is_empty(), "no title pixel inside its frames");
186 assert!(
187 rows.iter().all(|&y| y >= h * 3 / 10 && y < h * 7 / 10),
188 "the centred title drew outside the middle band: {rows:?}"
189 );
190 assert!(
191 changed_rows(&before_out.bgra, &after_out.bgra, w, h).is_empty(),
192 "the frame after the title's last changed"
193 );
194}
195
196#[test]
197fn a_title_past_the_last_clip_is_text_on_black() {
198 let mut session = open(asset("test_av.mp4"));
199 // test_av.mp4 runs 150 frames; the title runs the timeline on to 180.
200 session
201 .add_title(title(150, 30, Place::Centre))
202 .expect("a title past the clip is added");
203 let f = session
204 .compose_at(160, W, H)
205 .expect("a frame of the title over black composes");
206 let total = (f.width * f.height) as usize;
207 let lit = f
208 .bgra
209 .as_chunks::<4>().0.iter()
210 .filter(|px| px[0].max(px[1]).max(px[2]) > 2)
211 .count();
212 let white = f
213 .bgra
214 .as_chunks::<4>().0.iter()
215 .filter(|px| px[0].max(px[1]).max(px[2]) > 200)
216 .count();
217 assert!(white > 100, "no white text over the black ({white} pixels)");
218 assert!(lit * 10 < total, "the frame is not black around the text ({lit} of {total})");
219 assert!(
220 session.compose_at(180, W, H).is_err(),
221 "frame 180 is past the title and the timeline"
222 );
223}
224
225#[test]
226fn a_fade_in_starts_fainter_than_its_middle() {
227 let mut session = open(asset("test_av.mp4"));
228 session
229 .add_title(Title {
230 fade_in: 10,
231 ..title(150, 30, Place::Centre)
232 })
233 .expect("a title with a fade-in is added");
234 let first = light(&session.compose_at(150, W, H).expect("the first frame"));
235 let mid = light(&session.compose_at(155, W, H).expect("a frame mid-fade"));
236 let full = light(&session.compose_at(160, W, H).expect("a frame past the fade"));
237 assert!(first > 0, "the first frame shows nothing at all");
238 assert!(first < mid, "the first frame ({first}) is not fainter than mid-fade ({mid})");
239 assert!(mid < full, "mid-fade ({mid}) is not fainter than full ({full})");
240}
241
242/// A title's colour and side reach the composed frame: yellow letters, against the left margin.
243#[test]
244fn a_title_look_reaches_the_composed_frame() {
245 use engine::text::{HPlace, Weight};
246 let mut session = open(asset("test_av.mp4"));
247 session
248 .add_title(Title {
249 style: TextStyle {
250 ink: [255, 204, 0],
251 hplace: HPlace::Left,
252 weight: Weight::Bold,
253 ..title(150, 30, Place::Centre).style
254 },
255 ..title(150, 30, Place::Centre)
256 })
257 .expect("a styled title is added");
258 let f = session.compose_at(155, W, H).expect("a frame over the title");
259 let px = f.bgra.as_chunks::<4>().0;
260 let lit: Vec<(usize, &[u8; 4])> = px.iter().enumerate().filter(|(_, p)| p[0] > 0 || p[1] > 0 || p[2] > 0).collect();
261 assert!(lit.len() > 100, "no text drawn");
262 let brightest = lit.iter().max_by_key(|(_, p)| u32::from(p[2])).unwrap().1;
263 assert!(brightest[2] > 240 && (190..=215).contains(&brightest[1]) && brightest[0] < 20, "yellow: {brightest:?}");
264 assert!(lit.iter().all(|(i, _)| (*i % W as usize) < W as usize / 2), "the block sits in the left half");
265}
266
267/// The mean green channel over the whole frame: a black frame is near zero,
268/// and a picture scaled by `k` toward black has a mean of about `k` times its
269/// own.
270fn mean_green(f: &Frame) -> f64 {
271 let n = (f.bgra.len() / 4) as f64;
272 f.bgra.as_chunks::<4>().0.iter().map(|px| f64::from(px[1])).sum::<f64>() / n
273}
274
275#[test]
276fn a_picture_fade_comes_from_black_and_goes_to_it() {
277 let mut session = open(asset("test_av.mp4"));
278 // test_av.mp4 is one clip of 150 frames at 30 fps, so the clip's own
279 // frames are the timeline's. Measure it plain first.
280 let plain = |s: &PlaybackSession, at: u32| s.compose_at(at, W, H).expect("frame");
281 let base: Vec<Frame> = [0, 5, 10, 140, 145, 149]
282 .into_iter()
283 .map(|at| plain(&session, at))
284 .collect();
285 assert!(session.set_fade_in(Lane::V1, 0, 10));
286 assert!(session.set_fade_out(Lane::V1, 0, 10));
287
288 // The fade-in: black on its first frame, half of the picture half way up
289 // the ramp, and the picture itself from the frame the ramp ends on.
290 let (first, half, done) = (plain(&session, 0), plain(&session, 5), plain(&session, 10));
291 assert!(mean_green(&first) <= 2.0, "the first frame is not black: {}", mean_green(&first));
292 let (b5, b10) = (mean_green(&base[1]), mean_green(&base[2]));
293 let m5 = mean_green(&half);
294 assert!(
295 (m5 - 0.5 * b5).abs() <= 2.0 + 0.03 * b5,
296 "mid-fade ({m5:.1}) is not about half the picture ({b5:.1})"
297 );
298 assert!(done.bgra == base[2].bgra, "the frame the fade-in ends on is not the picture");
299 assert!(mean_green(&done) > b10 * 0.99, "the picture is still fading");
300
301 // The fade-out: the picture until its last ten frames, half way down the
302 // ramp at frame 145, and black on the last frame of the clip.
303 let (out_mid, last) = (plain(&session, 145), plain(&session, 149));
304 let (b145, b149) = (mean_green(&base[4]), mean_green(&base[5]));
305 let m145 = mean_green(&out_mid);
306 assert!(
307 (m145 - 0.5 * b145).abs() <= 2.0 + 0.03 * b145,
308 "mid-fade-out ({m145:.1}) is not about half the picture ({b145:.1})"
309 );
310 assert!(mean_green(&last) < 0.2 * b149, "the last frame is not near black");
311 assert!(
312 plain(&session, 140).bgra == base[3].bgra,
313 "a frame before the fade-out's ramp is not the picture"
314 );
315}
316
317/// The BGR of pixel `i` of a BGRA frame.
318fn px(f: &Frame, i: usize) -> &[u8] {
319 &f.bgra[i * 4..i * 4 + 3]
320}
321
322/// A picture-in-picture: V2 is a smaller, moved picture over V1. Outside the
323/// picture V1 must show through (it is the same pixels V1 makes alone); inside
324/// it the V2 picture must be what V2 makes alone. Both are exact -- the layers
325/// are composed with the same placement a single clip gets -- so the check is
326/// per pixel, not a mean.
327#[test]
328fn a_transformed_clip_on_top_lets_the_clip_beneath_show_outside_it() {
329 let mut session = open(asset("test_av.mp4"));
330 let v2 = session.add_lane(LaneKind::Video);
331 // The same file on V2 from frame 0: the source is already on the timeline,
332 // and the PiP is a scaled picture, so it differs from V1 wherever it lands.
333 session
334 .place_stream_at(0.0, &asset("test_av.mp4"), 0, Some(v2))
335 .expect("place the picture on V2");
336 let pip = engine::transform::TransformParams {
337 pos_x: 0.3,
338 pos_y: 0.3,
339 scale: 0.3,
340 ..Default::default()
341 };
342 assert!(session.set_transform(v2, 0, Some(pip)));
343
344 let at = 20;
345 let layered = session.compose_at(at, W, H).expect("layered frame");
346 assert!(session.set_lane_hidden(v2, true));
347 let v1_alone = session.compose_at(at, W, H).expect("V1 alone");
348 assert!(session.set_lane_hidden(v2, false));
349 assert!(session.set_lane_hidden(Lane::V1, true));
350 let v2_alone = session.compose_at(at, W, H).expect("V2 alone");
351 assert!(session.set_lane_hidden(Lane::V1, false));
352
353 let (mut inside, mut outside) = (0usize, 0usize);
354 for i in 0..(W * H) as usize {
355 // V2 alone is black outside its picture; a picture pixel is at least
356 // this bright in one channel (the test clip is not black there).
357 let is_pip = px(&v2_alone, i).iter().any(|&c| c > 6);
358 let want = if is_pip { &v2_alone } else { &v1_alone };
359 if is_pip {
360 inside += 1;
361 } else {
362 outside += 1;
363 }
364 assert_eq!(
365 px(&layered, i),
366 px(want, i),
367 "pixel {i} ({}, {}) is not the {} picture",
368 i % W as usize,
369 i / W as usize,
370 if is_pip { "V2" } else { "V1" }
371 );
372 }
373 // The picture is a real share of the frame, and V1 shows around it.
374 assert!(inside > (W * H) as usize / 20, "the PiP covers only {inside} pixels");
375 assert!(outside > (W * H) as usize / 2, "V1 shows on only {outside} pixels");
376}
377
378/// The same picture-in-picture as the frame test above, played: the preview's
379/// first picture after a seek is the picture `compose_at` composes there, so the
380/// layered preview and the export agree -- not only the frame an agent asks for.
381/// The preview's picture at timeline `at`, played: seek there and take the frame
382/// the preview delivers for it, at the viewer's size.
383fn played_at(session: &mut PlaybackSession, at: u32) -> Frame {
384 session.seek(f64::from(at) / 30.0);
385 let deadline = Instant::now() + std::time::Duration::from_secs(10);
386 loop {
387 if let Some(frame) = session.try_frame()
388 && frame.index == at
389 {
390 return frame;
391 }
392 assert!(Instant::now() < deadline, "no picture at frame {at} after the seek");
393 std::thread::sleep(std::time::Duration::from_millis(4));
394 }
395}
396
397/// The picture-in-picture of the frame test above, played. The preview composes
398/// at the viewer's size on its own path, so it is compared with the same
399/// preview's V1 alone and V2 alone -- like with like, at one size -- not with
400/// `compose_at`, which resizes a project-size frame.
401#[test]
402fn a_layered_picture_plays_as_it_is_layered() {
403 let mut session = open(asset("test_av.mp4"));
404 let v2 = session.add_lane(LaneKind::Video);
405 session
406 .place_stream_at(0.0, &asset("test_av.mp4"), 0, Some(v2))
407 .expect("place the picture on V2");
408 let pip = engine::transform::TransformParams {
409 pos_x: 0.3,
410 pos_y: 0.3,
411 scale: 0.3,
412 ..Default::default()
413 };
414 assert!(session.set_transform(v2, 0, Some(pip)));
415 assert!(session.set_view_size_exact(W, H));
416
417 let at = 30;
418 let layered = played_at(&mut session, at);
419 assert!(session.set_lane_hidden(v2, true));
420 let v1_alone = played_at(&mut session, at);
421 assert!(session.set_lane_hidden(v2, false));
422 assert!(session.set_lane_hidden(Lane::V1, true));
423 let v2_alone = played_at(&mut session, at);
424 assert!(session.set_lane_hidden(Lane::V1, false));
425 assert_eq!((layered.width, layered.height), (W, H));
426
427 let n = (W * H) as usize;
428 let (mut inside, mut outside_worst, mut inside_worst) = (0usize, 0u8, 0u8);
429 for i in 0..n {
430 let a = &layered.bgra[i * 4..i * 4 + 3];
431 let is_pip = v2_alone.bgra[i * 4..i * 4 + 3].iter().any(|&c| c > 6);
432 let (want, worst) = match is_pip {
433 true => {
434 inside += 1;
435 (&v2_alone.bgra, &mut inside_worst)
436 }
437 false => (&v1_alone.bgra, &mut outside_worst),
438 };
439 let d = (0..3).map(|c| a[c].abs_diff(want[i * 4 + c])).max().unwrap_or(0);
440 *worst = (*worst).max(d);
441 }
442 eprintln!("played: outside the PiP worst {outside_worst}, inside worst {inside_worst}");
443 assert!(inside > n / 20 && n - inside > n / 2, "the PiP covers {inside} of {n} pixels");
444 assert!(outside_worst <= 2, "outside the PiP the preview is not V1: worst {outside_worst}");
445 assert!(inside_worst <= 2, "inside the PiP the preview is not V2: worst {inside_worst}");
446}
447
448/// A dissolve on V1 with a V2 overlay across it. V1 is cut in two at frame 60
449/// (A is 0..60, B is 60..150, both the test file) and A dissolves into B over
450/// the last 10 frames. Mid-transition, outside the overlay, the picture must be
451/// the blend of A and B -- the same picture a dissolve with nothing over it
452/// composes -- and not A alone; inside the overlay it must be V2 alone.
453#[test]
454fn a_dissolve_under_a_layer_blends_the_clips_beneath_it() {
455 let mut session = open(asset("test_av.mp4"));
456 assert!(session.cut_at(2.0), "cut V1 at frame 60");
457 assert!(session.set_transition_out(Lane::V1, 0, 10));
458 let v2 = session.add_lane(LaneKind::Video);
459 session
460 .place_stream_at(0.0, &asset("test_av.mp4"), 0, Some(v2))
461 .expect("place the picture on V2");
462 let pip = engine::transform::TransformParams {
463 pos_x: 0.3,
464 pos_y: 0.3,
465 scale: 0.3,
466 ..Default::default()
467 };
468 assert!(session.set_transform(v2, 0, Some(pip)));
469
470 // Frame 55 is the window's sixth frame of ten: A and B both show.
471 let at = 55;
472 let layered = session.compose_at(at, W, H).expect("layered dissolve");
473 // The same dissolve with nothing over it: the single-clip blend.
474 assert!(session.set_lane_hidden(v2, true));
475 let blend = session.compose_at(at, W, H).expect("V1 dissolve alone");
476 assert!(session.set_lane_hidden(v2, false));
477 // A alone: the same frame with the dissolve taken away.
478 assert!(session.set_transition_out(Lane::V1, 0, 0));
479 assert!(session.set_lane_hidden(v2, true));
480 let a_alone = session.compose_at(at, W, H).expect("A alone");
481 assert!(session.set_lane_hidden(v2, false));
482 assert!(session.set_transition_out(Lane::V1, 0, 10));
483 assert!(session.set_lane_hidden(Lane::V1, true));
484 let v2_alone = session.compose_at(at, W, H).expect("V2 alone");
485 assert!(session.set_lane_hidden(Lane::V1, false));
486
487 let (mut inside, mut outside, mut blended_apart) = (0usize, 0usize, 0usize);
488 for i in 0..(W * H) as usize {
489 let is_pip = px(&v2_alone, i).iter().any(|&c| c > 6);
490 if is_pip {
491 inside += 1;
492 assert_eq!(px(&layered, i), px(&v2_alone, i), "pixel {i} is not the V2 picture");
493 } else {
494 outside += 1;
495 assert_eq!(
496 px(&layered, i),
497 px(&blend, i),
498 "pixel {i} ({}, {}) is not the A/B blend",
499 i % W as usize,
500 i / W as usize
501 );
502 if px(&a_alone, i) != px(&blend, i) {
503 blended_apart += 1;
504 }
505 }
506 }
507 // The check has to be able to tell a blend from A. The test clip is mostly
508 // still, so the blend departs from A on a few thousand pixels, not most.
509 assert!(inside > (W * H) as usize / 20, "the PiP covers only {inside} pixels");
510 assert!(outside > (W * H) as usize / 2, "V1 shows on only {outside} pixels");
511 assert!(blended_apart > 1000, "the blend is A itself: only {blended_apart} pixels differ");
512}