forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

playback.rs1124 lines, 42.6 KiBHistoryRawDownload
1//! End-to-end playback timing, without a UI. Both files run through the same
2//! checks: `test_baseline.mp4` has no audio and is therefore always wall-paced,
3//! `test_av.mp4` uses the audio clock when a PipeWire daemon is around and falls
4//! back to the same wall path when it is not -- so neither test is `#[ignore]`d.
5//!
6//! ```text
7//! cargo test -p engine --release --test playback -- --nocapture
8//! ```
9
10use std::path::{Path, PathBuf};
11use std::thread::sleep;
12use std::time::{Duration, Instant};
13
14use engine::project::Lane;
15use engine::{DecodeSession, Frame, PlaybackSession};
16
17fn asset(name: &str) -> PathBuf {
18 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
19 .join("../../assets")
20 .join(name)
21}
22
23/// Opens a session the way every test here wants one: silent. The suite plays
24/// real files through the real device, so without this a `cargo test` is two
25/// minutes of noise out of the speakers of whoever ran it.
26///
27/// Muting is the gain knob, not a pause and not a fake device: the stream is
28/// still connected, the daemon still schedules it, the samples are still
29/// decoded, written, and handed over -- only the last multiply before the
30/// device is zero. Every clock, `fed` and `played_out` assertion below is
31/// therefore measuring exactly what it measured when this was audible.
32fn open(path: impl AsRef<Path>) -> PlaybackSession {
33 let session = PlaybackSession::open(path).expect("open");
34 // False for the silent fixtures, which have no device to quieten.
35 session.set_gain(0.0);
36 session
37}
38
39/// One render tick of a front-end: advance the clock, take whatever frames are
40/// due. Returns the highest frame index seen so far.
41fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) {
42 session.tick();
43 let target = session.now() * session.meta().frame_rate;
44 while let Some(frame) = session.try_frame() {
45 if let Some(previous) = *last_index {
46 assert_eq!(
47 frame.index,
48 previous + 1,
49 "frames must arrive in index order"
50 );
51 }
52 *last_index = Some(frame.index);
53 // Stop at the first frame past the clock; the real app holds it for the
54 // next tick, we simply stop draining.
55 if f64::from(frame.index) > target {
56 return;
57 }
58 }
59}
60
61/// Pumps for `duration` of wall time at roughly a display refresh.
62fn run_for(session: &mut PlaybackSession, last_index: &mut Option<u32>, duration: Duration) {
63 let deadline = Instant::now() + duration;
64 while Instant::now() < deadline {
65 pump(session, last_index);
66 sleep(Duration::from_millis(8));
67 }
68}
69
70fn plays_at_real_speed(name: &str) {
71 let path = asset(name);
72 let mut session = open(&path);
73 assert_eq!(session.now(), 0.0, "a fresh session starts at zero");
74 assert!(!session.is_playing(), "a fresh session starts paused");
75 let mut last_index = None;
76
77 session.play();
78 let started = Instant::now();
79 run_for(&mut session, &mut last_index, Duration::from_secs(2));
80 let (played, wall) = (session.now(), started.elapsed().as_secs_f64());
81 eprintln!("{name}: clock {played:.3}s over {wall:.3}s wall");
82 assert!(
83 (played - wall).abs() < wall * 0.15,
84 "clock ran at the wrong speed: {played:.3}s in {wall:.3}s"
85 );
86 assert!(last_index.is_some(), "no frames arrived");
87
88 session.pause();
89 let frozen = session.now();
90 run_for(&mut session, &mut last_index, Duration::from_millis(300));
91 assert!(
92 (session.now() - frozen).abs() < 0.025,
93 "paused clock moved: {frozen:.3}s -> {:.3}s",
94 session.now()
95 );
96
97 session.play();
98 run_for(&mut session, &mut last_index, Duration::from_millis(500));
99 let resumed = session.now();
100 assert!(
101 resumed > frozen + 0.3,
102 "clock did not resume: {frozen:.3}s -> {resumed:.3}s"
103 );
104 // No time was invented across the pause: 2.5 s of playing, not 2.8 s.
105 assert!(
106 resumed < wall + 0.7,
107 "the pause leaked into the timeline: {resumed:.3}s"
108 );
109}
110
111#[test]
112fn video_only_plays_at_real_speed() {
113 plays_at_real_speed("test_baseline.mp4");
114}
115
116#[test]
117fn audio_video_plays_at_real_speed() {
118 plays_at_real_speed("test_av.mp4");
119}
120
121/// The next frame off the (post-seek, freshly opened) channel.
122fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
123 let deadline = Instant::now() + Duration::from_secs(10);
124 loop {
125 if let Some(frame) = session.try_frame() {
126 return frame;
127 }
128 assert!(Instant::now() < deadline, "no frame after {what}");
129 sleep(Duration::from_millis(4));
130 }
131}
132
133fn next_index(session: &mut PlaybackSession, what: &str) -> u32 {
134 next_frame(session, what).index
135}
136
137/// Ticks like a front-end but takes every frame as fast as the decoder makes
138/// them, until the timeline is played out. Returns how many arrived and the
139/// last index.
140fn drain_to_eof(session: &mut PlaybackSession) -> (u32, Option<u32>) {
141 let deadline = Instant::now() + Duration::from_secs(20);
142 let (mut count, mut last) = (0, None);
143 loop {
144 session.tick();
145 while let Some(frame) = session.try_frame() {
146 count += 1;
147 last = Some(frame.index);
148 }
149 if session.is_eos() {
150 return (count, last);
151 }
152 assert!(Instant::now() < deadline, "still draining after 20 s");
153 sleep(Duration::from_millis(4));
154 }
155}
156
157/// The pixels of one source frame, decoded on its own -- the reference a
158/// timeline frame is checked against.
159fn source_frame(path: &Path, index: u32) -> Vec<u8> {
160 let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
161 let frame = rx
162 .recv_timeout(Duration::from_secs(10))
163 .expect("reference frame");
164 assert_eq!(frame.index, index, "open_range starts where it is told");
165 frame.bgra
166}
167
168fn threads() -> usize {
169 std::fs::read_to_string("/proc/self/status")
170 .unwrap()
171 .lines()
172 .find_map(|l| l.strip_prefix("Threads:"))
173 .and_then(|n| n.trim().parse().ok())
174 .expect("Threads: in /proc/self/status")
175}
176
177/// Wall-clock seek: no audio track, so this runs anywhere.
178#[test]
179fn seek_repositions_video_and_clock() {
180 let mut session = open(asset("test_baseline.mp4"));
181 let fps = session.meta().frame_rate;
182 let mut last_index = None;
183
184 session.play();
185 run_for(&mut session, &mut last_index, Duration::from_millis(500));
186
187 session.seek(3.0);
188 assert!(
189 (session.now() - 3.0).abs() < 0.05,
190 "clock at {}",
191 session.now()
192 );
193 assert_eq!(
194 next_index(&mut session, "seek(3.0)"),
195 (3.0 * fps) as u32,
196 "the first frame after a seek is the target frame"
197 );
198 sleep(Duration::from_millis(200));
199 assert!(session.now() > 3.05, "clock stalled at {}", session.now());
200
201 // Run it out, then seek back: the old workers are gone, not steered.
202 let last_frame = session.meta().frame_count - 1;
203 assert_eq!(drain_to_eof(&mut session).1, Some(last_frame));
204 session.seek(0.0);
205 assert_eq!(next_index(&mut session, "seek(0.0) after EOF"), 0);
206 assert!(session.now() < 0.2, "clock at {}", session.now());
207}
208
209/// Past the end lands on the last frame instead of hanging, and the clock keeps
210/// running -- with audio that means falling through to wall time, because the
211/// device is never fed another sample.
212#[test]
213fn seek_past_the_end_clamps() {
214 let mut session = open(asset("test_av.mp4"));
215 let meta = *session.meta();
216 let duration = f64::from(meta.frame_count) / meta.frame_rate;
217
218 session.play();
219 session.seek(999.0);
220 assert!(
221 (session.now() - duration).abs() < 0.05,
222 "clock at {} for a {duration}s file",
223 session.now()
224 );
225 assert_eq!(
226 next_index(&mut session, "seek(999.0)"),
227 meta.frame_count - 1
228 );
229
230 let landed = session.now();
231 let deadline = Instant::now() + Duration::from_secs(2);
232 while session.now() <= landed + 0.05 {
233 session.tick();
234 assert!(Instant::now() < deadline, "clock froze at {landed}");
235 sleep(Duration::from_millis(8));
236 }
237}
238
239/// Scrubbing: seeks with no time in between must neither panic nor leave the
240/// abandoned workers behind, and the last one still wins.
241#[test]
242fn rapid_seeks_settle_on_the_last_one() {
243 let mut session = open(asset("test_av.mp4"));
244 let fps = session.meta().frame_rate;
245 let mut last_index = None;
246
247 session.play();
248 run_for(&mut session, &mut last_index, Duration::from_millis(300));
249 let before = threads();
250
251 for t in [4.0, 1.0, 3.5, 0.5, 2.0] {
252 session.seek(t);
253 }
254 assert_eq!(
255 next_index(&mut session, "5 rapid seeks"),
256 (2.0 * fps) as u32
257 );
258
259 sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
260 let after = threads();
261 eprintln!("rapid seeks: {before} threads -> {after}");
262 assert!(
263 after <= before + 3,
264 "workers piled up: {before} threads -> {after}"
265 );
266}
267
268/// The audio path proper: needs a PipeWire daemon and the output plugin next to
269/// the test binary (`LD_LIBRARY_PATH=target/release`).
270#[test]
271#[ignore = "needs a running PipeWire daemon"]
272fn seek_keeps_the_audio_clock() {
273 let mut session = open(asset("test_av.mp4"));
274 let meta = *session.meta();
275 let mut last_index = None;
276
277 session.play();
278 run_for(&mut session, &mut last_index, Duration::from_secs(1));
279
280 session.seek(3.0);
281 assert!(
282 (session.now() - 3.0).abs() < 0.05,
283 "clock at {}",
284 session.now()
285 );
286 let first = next_index(&mut session, "seek(3.0)");
287 assert_eq!(first, (3.0 * meta.frame_rate) as u32);
288 let mut after_seek = None;
289 run_for(&mut session, &mut after_seek, Duration::from_millis(600));
290 let advanced = session.now();
291 eprintln!("seek(3.0) -> {advanced:.3}s, frames {first}..={after_seek:?}");
292 assert!(
293 (3.3..3.9).contains(&advanced),
294 "clock did not run at real speed after the seek: {advanced:.3}s"
295 );
296
297 // Everything from the target on, and nothing before it: ~2 s of frames.
298 let (drained, last) = drain_to_eof(&mut session);
299 let total = 1 + after_seek.map_or(0, |i| i - first) + drained;
300 eprintln!("frames from 3.0s to EOF: {total}");
301 // `run_for` pumps faster than real time, so it may have hit EOF by itself.
302 assert_eq!(last.or(after_seek), Some(meta.frame_count - 1), "no EOF");
303 assert!(
304 (55..=65).contains(&total),
305 "expected ~60 frames left, got {total}"
306 );
307
308 // A full second run after EOF, from zero.
309 session.seek(0.0);
310 session.play();
311 let mut second = None;
312 run_for(&mut session, &mut second, Duration::from_millis(800));
313 assert_eq!(second.map(|i| i > 0), Some(true), "second run stalled");
314 assert!(session.now() > 0.5, "second run clock at {}", session.now());
315 assert_eq!(
316 drain_to_eof(&mut session).1.or(second),
317 Some(meta.frame_count - 1),
318 "second run did not finish"
319 );
320}
321
322/// The edit list end to end: two cuts, drop the middle clip, play the result.
323/// What comes out is one contiguous timeline whose *pictures* skip the hole --
324/// no audio needed, so this runs anywhere.
325#[test]
326fn edits_traverse_cuts() {
327 let path = asset("test_baseline.mp4");
328 let mut session = open(&path);
329 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
330 let whole = f64::from(total) / fps;
331 assert!((session.timeline_duration() - whole).abs() < 1e-9);
332 assert_eq!(session.clip_spans(), vec![(0.0, whole)]);
333
334 assert!(session.cut_at(2.0), "cut at 2 s");
335 assert!(session.cut_at(3.5), "cut at 3.5 s");
336 assert!(
337 !session.cut_at(2.0),
338 "the same frame twice: already a boundary"
339 );
340 assert!(!session.cut_at(0.0), "nothing before the first frame");
341 assert_eq!(session.clip_spans().len(), 3);
342 // Cuts are metadata: the timeline is the same length as before.
343 assert!((session.timeline_duration() - whole).abs() < 1e-9);
344
345 let (cut, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
346 assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip");
347 let kept = total - (hole_end - cut);
348 assert_eq!(session.clip_spans().len(), 2);
349 assert!(
350 (session.timeline_duration() - f64::from(kept) / fps).abs() < 1e-9,
351 "duration after the delete: {}",
352 session.timeline_duration()
353 );
354
355 // Play the whole edited timeline from the top.
356 session.seek(0.0);
357 session.play();
358 let deadline = Instant::now() + Duration::from_secs(20);
359 let (mut expect, mut boundary) = (0, None);
360 loop {
361 session.tick();
362 while let Some(frame) = session.try_frame() {
363 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
364 if frame.index == cut {
365 boundary = Some(frame.bgra);
366 }
367 expect += 1;
368 }
369 if session.is_eos() {
370 break;
371 }
372 assert!(Instant::now() < deadline, "still draining after 20 s");
373 sleep(Duration::from_millis(4));
374 }
375 assert_eq!(expect, kept, "the edited timeline, whole and nothing but");
376 // From here the playhead has to stand still: an edit reseeks to *now*, so a
377 // running clock would move the frame these assertions expect.
378 session.pause();
379
380 // The frames behind those indices skipped the deleted range: the picture at
381 // the boundary is source `hole_end`, not the source frame with that number.
382 let boundary = boundary.expect("no frame at the cut");
383 assert!(
384 boundary == source_frame(&path, hole_end),
385 "the boundary frame is not source {hole_end}"
386 );
387 assert!(
388 boundary != source_frame(&path, cut),
389 "the deleted range is still being decoded"
390 );
391
392 // Seek into the surviving second clip: timeline 3.0 s is source 3.0 s + the
393 // 1.5 s hole.
394 session.seek(3.0);
395 let landed = next_frame(&mut session, "seek(3.0) after edits");
396 assert_eq!(landed.index, (3.0 * fps) as u32);
397 assert!(
398 landed.bgra == source_frame(&path, (4.5 * fps) as u32),
399 "the seek landed on the wrong source frame"
400 );
401 assert!(!session.is_eos(), "a seek revives a played-out session");
402
403 assert!(session.undo(), "undo the delete");
404 assert_eq!(session.clip_spans().len(), 3);
405 assert!(
406 (session.timeline_duration() - whole).abs() < 1e-9,
407 "undo did not restore the duration: {}",
408 session.timeline_duration()
409 );
410 // The undo reseeks to the (still paused) playhead, and on the restored
411 // timeline 3.0 s is source 3.0 s again -- the hole is back.
412 let restored = next_frame(&mut session, "undo");
413 assert_eq!(restored.index, (3.0 * fps) as u32);
414 assert!(
415 restored.bgra == source_frame(&path, (3.0 * fps) as u32),
416 "undo did not restore the mapping"
417 );
418}
419
420/// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the
421/// pasted stretch has to decode its own range -- not the frames the timeline
422/// used to hold at that position.
423#[test]
424fn paste_duplicates_a_clip_at_the_playhead() {
425 let path = asset("test_baseline.mp4");
426 let mut session = open(&path);
427 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
428 let whole = f64::from(total) / fps;
429
430 assert!(session.cut_at(2.0), "cut at 2 s");
431 let copied = session.clip_at(0).expect("clip 0");
432 let copied_len = copied.len();
433 assert_eq!(copied_len, (2.0 * fps) as u32);
434 assert!(session.clip_at(2).is_none(), "only two clips so far");
435
436 // Mid-clip: the paste splits clip 1 and lands between the halves.
437 let at = (4.0 * fps) as u32;
438 assert!(session.paste_at(4.0, copied), "paste at 4 s");
439 assert_eq!(session.clip_spans().len(), 4);
440 let grown = total + copied_len;
441 assert!(
442 (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
443 "duration after the paste: {}",
444 session.timeline_duration()
445 );
446
447 // Play the edited timeline from the top, keeping the two seam frames.
448 session.seek(0.0);
449 session.play();
450 let deadline = Instant::now() + Duration::from_secs(30);
451 let (mut expect, mut pasted, mut resumed) = (0, None, None);
452 loop {
453 session.tick();
454 while let Some(frame) = session.try_frame() {
455 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
456 if frame.index == at {
457 pasted = Some(frame.bgra);
458 } else if frame.index == at + copied_len {
459 resumed = Some(frame.bgra);
460 }
461 expect += 1;
462 }
463 if session.is_eos() {
464 break;
465 }
466 assert!(Instant::now() < deadline, "still draining after 30 s");
467 sleep(Duration::from_millis(4));
468 }
469 assert_eq!(expect, grown, "the pasted timeline, whole and nothing but");
470 // As above: an edit reseeks to *now*, so stop the clock before asserting.
471 session.pause();
472
473 // At the paste position the picture is the copied clip's first frame, and
474 // the split-off remainder resumes exactly where it was interrupted.
475 assert!(
476 pasted.expect("no frame at the paste") == source_frame(&path, copied.in_frame),
477 "the paste is not showing source {}",
478 copied.in_frame
479 );
480 assert!(
481 resumed.expect("no frame after the paste") == source_frame(&path, at),
482 "the timeline did not resume at source {at}"
483 );
484
485 assert!(session.undo(), "undo the paste");
486 assert_eq!(session.clip_spans().len(), 2, "one step, back to the cut");
487 assert!(
488 (session.timeline_duration() - whole).abs() < 1e-9,
489 "undo did not restore the duration: {}",
490 session.timeline_duration()
491 );
492}
493
494/// Pasting at the playhead while it is running: like a delete this moves every
495/// following frame, so the session reseeks under itself -- what must not happen
496/// is a stall, and the grown timeline still plays out whole. No audio needed.
497#[test]
498fn paste_while_playing_does_not_stall() {
499 let path = asset("test_baseline.mp4");
500 let mut session = open(&path);
501 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
502 let mut last_index = None;
503
504 assert!(session.cut_at(2.0), "cut at 2 s");
505 let copied = session.clip_at(0).expect("clip 0");
506 session.play();
507 run_for(&mut session, &mut last_index, Duration::from_millis(300));
508 assert!(last_index.is_some(), "no frames before the paste");
509
510 // Into the clip under the running playhead: the paste splits it in two and
511 // lands between the halves.
512 assert!(
513 session.paste_at(session.now(), copied),
514 "paste at the playhead"
515 );
516 assert!(session.is_playing(), "the paste stopped the clock");
517 assert_eq!(session.clip_spans().len(), 4);
518 let grown = total + copied.len();
519 assert!(
520 (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
521 "duration after the paste: {}",
522 session.timeline_duration()
523 );
524
525 // As after a mid-play import: the reseek makes the indices step backwards
526 // once, so this drains without `pump`'s index-order check.
527 let (count, last) = drain_to_eof(&mut session);
528 eprintln!("paste while playing: {count} more frames, last {last:?}");
529 assert_eq!(last, Some(grown - 1), "the grown timeline did not play out");
530}
531
532/// Pasting past the end of a played-out timeline appends, and the reseek every
533/// edit does clears `eos` -- so the session plays on into the pasted clip
534/// instead of staying dead.
535#[test]
536fn paste_at_eos_revives_the_session() {
537 let path = asset("test_baseline.mp4");
538 let mut session = open(&path);
539 let total = session.meta().frame_count;
540
541 assert!(session.cut_at(2.0), "cut at 2 s");
542 let copied = session.clip_at(0).expect("clip 0");
543 session.play();
544 assert_eq!(drain_to_eof(&mut session).1, Some(total - 1));
545 assert!(session.is_eos());
546
547 assert!(
548 session.paste_at(999.0, copied),
549 "paste past the end appends"
550 );
551 assert!(!session.is_eos(), "the paste did not revive the session");
552 assert_eq!(
553 session.clip_spans().len(),
554 3,
555 "two clips plus the pasted one"
556 );
557 // No assertion on *where* it resumes: an edit reseeks to `now()`, and at EOS
558 // that is wherever the wall clock got to while draining -- a race. What is
559 // fixed is that frames come again and the whole grown timeline plays out.
560 next_frame(&mut session, "paste at EOS");
561 assert_eq!(
562 drain_to_eof(&mut session).1,
563 Some(total + copied.len() - 1),
564 "the pasted clip did not play out"
565 );
566}
567
568/// Editing while the device is running. A cut must not disturb playback at all
569/// and a delete reseeks under it -- in both cases the audio keeps coming, which
570/// is what stops `tick` from handing the timeline back to wall time.
571#[test]
572#[ignore = "needs a running PipeWire daemon"]
573fn edits_keep_the_audio_clock() {
574 let mut session = open(asset("test_av.mp4"));
575 let fps = session.meta().frame_rate;
576 let mut last_index = None;
577
578 session.play();
579 run_for(&mut session, &mut last_index, Duration::from_millis(700));
580 let before = session.now();
581 assert!(before > 0.3, "clock stalled at {before:.3}s");
582
583 // Metadata only: no worker is touched, so the indices stay contiguous
584 // across the boundary `run_for` is about to cross.
585 assert!(session.cut_at(1.5), "cut at 1.5 s");
586 run_for(&mut session, &mut last_index, Duration::from_millis(900));
587 let after_cut = session.now();
588 assert!(
589 after_cut > before + 0.6,
590 "the clock stopped across the cut: {before:.3}s -> {after_cut:.3}s"
591 );
592 assert!(
593 last_index.map(|i| f64::from(i) > 1.5 * fps) == Some(true),
594 "playback never reached the cut: {last_index:?}"
595 );
596
597 // Deleting the head clip moves everything after it, so the session reseeks
598 // under the playhead: same timeline position, new source frame, and the
599 // frame numbering restarts at the landing frame.
600 assert!(session.delete_clip(Lane::V1, 0), "drop the head clip");
601 let landed = session.now();
602 assert!(
603 (landed - after_cut).abs() < 0.2,
604 "the delete moved the playhead: {after_cut:.3}s -> {landed:.3}s"
605 );
606 let first = next_frame(&mut session, "the delete reseek").index;
607 assert!(
608 first.abs_diff((landed * fps) as u32) <= 1,
609 "the delete landed at {first} instead of the playhead ({landed:.3}s)"
610 );
611 // No EOS assertion here: `run_for` drains a frame per 8 ms call, far faster
612 // than real time (ledger), so how much timeline is left after it is a race.
613 let mut after_delete = Some(first);
614 run_for(&mut session, &mut after_delete, Duration::from_millis(500));
615 assert!(after_delete > Some(first), "no frames after the delete");
616 assert!(
617 session.now() > landed + 0.3,
618 "the clock stopped after the delete: {landed:.3}s -> {:.3}s",
619 session.now()
620 );
621 eprintln!(
622 "edits: {before:.3}s -> cut -> {after_cut:.3}s -> delete -> {:.3}s of a {:.3}s timeline",
623 session.now(),
624 session.timeline_duration()
625 );
626}
627
628/// Frame count straight from the container, without decoding anything.
629fn frame_count(path: &Path) -> u32 {
630 engine::demux::Demuxer::open(path)
631 .expect("demux")
632 .0
633 .frame_count
634}
635
636/// Import: a second file appended to the timeline, played through as one
637/// stream. No audio needed for the pictures, so this runs anywhere.
638#[test]
639fn import_appends_a_second_source_and_plays_across_the_join() {
640 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
641 let mut session = open(&av);
642 let (fps, first) = (session.meta().frame_rate, session.meta().frame_count);
643 let second = frame_count(&av2);
644 assert_eq!((first, second), (150, 120), "fixtures changed");
645
646 session.import(&av2).expect("test_av2 matches test_av");
647 assert_eq!(session.clip_spans().len(), 2);
648 assert_eq!(
649 session
650 .clip_spans_by_source()
651 .iter()
652 .map(|&(.., s)| s)
653 .collect::<Vec<_>>(),
654 vec![0, 1],
655 "the appended clip plays the imported file"
656 );
657 assert!(
658 (session.timeline_duration() - 9.0).abs() < 1e-9,
659 "5 s + 4 s: {}",
660 session.timeline_duration()
661 );
662
663 // Play the joined timeline whole, keeping the picture at the join.
664 session.seek(0.0);
665 session.play();
666 let deadline = Instant::now() + Duration::from_secs(30);
667 let (mut expect, mut boundary) = (0, None);
668 loop {
669 session.tick();
670 while let Some(frame) = session.try_frame() {
671 assert_eq!(
672 frame.index, expect,
673 "timeline indices must be contiguous across a source join"
674 );
675 if frame.index == first {
676 boundary = Some(frame.bgra);
677 }
678 expect += 1;
679 }
680 if session.is_eos() {
681 break;
682 }
683 assert!(Instant::now() < deadline, "still draining after 30 s");
684 sleep(Duration::from_millis(4));
685 }
686 assert_eq!(expect, first + second, "270 frames, whole and nothing but");
687 // As everywhere else: stop the clock before asserting on landing frames.
688 session.pause();
689 assert!(
690 boundary.expect("no frame at the join") == source_frame(&av2, 0),
691 "timeline frame {first} is not the imported file's frame 0"
692 );
693
694 // Edits across the join keep every clip pointing at its own file: cut one
695 // second into the imported clip, then drop the whole original.
696 assert!(session.cut_at(6.0), "cut 1 s into the imported clip");
697 assert_eq!(session.clip_spans().len(), 3);
698 assert!(session.delete_clip(Lane::V1, 0), "drop the first source");
699 assert_eq!(session.clip_spans_by_source()[0].2, 1);
700 assert!(
701 (session.timeline_duration() - f64::from(second) / fps).abs() < 1e-9,
702 "only the imported file is left: {}",
703 session.timeline_duration()
704 );
705 session.seek(0.0);
706 let landed = next_frame(&mut session, "seek(0.0) after the delete");
707 assert_eq!(landed.index, 0);
708 assert!(
709 landed.bgra == source_frame(&av2, 0),
710 "the delete lost the source mapping"
711 );
712
713 assert!(session.undo(), "undo the delete");
714 assert_eq!(session.clip_spans().len(), 3);
715 let restored = next_frame(&mut session, "undo");
716 assert_eq!(restored.index, 0);
717 assert!(
718 restored.bgra == source_frame(&av, 0),
719 "undo did not restore the first source"
720 );
721}
722
723/// One timeline, one set of parameters: everything else is refused by name and
724/// changes nothing.
725#[test]
726fn import_refuses_what_does_not_match() {
727 let mut session = open(asset("test_av.mp4"));
728
729 // A different *codec* cannot join: one timeline is one kind of source.
730 let err = session
731 .import(&asset("test_vp9.mp4"))
732 .expect_err("VP9 must be refused")
733 .to_string();
734 assert!(err.contains("VP9"), "refusal must name the codec: {err}");
735
736 // A different resolution is no longer among the refusals -- it is placed on
737 // the project canvas instead -- but this file is also silent, and that is.
738 let err = session
739 .import(&asset("test_mismatch.mp4"))
740 .expect_err("a silent file must be refused")
741 .to_string();
742 assert!(err.contains("audio"), "refusal must name the audio: {err}");
743 assert!(
744 !err.contains("640x360"),
745 "a resolution of its own is not a refusal any more: {err}"
746 );
747
748 // Same size and rate, no audio track: the timeline has one.
749 let err = session
750 .import(&asset("test_baseline.mp4"))
751 .expect_err("a silent file must be refused")
752 .to_string();
753 assert!(err.contains("audio"), "refusal must name the audio: {err}");
754
755 assert!(
756 session.import(&asset("no_such_file.mp4")).is_err(),
757 "a missing file is an error, not a panic"
758 );
759 assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");
760 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
761
762 // The mirror: audio into a silent timeline is refused just as loudly.
763 let mut silent = open(asset("test_baseline.mp4"));
764 let err = silent
765 .import(&asset("test_av.mp4"))
766 .expect_err("audio into a silent timeline")
767 .to_string();
768 assert!(err.contains("audio"), "refusal must name the audio: {err}");
769}
770
771/// The user-facing point of a project resolution: media of two sizes on one
772/// timeline, each composed onto the project's own canvas.
773///
774/// 640x360 joins a 1280x720 timeline (it would have been refused before this
775/// slice), and both clips come out of `try_frame` at the project's size --
776/// which is what makes the export, the window and the renderer one shape.
777#[test]
778fn media_of_two_resolutions_share_one_timeline() {
779 let mut session = open(asset("test_baseline.mp4"));
780 assert_eq!(session.resolution(), (1280, 720), "source 0's picture");
781 assert_eq!(session.native_resolution(), (1280, 720));
782 session
783 .import(&asset("test_mismatch.mp4"))
784 .expect("640x360 must join a 1280x720 timeline");
785 // 150 frames of the first file, then 60 of the second, at 30 fps.
786 assert_eq!(session.clip_spans().len(), 2);
787 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
788
789 for (at, what) in [(1.0, "the 1280x720 clip"), (6.0, "the 640x360 clip")] {
790 session.seek(at);
791 let frame = next_frame(&mut session, what);
792 assert_eq!(
793 (frame.width, frame.height),
794 (1280, 720),
795 "{what} did not come out at the project resolution"
796 );
797 assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
798 }
799}
800
801/// The geometry, asserted on the pixels: on a canvas whose aspect the media does
802/// not share, a `Fit` clip is letterboxed -- bars exactly black, picture where
803/// `scale::fit_rect` puts it -- and `Fill` crops the bars away.
804#[test]
805fn a_fitted_clip_is_letterboxed_and_a_filled_one_is_not() {
806 let mut session = open(asset("test_baseline.mp4"));
807 session
808 .import(&asset("test_mismatch.mp4"))
809 .expect("640x360 joins");
810 // A 4:3 project: both clips are 16:9, so both are letterboxed on it. 960x720
811 // holds the whole 640x360 picture as 960x540 with 90 rows of bar either way
812 // (fit_rect's own arithmetic, asserted in scale.rs).
813 assert!(session.set_resolution(960, 720), "4:3 project");
814 session.seek(6.0);
815 let frame = next_frame(&mut session, "the 640x360 clip on a 4:3 canvas");
816 assert_eq!((frame.width, frame.height), (960, 720));
817 let row = |frame: &Frame, y: usize| {
818 frame.bgra[y * 960 * 4..][..960 * 4]
819 .chunks_exact(4)
820 .map(|px| (px[0], px[1], px[2]))
821 .collect::<Vec<_>>()
822 };
823 let black = |row: &[(u8, u8, u8)]| row.iter().all(|&px| px == (0, 0, 0));
824 assert!(black(&row(&frame, 0)), "top bar is not black");
825 assert!(black(&row(&frame, 89)), "the bar stops one row early");
826 assert!(black(&row(&frame, 719)), "bottom bar is not black");
827 assert!(
828 !black(&row(&frame, 360)),
829 "the picture area is black: nothing was composed"
830 );
831 // Same clip, filled: the canvas is covered, so no row is a bar.
832 let (lane, idx) = session.video_clip_at(6.0).expect("a clip at 6 s");
833 assert!(session.set_fit(lane, idx, engine::scale::FitPolicy::Fill));
834 session.seek(6.0);
835 let filled = next_frame(&mut session, "the same clip filled");
836 assert_eq!((filled.width, filled.height), (960, 720));
837 assert!(!black(&row(&filled, 0)), "Fill left a top bar");
838 assert!(!black(&row(&filled, 719)), "Fill left a bottom bar");
839 assert_ne!(
840 row(&frame, 360),
841 row(&filled, 360),
842 "Fill showed the same pixels as Fit: the crop did nothing"
843 );
844}
845
846/// The clip that pays nothing: a project at its media's own size must hand the
847/// decoder's bytes through untouched, not merely equal ones. Same frame, same
848/// bytes, whether or not the composition path exists.
849#[test]
850fn a_project_at_the_media_size_is_the_decoder_untouched() {
851 let mut session = open(asset("test_baseline.mp4"));
852 session.seek(1.0);
853 let frame = next_frame(&mut session, "seek to 1 s");
854 assert_eq!((frame.width, frame.height), (1280, 720));
855 assert_eq!(
856 frame.bgra,
857 source_frame(&asset("test_baseline.mp4"), frame.index),
858 "the pass-through path changed a byte"
859 );
860}
861
862/// The same file twice is two clips of one source -- a source index is handed
863/// out once and reused, which is what keeps clipboard clips valid forever.
864#[test]
865fn importing_one_file_twice_reuses_its_source() {
866 let mut session = open(asset("test_av.mp4"));
867 let av2 = asset("test_av2.mp4");
868 session.import(&av2).expect("first import");
869 session.import(&av2).expect("second import");
870 assert_eq!(
871 session
872 .clip_spans_by_source()
873 .iter()
874 .map(|&(.., s)| s)
875 .collect::<Vec<_>>(),
876 vec![0, 1, 1],
877 "one new source, two clips of it"
878 );
879 assert!(
880 (session.timeline_duration() - 13.0).abs() < 1e-9,
881 "5 s + 4 s + 4 s: {}",
882 session.timeline_duration()
883 );
884}
885
886/// Importing after the timeline has been played out revives the session at the
887/// join, not at wherever the free-running clock got to.
888#[test]
889fn import_at_eos_resumes_into_the_new_clip() {
890 let av2 = asset("test_av2.mp4");
891 let mut session = open(asset("test_av.mp4"));
892 let first = session.meta().frame_count;
893
894 session.play();
895 assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
896 assert!(session.is_eos());
897
898 session.import(&av2).expect("import at EOS");
899 assert!(!session.is_eos(), "the import did not revive the session");
900 let landed = next_frame(&mut session, "import at EOS");
901 assert_eq!(landed.index, first, "resumed at the join");
902 assert!(
903 landed.bgra == source_frame(&av2, 0),
904 "the resume is not showing the imported file"
905 );
906 assert_eq!(
907 drain_to_eof(&mut session).1,
908 Some(first + frame_count(&av2) - 1),
909 "the appended clip did not play out"
910 );
911}
912
913/// A source deleted mid-session: the clip that names it contributes no pictures
914/// and the timeline still ends, instead of stalling on the missing file.
915#[test]
916fn a_vanished_source_is_skipped() {
917 let scratch =
918 std::env::temp_dir().join(format!("video_editor_vanish_{}.mp4", std::process::id()));
919 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
920 let mut session = open(asset("test_av.mp4"));
921 let first = session.meta().frame_count;
922 session.import(&scratch).expect("import the copy");
923 std::fs::remove_file(&scratch).expect("unlink");
924
925 session.seek(0.0);
926 session.play();
927 let (count, last) = drain_to_eof(&mut session);
928 assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
929 assert_eq!(count, first, "the first source still played whole");
930 assert!(session.is_eos(), "the timeline still ends");
931}
932
933/// Importing while the device is running: the import reseeks under the
934/// playhead, so what must not happen is a stall -- the joined timeline still
935/// plays out whole. No audio needed, so this runs anywhere.
936#[test]
937fn import_during_play_does_not_stall() {
938 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
939 let mut session = open(&av);
940 let first = session.meta().frame_count;
941 let mut last_index = None;
942
943 session.play();
944 run_for(&mut session, &mut last_index, Duration::from_millis(300));
945 assert!(last_index.is_some(), "no frames before the import");
946
947 session.import(&av2).expect("import while playing");
948 assert_eq!(session.clip_spans().len(), 2);
949 assert!(session.is_playing(), "the import stopped the clock");
950
951 // From here on the indices go *backwards* once: `run_for` decodes far ahead
952 // of the clock (ledger), and the import reseeks to `now()` -- which is why
953 // this drains with `drain_to_eof` instead of the order-checking `pump`.
954 let (count, last) = drain_to_eof(&mut session);
955 eprintln!("import while playing: {count} more frames, last {last:?}");
956 assert_eq!(
957 last,
958 Some(first + frame_count(&av2) - 1),
959 "the joined timeline did not play out"
960 );
961}
962
963/// An import is *one* undo step: the appended clip goes, the source entry stays
964/// behind (documented, harmless -- source indexes are forever), and the session
965/// is still playable on the restored timeline.
966#[test]
967fn undo_after_import_is_one_step() {
968 let av2 = asset("test_av2.mp4");
969 let mut session = open(asset("test_av.mp4"));
970 session.import(&av2).expect("import");
971 assert_eq!(session.clip_spans().len(), 2);
972 assert!((session.timeline_duration() - 9.0).abs() < 1e-9);
973
974 assert!(session.undo(), "undo the import");
975 assert_eq!(session.clip_spans().len(), 1, "one step, back to one clip");
976 assert!(
977 (session.timeline_duration() - 5.0).abs() < 1e-9,
978 "undo did not restore the duration: {}",
979 session.timeline_duration()
980 );
981
982 // The orphan source is only observable on the project -- `PlaybackSession`
983 // exposes sources through `clip_spans_by_source`, and the undone clip is
984 // exactly the one that named it.
985 let mut project = engine::Project::single(asset("test_av.mp4"), 150);
986 let source = project.import(&av2, 0);
987 assert!(project.append_clip(source, 120));
988 assert!(project.undo());
989 assert_eq!(project.clips().len(), 1);
990 assert_eq!(project.sources().len(), 2, "the source entry stays behind");
991
992 // Still playable: the undo reseeked to the (paused) playhead at zero.
993 session.play();
994 assert_eq!(next_index(&mut session, "undo of an import"), 0);
995}
996
997/// The audio path across a source join: one worker spans both files, so the
998/// clock must keep running at real speed through the boundary. (Whether it is
999/// still the *audio* clock is not observable from outside -- a device that ran
1000/// dry would fall back to wall time at the same speed -- so this catches a
1001/// stall, not a silent fallback.)
1002#[test]
1003#[ignore = "needs a running PipeWire daemon"]
1004fn audio_runs_across_a_source_join() {
1005 let mut session = open(asset("test_av.mp4"));
1006 session.import(&asset("test_av2.mp4")).expect("import");
1007 let first = session.meta().frame_count;
1008
1009 session.seek(4.5); // half a second before the join
1010 session.play();
1011 let mut last_index = None;
1012 run_for(&mut session, &mut last_index, Duration::from_millis(1500));
1013 let now = session.now();
1014 eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
1015 assert!(
1016 (5.4..6.6).contains(&now),
1017 "the clock did not run at real speed across the join: {now:.3}s"
1018 );
1019 assert!(
1020 last_index.map(|i| i > first) == Some(true),
1021 "playback never crossed the join: {last_index:?}"
1022 );
1023 // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
1024 // real time, so the decoder may well have reached 9 s while the clock is at
1025 // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
1026}
1027
1028/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap*
1029/// rather than closing up, and a gap plays: the timeline keeps its length, the
1030/// frame numbering stays contiguous straight through, and every picture over
1031/// the hole is black. No audio needed, so this runs anywhere.
1032#[test]
1033fn a_video_gap_plays_black_without_shortening_the_timeline() {
1034 let path = asset("test_baseline.mp4");
1035 let mut session = open(&path);
1036 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
1037 let whole = session.timeline_duration();
1038
1039 assert!(session.cut_at(2.0), "split at 2 s");
1040 assert!(session.cut_at(3.5), "split at 3.5 s");
1041 assert!(
1042 session.lift_clip(Lane::V1, 1),
1043 "lift the middle picture out"
1044 );
1045 assert_eq!(
1046 session.clip_spans().len(),
1047 2,
1048 "two placements, and a hole between them"
1049 );
1050 assert!(
1051 (session.timeline_duration() - whole).abs() < 1e-9,
1052 "a lift leaves a gap: the timeline is exactly as long as it was"
1053 );
1054
1055 let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
1056 session.seek(0.0);
1057 session.play();
1058 let deadline = Instant::now() + Duration::from_secs(20);
1059 let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32);
1060 loop {
1061 session.tick();
1062 while let Some(frame) = session.try_frame() {
1063 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
1064 let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]);
1065 if (hole..hole_end).contains(&frame.index) {
1066 assert!(is_black, "frame {} is inside the gap", frame.index);
1067 black += 1;
1068 } else {
1069 lit += 1;
1070 }
1071 expect += 1;
1072 }
1073 if session.is_eos() {
1074 break;
1075 }
1076 assert!(Instant::now() < deadline, "still draining after 20 s");
1077 sleep(Duration::from_millis(4));
1078 }
1079 assert_eq!(expect, total, "the whole timeline, gap included");
1080 assert_eq!(black, hole_end - hole, "every frame of the hole was black");
1081 assert!(lit > 0, "and the clips around it still decoded");
1082
1083 // The gap is one undo step back to the clip that was there.
1084 assert!(session.undo());
1085 assert_eq!(session.clip_spans().len(), 3);
1086}
1087
1088/// A hole in the *audio* lane, with the device running: the master clock counts
1089/// samples the device has been fed, so silence has to be fed as real chunks or
1090/// the timeline would stall on the hole. Needs a PipeWire daemon and the output
1091/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`).
1092///
1093/// Muted like every other device test: what it asserts is the clock and the
1094/// frame numbering, both of which count fed samples and not their loudness. The
1095/// silence of a gap is proved off the decoder instead, with no device involved,
1096/// in `audio_segments::a_gap_segment_is_silence_of_its_own_length`.
1097#[test]
1098#[ignore = "needs a running PipeWire daemon"]
1099fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
1100 let mut session = open(asset("test_av.mp4"));
1101 assert!(session.cut_at(1.0), "split at 1 s");
1102 assert!(session.cut_at(2.0), "split at 2 s");
1103 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1104 assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
1105 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1106 let duration = session.timeline_duration();
1107
1108 session.seek(0.0);
1109 let mut last_index = None;
1110 session.play();
1111 // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at
1112 // 1 s, so a stall anywhere inside it cannot hide.
1113 run_for(&mut session, &mut last_index, Duration::from_millis(2_400));
1114 let now = session.now();
1115 assert!(
1116 now > 2.2 && now < duration,
1117 "the clock stalled on the audio gap at {now:.3}s"
1118 );
1119 assert!(
1120 last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true),
1121 "pictures stopped over the silence: {last_index:?}"
1122 );
1123 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
1124}