forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

video_copy.rs671 lines, 26.4 KiBHistoryRawDownload
1//! The video copy path: a Matroska timeline nobody has touched leaves as the
2//! very coded blocks its source holds, and one that anybody *has* touched still
3//! goes through the encoder.
4//!
5//! What is measured here is not "a file came out": it is that the bytes of the
6//! file that came out are the source's own, that the pictures either side of a
7//! cut still decode through this project's own decoder, and that every gate the
8//! copy claims to have really refuses.
9//!
10//! ```text
11//! cargo build -p engine -p engine-hw --release
12//! LD_LIBRARY_PATH=target/release \
13//! cargo test -p engine --release --test video_copy -- --test-threads=1
14//! ```
15//!
16//! No test here needs the plugin: export decodes HEVC on the same software seat
17//! playback uses (`ec-h265`), and the copy itself decodes nothing. The
18//! multi-cut tests build their own source with the `ffmpeg` CLI -- the fixture
19//! suite's HEVC file is two groups of pictures long, which has no interior to
20//! splice -- and say so and pass where it is not installed, exactly as
21//! `tests/hevc_export.rs` does.
22
23use crate::hwchild;
24
25use std::path::{Path, PathBuf};
26use std::process::Command;
27use std::time::{Duration, Instant};
28
29use engine::demux::Demuxer;
30use engine::export::{ExportSettings, Format};
31use engine::hw::HwSession;
32use engine::project::{Lane, Speed};
33use engine::scratch::Scratch;
34use engine::{DecodeSession, PlaybackSession};
35
36fn asset(name: &str) -> PathBuf {
37 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
38 .join("../../assets")
39 .join(name)
40}
41
42/// One coded block of a Matroska picture track, as the file holds it.
43#[derive(PartialEq)]
44struct Coded {
45 bytes: Vec<u8>,
46 key: bool,
47 ts_ns: i64,
48}
49
50/// Every block of `path`'s picture track, in the file's own order.
51fn blocks(path: &Path) -> Vec<Coded> {
52 let (_, demuxer) = Demuxer::open(path).expect("open");
53 let Demuxer::Mkv(mut demuxer) = demuxer else {
54 panic!("{} is not Matroska", path.display());
55 };
56 (0..demuxer.block_count())
57 .map(|i| {
58 let block = demuxer
59 .coded_block(i)
60 .expect("read a block")
61 .expect("a block at an index the count states");
62 Coded {
63 bytes: block.bytes.to_vec(),
64 key: block.key,
65 ts_ns: block.ts_ns,
66 }
67 })
68 .collect()
69}
70
71/// Runs an export to completion and hands back the encoder line it published --
72/// which is where a copy says it was one.
73fn export(session: &PlaybackSession, out: &Path, format: Format) -> String {
74 let settings = ExportSettings {
75 format,
76 ..Default::default()
77 };
78 let handle = session.export_to_with(out, &settings);
79 let started = Instant::now();
80 while !handle.is_finished() {
81 assert!(
82 started.elapsed() < Duration::from_secs(600),
83 "the export did not finish in 600 s"
84 );
85 std::thread::sleep(Duration::from_millis(20));
86 }
87 let encoders = handle.encoders().unwrap_or_default();
88 handle
89 .result()
90 .expect("an outcome")
91 .unwrap_or_else(|e| panic!("export failed: {e}"));
92 encoders
93}
94
95/// A source of `gops` groups of pictures at 30 fps, keyed every 30 frames, with
96/// B-frames and the open groups x265 writes by default -- which is the shape a
97/// film off a disc has and the shape the copy path has to survive. `None` where
98/// `ffmpeg` is not installed.
99fn multi_gop(name: &str, gops: u32) -> Option<Scratch> {
100 let out = Scratch::file(name, "mkv");
101 let seconds = gops.to_string();
102 let ok = Command::new("ffmpeg")
103 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
104 .arg(format!("testsrc2=size=320x240:rate=30:duration={seconds}"))
105 .args(["-f", "lavfi", "-i"])
106 .arg(format!("sine=frequency=440:duration={seconds}"))
107 .args([
108 "-map",
109 "0:v",
110 "-map",
111 "1:a",
112 "-c:v",
113 "libx265",
114 "-x265-params",
115 "log-level=error:keyint=30:min-keyint=30:scenecut=0",
116 "-pix_fmt",
117 "yuv420p",
118 "-c:a",
119 "aac",
120 "-b:a",
121 "128k",
122 ])
123 .arg(&out)
124 .status()
125 .ok()?;
126 ok.success().then_some(out)
127}
128
129/// An untouched Matroska timeline is written by copying: the file that comes out
130/// holds its source's blocks, byte for byte, with the same sync points and the
131/// same timing -- reordered B-frames included, which is the thing a frame
132/// counter would silently get wrong.
133#[test]
134fn an_untouched_matroska_timeline_leaves_as_its_source_packets() {
135 let source = asset("test_hevc.mkv");
136 let session = PlaybackSession::open(&source).expect("open the fixture");
137 let out = Scratch::file("ve_copy_untouched", "mkv");
138 let line = export(&session, &out, Format::Hevc);
139 assert!(
140 line.starts_with("copy · "),
141 "an untouched timeline was not copied: {line}"
142 );
143 let (before, after) = (blocks(&source), blocks(&out));
144 assert_eq!(before.len(), after.len(), "block count");
145 for (i, (a, b)) in before.iter().zip(&after).enumerate() {
146 assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes");
147 assert_eq!(a.key, b.key, "block {i} sync flag");
148 // Millisecond ticks either side, so the comparison is the timestamp the
149 // container can really state.
150 assert_eq!(
151 a.ts_ns / 1_000_000,
152 b.ts_ns / 1_000_000,
153 "block {i} is shown at another time than its source"
154 );
155 }
156}
157
158/// The same for AV1, whose blocks are whole temporal units rather than
159/// length-prefixed NALs: one gate, two codecs, and the file says which.
160#[test]
161fn an_untouched_av1_timeline_leaves_as_its_source_packets() {
162 let source = asset("test_av1.mkv");
163 let session = PlaybackSession::open(&source).expect("open the fixture");
164 let out = Scratch::file("ve_copy_av1", "mkv");
165 let line = export(&session, &out, Format::Av1);
166 assert!(line.starts_with("copy · "), "AV1 was not copied: {line}");
167 let (before, after) = (blocks(&source), blocks(&out));
168 assert_eq!(before.len(), after.len(), "block count");
169 for (i, (a, b)) in before.iter().zip(&after).enumerate() {
170 assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes");
171 }
172}
173
174/// The Exact quality row asked of a timeline nobody has touched: it must copy
175/// exactly as the plain [`Format::Hevc`] row above already does, since the
176/// only thing `exact` adds over an untouched timeline is the flag itself --
177/// what it changes is the *fallback*, and there is none to reach here.
178#[test]
179fn exact_on_an_untouched_matroska_timeline_is_stream_identical() {
180 let source = asset("test_hevc.mkv");
181 let session = PlaybackSession::open(&source).expect("open the fixture");
182 let out = Scratch::file("ve_copy_exact", "mkv");
183 let settings = ExportSettings {
184 format: Format::Hevc,
185 exact: true,
186 ..Default::default()
187 };
188 let handle = session.export_to_with(&out, &settings);
189 let started = Instant::now();
190 while !handle.is_finished() {
191 assert!(
192 started.elapsed() < Duration::from_secs(600),
193 "the export did not finish in 600 s"
194 );
195 std::thread::sleep(Duration::from_millis(20));
196 }
197 let line = handle.encoders().unwrap_or_default();
198 handle
199 .result()
200 .expect("an outcome")
201 .unwrap_or_else(|e| panic!("export failed: {e}"));
202 assert!(line.starts_with("copy · "), "exact did not copy: {line}");
203 let (before, after) = (blocks(&source), blocks(&out));
204 assert_eq!(before.len(), after.len(), "block count");
205 for (i, (a, b)) in before.iter().zip(&after).enumerate() {
206 assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes");
207 assert_eq!(a.key, b.key, "block {i} sync flag");
208 }
209}
210
211/// Exact asked of an mp4: [`CopyPlan`]'s own corner-cut is that mp4 copies
212/// nothing yet, so the container cannot carry the source's codec byte for
213/// byte -- a state report, named before a frame is touched, and not a silent
214/// re-encode wearing the Exact label.
215#[test]
216fn exact_refuses_a_container_that_cannot_carry_the_codec() {
217 let source = asset("test_hevc.mkv");
218 let session = PlaybackSession::open(&source).expect("open the fixture");
219 let out = Scratch::file("ve_copy_exact_refused", "mp4");
220 let settings = ExportSettings {
221 format: Format::Mp4,
222 exact: true,
223 ..Default::default()
224 };
225 let handle = session.export_to_with(&out, &settings);
226 let started = Instant::now();
227 while !handle.is_finished() {
228 assert!(
229 started.elapsed() < Duration::from_secs(600),
230 "the export did not finish in 600 s"
231 );
232 std::thread::sleep(Duration::from_millis(20));
233 }
234 let err = handle
235 .result()
236 .expect("an outcome")
237 .expect_err("an mp4 cannot honour exact");
238 assert!(
239 err.to_string().contains("cannot carry"),
240 "unexpected refusal: {err}"
241 );
242}
243
244/// A cut placed on a sync point: the middle of the film is deleted and both
245/// sides leave as copies. What is checked is the join -- the blocks either side
246/// of it are the source's own, the timestamps rise a frame at a time across it
247/// once they are put back in display order, and nothing but the leading
248/// pictures the cut orphaned is missing.
249#[test]
250fn a_cut_on_a_keyframe_copies_both_sides() {
251 let Some(source) = multi_gop("ve_copy_source", 6) else {
252 println!("ffmpeg is not installed: skipping the multi-cut copy test");
253 return;
254 };
255 let before = blocks(&source);
256 let keys: Vec<usize> = (0..before.len()).filter(|&i| before[i].key).collect();
257 assert!(keys.len() >= 4, "expected several groups, got {keys:?}");
258 // Frames 60 and 120 in the block order the whole engine counts in.
259 let (first, second) = (keys[2], keys[4]);
260 let mut session = PlaybackSession::open(&source).expect("open the source");
261 let fps = session.meta().frame_rate;
262 assert!(session.cut_at(first as f64 / fps), "cut at the third group");
263 assert!(
264 session.cut_at(second as f64 / fps),
265 "cut at the fifth group"
266 );
267 // One call: the picture and the sound of a take are one group, so
268 // deleting the clip takes its lane partner with it.
269 assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip");
270
271 let out = Scratch::file("ve_copy_cut", "mkv");
272 let line = export(&session, &out, Format::Hevc);
273 assert!(
274 line.starts_with("copy · "),
275 "a keyframe cut was not copied: {line}"
276 );
277
278 // What the file should hold: the blocks before the cut, then the blocks
279 // after it minus the leading pictures the second region orphaned -- those
280 // are shown before their own sync point and reference the group this cut
281 // threw away.
282 let after = blocks(&out);
283 let mut want: Vec<&Coded> = before[..first].iter().collect();
284 let origin = before[second].ts_ns;
285 want.extend(before[second..].iter().filter(|b| b.ts_ns >= origin));
286 assert_eq!(after.len(), want.len(), "copied block count");
287 for (i, (a, b)) in want.iter().zip(&after).enumerate() {
288 assert_eq!(a.bytes, b.bytes, "block {i} is not the source's bytes");
289 assert_eq!(a.key, b.key, "block {i} sync flag");
290 }
291 // Put back in display order, the file is a frame grid with one hole: the
292 // frames the second region's dropped leading pictures would have filled,
293 // which is where the picture before the cut is held instead.
294 let mut shown: Vec<i64> = after.iter().map(|b| b.ts_ns / 1_000_000).collect();
295 shown.sort_unstable();
296 let step = (1000.0 / fps).round() as i64;
297 let holes = shown
298 .windows(2)
299 .filter(|w| (w[1] - w[0] - step).abs() > 1)
300 .count();
301 assert!(
302 holes <= 1,
303 "the copied file is not one run of frames: {holes} holes in {shown:?}"
304 );
305 assert_eq!(shown[0], 0, "the file starts at the timeline's own zero");
306}
307
308/// ...and that join really decodes: every picture around it comes back through
309/// this project's own demuxer and decoder, in order, without an error and
310/// without a black frame where the cut is.
311#[test]
312fn the_pictures_either_side_of_a_copied_cut_decode() {
313 let Some(source) = multi_gop("ve_copy_decode_source", 6) else {
314 println!("ffmpeg is not installed: skipping the copied-join decode test");
315 return;
316 };
317 let before = blocks(&source);
318 let keys: Vec<usize> = (0..before.len()).filter(|&i| before[i].key).collect();
319 let (first, second) = (keys[2], keys[4]);
320 let mut session = PlaybackSession::open(&source).expect("open the source");
321 let fps = session.meta().frame_rate;
322 assert!(session.cut_at(first as f64 / fps));
323 assert!(session.cut_at(second as f64 / fps));
324 assert!(session.delete_clip(Lane::V1, 1));
325 let out = Scratch::file("ve_copy_decode", "mkv");
326 let line = export(&session, &out, Format::Hevc);
327 assert!(line.starts_with("copy · "), "not copied: {line}");
328
329 let (meta, frames) = match DecodeSession::open(&out) {
330 Ok(open) => open,
331 Err(e) => {
332 println!("no HEVC decoder here ({e}): skipping the decode-back");
333 return;
334 }
335 };
336 let mut seen = Vec::new();
337 for frame in frames {
338 let luma: u64 = frame
339 .bgra
340 .as_chunks::<4>().0.iter()
341 .map(|px| u64::from(px[1]))
342 .sum::<u64>()
343 / (u64::from(frame.width) * u64::from(frame.height));
344 seen.push((frame.index, luma));
345 }
346 assert!(
347 seen.len() >= meta.frame_count as usize - 8,
348 "{} pictures decoded of {}",
349 seen.len(),
350 meta.frame_count
351 );
352 for (i, (index, _)) in seen.iter().enumerate() {
353 assert_eq!(*index as usize, i, "pictures came back out of order");
354 }
355 // The join is at the first region's length; a frame either side of it is a
356 // real picture rather than the black a broken splice decodes to.
357 let joint = first.min(seen.len() - 1);
358 for at in [0, joint.saturating_sub(2), joint, seen.len() - 1] {
359 assert!(
360 seen[at].1 > 4,
361 "picture {at} around the join is black ({} luma)",
362 seen[at].1
363 );
364 }
365}
366
367/// Every gate the copy claims: a grade, a speed and a format whose container
368/// this path does not write all put the export back through the encoder. A copy
369/// that took any of these would write a file that is not what was watched.
370#[test]
371fn a_touched_timeline_is_still_encoded() {
372 let source = asset("test_hevc.mkv");
373 let out = Scratch::file("ve_copy_gate", "mkv");
374
375 let mut graded = PlaybackSession::open(&source).expect("open");
376 assert!(graded.set_color(
377 Lane::V1,
378 0,
379 Some(engine::color::ColorParams {
380 saturation: 1.4,
381 ..Default::default()
382 })
383 ));
384 let line = export(&graded, &out, Format::Hevc);
385 assert!(
386 !line.starts_with("copy"),
387 "a graded timeline was copied: {line}"
388 );
389
390 let mut speeded = PlaybackSession::open(&source).expect("open");
391 speeded
392 .set_speed(Lane::V1, 0, Speed::from_permille(2000))
393 .expect("speed the clip");
394 let line = export(&speeded, &out, Format::Hevc);
395 assert!(
396 !line.starts_with("copy"),
397 "a speeded timeline was copied: {line}"
398 );
399
400 // The same untouched timeline into an mp4: nothing here copies into one,
401 // because a sample entry states its parameter sets once and the mp4 muxer
402 // times its samples by a frame counter.
403 let plain = PlaybackSession::open(&source).expect("open");
404 let mp4 = Scratch::file("ve_copy_gate_mp4", "mp4");
405 let line = export(&plain, &mp4, Format::HevcMp4);
406 assert!(!line.starts_with("copy"), "an mp4 was copied: {line}");
407}
408
409/// The canvas gate, which is the gate that is missing: a project resized to a
410/// size its source is not comes out at the **project's** size, not at the
411/// source's frame size wearing a "copy" label.
412///
413/// The seat line is the symptom -- a user reads "copy · …" and hands over a
414/// file at the wrong resolution -- so this checks both halves: the file was
415/// encoded rather than copied, and it is the canvas that is in it.
416#[test]
417fn a_canvas_the_source_is_not_is_encoded_at_the_canvas() {
418 let source = asset("test_hevc.mkv");
419 let (source_meta, _) = Demuxer::open(&source).expect("open the fixture");
420 let (canvas, portrait) = ((960, 540), (720, 1280));
421 assert_ne!(
422 (canvas.0, canvas.1),
423 (source_meta.coded_width, source_meta.coded_height),
424 "the fixture is already this size: the gate is not exercised"
425 );
426
427 for (label, (w, h)) in [("a smaller canvas", canvas), ("a taller canvas", portrait)] {
428 let mut session = PlaybackSession::open(&source).expect("open");
429 assert!(session.set_resolution(w, h), "resize the project");
430 let out = Scratch::file("ve_copy_canvas", "mkv");
431 let line = export(&session, &out, Format::Hevc);
432 assert!(
433 !line.starts_with("copy"),
434 "{label} ({w}x{h}) was copied: {line}"
435 );
436 let (written, _) = Demuxer::open(&out).expect("reopen the export");
437 assert_eq!(
438 (written.coded_width, written.coded_height),
439 (w, h),
440 "{label} ({w}x{h}) came out at the source's size"
441 );
442 }
443}
444
445/// ...and the fit policy is read against the *canvas*, not on its own: a clip
446/// on a canvas the size of its own coded picture is the identity under every
447/// policy, `Fill` included, so `Fill` there is still the source's own blocks.
448/// A gate that refused every non-default policy would pass the test above and
449/// break this one.
450#[test]
451fn a_fit_policy_on_a_matching_canvas_is_still_the_identity() {
452 let source = asset("test_hevc.mkv");
453 for (label, fit) in [
454 ("fill", engine::scale::FitPolicy::Fill),
455 ("stretch", engine::scale::FitPolicy::Stretch),
456 ("centre", engine::scale::FitPolicy::Center),
457 ] {
458 let mut session = PlaybackSession::open(&source).expect("open");
459 assert!(session.set_fit(Lane::V1, 0, fit), "{label}: set the fit");
460 let out = Scratch::file("ve_copy_fit", "mkv");
461 let line = export(&session, &out, Format::Hevc);
462 assert!(
463 line.starts_with("copy · "),
464 "{label} on the source's own canvas was not copied: {line}"
465 );
466 let before = blocks(&source);
467 let after = blocks(&out);
468 assert_eq!(before.len(), after.len(), "{label}: block count");
469 assert!(
470 before.iter().zip(&after).all(|(a, b)| a.bytes == b.bytes),
471 "{label}: the blocks are not the source's own"
472 );
473 }
474}
475
476/// A cut that lands between two sync points is the case this path refuses: the
477/// head of the second region would need pictures that are not in the file, so
478/// the whole export goes back through the encoder rather than writing a file
479/// whose first second cannot be decoded.
480#[test]
481fn a_cut_off_the_keyframe_grid_falls_back_to_the_encoder() {
482 let source = asset("test_hevc.mkv");
483 let mut session = PlaybackSession::open(&source).expect("open");
484 let fps = session.meta().frame_rate;
485 // Block 40 of a file keyed every 30: inside the second group.
486 assert!(session.cut_at(40.0 / fps), "cut mid-group");
487 assert!(session.delete_clip(Lane::V1, 0), "drop the first clip");
488 let out = Scratch::file("ve_copy_offgrid", "mkv");
489 let line = export(&session, &out, Format::Hevc);
490 assert!(
491 !line.starts_with("copy"),
492 "a cut off the sync grid was copied: {line}"
493 );
494}
495
496/// The measurement this path exists for, on a real film rather than a fixture:
497/// a 4K HDR x265 Matroska of two and a half hours, cut once in the middle, out
498/// to Matroska. What it costs is the *edited* spans -- which for a copy is no
499/// spans at all -- plus reading and writing the bytes, against a re-encode that
500/// codes every one of its 167 thousand pictures.
501///
502/// `#[ignore]`d and named by environment, so no path off this machine is in the
503/// repository and the suite runs without the file:
504///
505/// ```text
506/// VE_FILM=/path/to/film.mkv VE_OUT=/somewhere/cut.mkv \
507/// cargo test -p engine --release --test video_copy -- --ignored --nocapture \
508/// a_real_film
509/// ```
510#[test]
511#[ignore]
512fn a_real_film_is_cut_by_copying_its_spans() {
513 let Ok(film) = std::env::var("VE_FILM") else {
514 println!("VE_FILM is not set: skipping the real-film copy measurement");
515 return;
516 };
517 // The decode-back below opens the hardware seat; the copy itself does not.
518 hwchild::require();
519 let film = PathBuf::from(film);
520 let opened = Instant::now();
521 let (meta, demuxer) = Demuxer::open(&film).expect("open the film");
522 let Demuxer::Mkv(mut source) = demuxer else {
523 panic!("the film is not Matroska");
524 };
525 println!(
526 "film: {}x{} {:?} {:.4} fps, {} blocks, indexed in {:?}",
527 meta.width,
528 meta.height,
529 meta.codec,
530 meta.frame_rate,
531 source.block_count(),
532 opened.elapsed()
533 );
534 // The cut: five minutes taken out of the middle of the film, on the two
535 // sync points nearest the half-hour marks -- which is what placing a cut on
536 // a keyframe means, and what the copy needs of any cut.
537 let mut sync_at = |from: u32| {
538 (from as usize..source.block_count())
539 .find(|&i| source.is_sync(i))
540 .expect("a sync point after the mark")
541 };
542 let (first, second) = (
543 sync_at((30.0 * 60.0 * meta.frame_rate) as u32),
544 sync_at((35.0 * 60.0 * meta.frame_rate) as u32),
545 );
546 println!(
547 "cutting blocks {first}..{second} out of {}",
548 meta.frame_count
549 );
550
551 let mut session = PlaybackSession::open(&film).expect("open the film as a project");
552 let fps = session.meta().frame_rate;
553 assert!(session.cut_at(first as f64 / fps), "cut at the first mark");
554 assert!(
555 session.cut_at(second as f64 / fps),
556 "cut at the second mark"
557 );
558 assert!(session.delete_clip(Lane::V1, 1), "drop the middle");
559
560 let out = PathBuf::from(
561 std::env::var("VE_OUT").unwrap_or_else(|_| "/tmp/ve_real_film_cut.mkv".into()),
562 );
563 let started = Instant::now();
564 let line = export(&session, &out, Format::Hevc);
565 let took = started.elapsed();
566 let bytes = std::fs::metadata(&out).expect("the exported file").len();
567 println!("exported {} MB in {:?} ({line})", bytes / 1_000_000, took);
568 assert!(
569 line.starts_with("copy · "),
570 "the film was not copied: {line}"
571 );
572
573 // The bytes: every block around either side of the join, and a sample
574 // across the rest -- a whole-file comparison is a second read of twelve
575 // gigabytes and says nothing this does not.
576 let mut written = blocks(&out);
577 println!("{} blocks written of {}", written.len(), meta.frame_count);
578 let origin = {
579 let block = source.coded_block(second).expect("read").expect("a block");
580 block.ts_ns
581 };
582 let mut want: Vec<usize> = (0..first).collect();
583 want.extend((second..source.block_count()).filter(|&i| {
584 let block = source.coded_block(i).expect("read").expect("a block");
585 block.ts_ns >= origin
586 }));
587 assert_eq!(written.len(), want.len(), "copied block count");
588 let near_join = first.saturating_sub(200)..(first + 200).min(want.len());
589 for (out_index, &source_index) in want.iter().enumerate() {
590 if !near_join.contains(&out_index) && out_index % 500 != 0 {
591 continue;
592 }
593 let block = source
594 .coded_block(source_index)
595 .expect("read")
596 .expect("a block");
597 assert_eq!(
598 block.bytes,
599 written[out_index].bytes.as_slice(),
600 "block {out_index} of the export is not source block {source_index}"
601 );
602 assert_eq!(
603 block.key, written[out_index].key,
604 "block {out_index} sync flag"
605 );
606 }
607 // The join itself, in display order: one run of frames with at most the one
608 // hole the orphaned leading pictures leave.
609 written.sort_by_key(|b| b.ts_ns);
610 let step = (1e9 / fps).round() as i64;
611 let holes: Vec<i64> = written
612 .windows(2)
613 .map(|w| w[1].ts_ns - w[0].ts_ns)
614 .filter(|d| (d - step).abs() > step / 2)
615 .collect();
616 println!("gaps in the shown order: {holes:?} ns (one frame is {step} ns)");
617 assert!(holes.len() <= 1, "the copied film is not one run of frames");
618
619 // ...and the join really decodes: two seconds either side of it, through
620 // this project's own demuxer and decoder, in order and never black. The
621 // start and the end of the film with them, so the file is exercised end to
622 // end and not only where it was cut.
623 let seconds = fps.round() as usize * 2;
624 let decode_at = |path: &Path, at: u32| -> Option<Vec<u64>> {
625 let mut decoder = HwSession::open_at(path, at)?;
626 let mut lumas = Vec::new();
627 while lumas.len() < seconds {
628 let Some((y, _, _, w, h)) = decoder.next_frame().expect("decode") else {
629 break;
630 };
631 lumas
632 .push(y.iter().map(|&s| u64::from(s)).sum::<u64>() / (u64::from(w) * u64::from(h)));
633 }
634 Some(lumas)
635 };
636 // The tail is measured against the *source's* own tail rather than against
637 // the count asked for: a decoder drains the last group of pictures the same
638 // way in both files (45 of the last 48 on this film, measured), and a copy
639 // is right when it behaves as its source does, not when it behaves better.
640 let tail = decode_at(&film, meta.frame_count - seconds as u32).map(|l| l.len());
641 for (what, at, least) in [
642 ("the start", 0, seconds),
643 ("the join", first as u32 - seconds as u32, seconds),
644 (
645 "the end",
646 written.len() as u32 - seconds as u32,
647 tail.unwrap_or(seconds),
648 ),
649 ] {
650 let Some(lumas) = decode_at(&out, at) else {
651 println!("no VA-API plugin here: skipping the decode of {what}");
652 break;
653 };
654 println!(
655 "{what} at frame {at}: {} pictures, luma {lumas:?}",
656 lumas.len()
657 );
658 assert!(
659 lumas.len() >= least,
660 "{what} decoded {} pictures of the {least} its source gives",
661 lumas.len()
662 );
663 // Limited-range black is 16, and this film opens and closes on it; what
664 // a broken splice decodes to is 0, and what it never does is stay in
665 // step with the source's own luma.
666 assert!(
667 lumas.iter().all(|&l| l >= 15),
668 "a black picture around {what}: {lumas:?}"
669 );
670 }
671}