forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

playback.rs1023 lines, 38.1 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(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(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(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 let err = session
730 .import(&asset("test_mismatch.mp4"))
731 .expect_err("640x360 must be refused")
732 .to_string();
733 assert!(err.contains("640x360"), "refusal must name the size: {err}");
734
735 // Same size and rate, no audio track: the timeline has one.
736 let err = session
737 .import(&asset("test_baseline.mp4"))
738 .expect_err("a silent file must be refused")
739 .to_string();
740 assert!(err.contains("audio"), "refusal must name the audio: {err}");
741
742 assert!(
743 session.import(&asset("no_such_file.mp4")).is_err(),
744 "a missing file is an error, not a panic"
745 );
746 assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");
747 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
748
749 // The mirror: audio into a silent timeline is refused just as loudly.
750 let mut silent = open(asset("test_baseline.mp4"));
751 let err = silent
752 .import(&asset("test_av.mp4"))
753 .expect_err("audio into a silent timeline")
754 .to_string();
755 assert!(err.contains("audio"), "refusal must name the audio: {err}");
756}
757
758/// The same file twice is two clips of one source -- a source index is handed
759/// out once and reused, which is what keeps clipboard clips valid forever.
760#[test]
761fn importing_one_file_twice_reuses_its_source() {
762 let mut session = open(asset("test_av.mp4"));
763 let av2 = asset("test_av2.mp4");
764 session.import(&av2).expect("first import");
765 session.import(&av2).expect("second import");
766 assert_eq!(
767 session
768 .clip_spans_by_source()
769 .iter()
770 .map(|&(.., s)| s)
771 .collect::<Vec<_>>(),
772 vec![0, 1, 1],
773 "one new source, two clips of it"
774 );
775 assert!(
776 (session.timeline_duration() - 13.0).abs() < 1e-9,
777 "5 s + 4 s + 4 s: {}",
778 session.timeline_duration()
779 );
780}
781
782/// Importing after the timeline has been played out revives the session at the
783/// join, not at wherever the free-running clock got to.
784#[test]
785fn import_at_eos_resumes_into_the_new_clip() {
786 let av2 = asset("test_av2.mp4");
787 let mut session = open(asset("test_av.mp4"));
788 let first = session.meta().frame_count;
789
790 session.play();
791 assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
792 assert!(session.is_eos());
793
794 session.import(&av2).expect("import at EOS");
795 assert!(!session.is_eos(), "the import did not revive the session");
796 let landed = next_frame(&mut session, "import at EOS");
797 assert_eq!(landed.index, first, "resumed at the join");
798 assert!(
799 landed.bgra == source_frame(&av2, 0),
800 "the resume is not showing the imported file"
801 );
802 assert_eq!(
803 drain_to_eof(&mut session).1,
804 Some(first + frame_count(&av2) - 1),
805 "the appended clip did not play out"
806 );
807}
808
809/// A source deleted mid-session: the clip that names it contributes no pictures
810/// and the timeline still ends, instead of stalling on the missing file.
811#[test]
812fn a_vanished_source_is_skipped() {
813 let scratch =
814 std::env::temp_dir().join(format!("video_editor_vanish_{}.mp4", std::process::id()));
815 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
816 let mut session = open(asset("test_av.mp4"));
817 let first = session.meta().frame_count;
818 session.import(&scratch).expect("import the copy");
819 std::fs::remove_file(&scratch).expect("unlink");
820
821 session.seek(0.0);
822 session.play();
823 let (count, last) = drain_to_eof(&mut session);
824 assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
825 assert_eq!(count, first, "the first source still played whole");
826 assert!(session.is_eos(), "the timeline still ends");
827}
828
829/// Importing while the device is running: the import reseeks under the
830/// playhead, so what must not happen is a stall -- the joined timeline still
831/// plays out whole. No audio needed, so this runs anywhere.
832#[test]
833fn import_during_play_does_not_stall() {
834 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
835 let mut session = open(&av);
836 let first = session.meta().frame_count;
837 let mut last_index = None;
838
839 session.play();
840 run_for(&mut session, &mut last_index, Duration::from_millis(300));
841 assert!(last_index.is_some(), "no frames before the import");
842
843 session.import(&av2).expect("import while playing");
844 assert_eq!(session.clip_spans().len(), 2);
845 assert!(session.is_playing(), "the import stopped the clock");
846
847 // From here on the indices go *backwards* once: `run_for` decodes far ahead
848 // of the clock (ledger), and the import reseeks to `now()` -- which is why
849 // this drains with `drain_to_eof` instead of the order-checking `pump`.
850 let (count, last) = drain_to_eof(&mut session);
851 eprintln!("import while playing: {count} more frames, last {last:?}");
852 assert_eq!(
853 last,
854 Some(first + frame_count(&av2) - 1),
855 "the joined timeline did not play out"
856 );
857}
858
859/// An import is *one* undo step: the appended clip goes, the source entry stays
860/// behind (documented, harmless -- source indexes are forever), and the session
861/// is still playable on the restored timeline.
862#[test]
863fn undo_after_import_is_one_step() {
864 let av2 = asset("test_av2.mp4");
865 let mut session = open(asset("test_av.mp4"));
866 session.import(&av2).expect("import");
867 assert_eq!(session.clip_spans().len(), 2);
868 assert!((session.timeline_duration() - 9.0).abs() < 1e-9);
869
870 assert!(session.undo(), "undo the import");
871 assert_eq!(session.clip_spans().len(), 1, "one step, back to one clip");
872 assert!(
873 (session.timeline_duration() - 5.0).abs() < 1e-9,
874 "undo did not restore the duration: {}",
875 session.timeline_duration()
876 );
877
878 // The orphan source is only observable on the project -- `PlaybackSession`
879 // exposes sources through `clip_spans_by_source`, and the undone clip is
880 // exactly the one that named it.
881 let mut project = engine::Project::single(asset("test_av.mp4"), 150);
882 let source = project.import(&av2, 0);
883 assert!(project.append_clip(source, 120));
884 assert!(project.undo());
885 assert_eq!(project.clips().len(), 1);
886 assert_eq!(project.sources().len(), 2, "the source entry stays behind");
887
888 // Still playable: the undo reseeked to the (paused) playhead at zero.
889 session.play();
890 assert_eq!(next_index(&mut session, "undo of an import"), 0);
891}
892
893/// The audio path across a source join: one worker spans both files, so the
894/// clock must keep running at real speed through the boundary. (Whether it is
895/// still the *audio* clock is not observable from outside -- a device that ran
896/// dry would fall back to wall time at the same speed -- so this catches a
897/// stall, not a silent fallback.)
898#[test]
899#[ignore = "needs a running PipeWire daemon"]
900fn audio_runs_across_a_source_join() {
901 let mut session = open(asset("test_av.mp4"));
902 session.import(&asset("test_av2.mp4")).expect("import");
903 let first = session.meta().frame_count;
904
905 session.seek(4.5); // half a second before the join
906 session.play();
907 let mut last_index = None;
908 run_for(&mut session, &mut last_index, Duration::from_millis(1500));
909 let now = session.now();
910 eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
911 assert!(
912 (5.4..6.6).contains(&now),
913 "the clock did not run at real speed across the join: {now:.3}s"
914 );
915 assert!(
916 last_index.map(|i| i > first) == Some(true),
917 "playback never crossed the join: {last_index:?}"
918 );
919 // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
920 // real time, so the decoder may well have reached 9 s while the clock is at
921 // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
922}
923
924/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap*
925/// rather than closing up, and a gap plays: the timeline keeps its length, the
926/// frame numbering stays contiguous straight through, and every picture over
927/// the hole is black. No audio needed, so this runs anywhere.
928#[test]
929fn a_video_gap_plays_black_without_shortening_the_timeline() {
930 let path = asset("test_baseline.mp4");
931 let mut session = open(&path);
932 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
933 let whole = session.timeline_duration();
934
935 assert!(session.cut_at(2.0), "split at 2 s");
936 assert!(session.cut_at(3.5), "split at 3.5 s");
937 assert!(
938 session.lift_clip(Lane::Video, 1),
939 "lift the middle picture out"
940 );
941 assert_eq!(
942 session.clip_spans().len(),
943 2,
944 "two placements, and a hole between them"
945 );
946 assert!(
947 (session.timeline_duration() - whole).abs() < 1e-9,
948 "a lift leaves a gap: the timeline is exactly as long as it was"
949 );
950
951 let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
952 session.seek(0.0);
953 session.play();
954 let deadline = Instant::now() + Duration::from_secs(20);
955 let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32);
956 loop {
957 session.tick();
958 while let Some(frame) = session.try_frame() {
959 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
960 let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]);
961 if (hole..hole_end).contains(&frame.index) {
962 assert!(is_black, "frame {} is inside the gap", frame.index);
963 black += 1;
964 } else {
965 lit += 1;
966 }
967 expect += 1;
968 }
969 if session.is_eos() {
970 break;
971 }
972 assert!(Instant::now() < deadline, "still draining after 20 s");
973 sleep(Duration::from_millis(4));
974 }
975 assert_eq!(expect, total, "the whole timeline, gap included");
976 assert_eq!(black, hole_end - hole, "every frame of the hole was black");
977 assert!(lit > 0, "and the clips around it still decoded");
978
979 // The gap is one undo step back to the clip that was there.
980 assert!(session.undo());
981 assert_eq!(session.clip_spans().len(), 3);
982}
983
984/// A hole in the *audio* lane, with the device running: the master clock counts
985/// samples the device has been fed, so silence has to be fed as real chunks or
986/// the timeline would stall on the hole. Needs a PipeWire daemon and the output
987/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`).
988///
989/// Muted like every other device test: what it asserts is the clock and the
990/// frame numbering, both of which count fed samples and not their loudness. The
991/// silence of a gap is proved off the decoder instead, with no device involved,
992/// in `audio_segments::a_gap_segment_is_silence_of_its_own_length`.
993#[test]
994#[ignore = "needs a running PipeWire daemon"]
995fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
996 let mut session = open(asset("test_av.mp4"));
997 assert!(session.cut_at(1.0), "split at 1 s");
998 assert!(session.cut_at(2.0), "split at 2 s");
999 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1000 assert!(
1001 session.lift_clip(Lane::Audio, 1),
1002 "lift the middle sound out"
1003 );
1004 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1005 let duration = session.timeline_duration();
1006
1007 session.seek(0.0);
1008 let mut last_index = None;
1009 session.play();
1010 // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at
1011 // 1 s, so a stall anywhere inside it cannot hide.
1012 run_for(&mut session, &mut last_index, Duration::from_millis(2_400));
1013 let now = session.now();
1014 assert!(
1015 now > 2.2 && now < duration,
1016 "the clock stalled on the audio gap at {now:.3}s"
1017 );
1018 assert!(
1019 last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true),
1020 "pictures stopped over the silence: {last_index:?}"
1021 );
1022 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
1023}