forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

playback.rs1890 lines, 75.9 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::fs::File;
11use std::os::fd::AsRawFd;
12use std::path::{Path, PathBuf};
13use std::thread::sleep;
14use std::time::{Duration, Instant};
15
16use engine::export::{ExportSettings, Format};
17use engine::project::Lane;
18use engine::scratch::Scratch;
19use engine::{Codec, DecodeSession, Frame, PlaybackSession};
20
21fn asset(name: &str) -> PathBuf {
22 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
23 .join("../../assets")
24 .join(name)
25}
26
27/// Opens a session the way every test here wants one: silent. The suite plays
28/// real files through the real device, so without this a `cargo test` is two
29/// minutes of noise out of the speakers of whoever ran it.
30///
31/// Muting is the gain knob, not a pause and not a fake device: the stream is
32/// still connected, the daemon still schedules it, the samples are still
33/// decoded, written, and handed over -- only the last multiply before the
34/// device is zero. Every clock, `fed` and `played_out` assertion below is
35/// therefore measuring exactly what it measured when this was audible.
36fn open(path: impl AsRef<Path>) -> PlaybackSession {
37 let session = PlaybackSession::open(path).expect("open");
38 // False for the silent fixtures, which have no device to quieten.
39 session.set_gain(0.0);
40 session
41}
42
43/// One render tick of a front-end: advance the clock, take whatever frames are
44/// due. Returns the highest frame index seen so far.
45fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) {
46 session.tick();
47 let target = session.now() * session.meta().frame_rate;
48 while let Some(frame) = session.try_frame() {
49 if let Some(previous) = *last_index {
50 // One at a time, in order. Every session here is a *pull* consumer
51 // -- `open` leaves `drop_late_pictures` off -- and such a caller is
52 // owed every frame of the range it asked for, which is the contract
53 // an export and the file-level API rest on. Only a session told it
54 // is being watched in real time may skip, and the two tests that
55 // turn that on take their frames through `next_index` instead.
56 assert_eq!(
57 frame.index,
58 previous + 1,
59 "frames must arrive in index order"
60 );
61 }
62 *last_index = Some(frame.index);
63 // Stop at the first frame past the clock; the real app holds it for the
64 // next tick, we simply stop draining.
65 if f64::from(frame.index) > target {
66 return;
67 }
68 }
69}
70
71/// Pumps for `duration` of wall time at roughly a display refresh.
72fn run_for(session: &mut PlaybackSession, last_index: &mut Option<u32>, duration: Duration) {
73 let deadline = Instant::now() + duration;
74 while Instant::now() < deadline {
75 pump(session, last_index);
76 sleep(Duration::from_millis(8));
77 }
78}
79
80fn plays_at_real_speed(name: &str) {
81 let path = asset(name);
82 let mut session = open(&path);
83 assert_eq!(session.now(), 0.0, "a fresh session starts at zero");
84 assert!(!session.is_playing(), "a fresh session starts paused");
85 let mut last_index = None;
86
87 session.play();
88 let started = Instant::now();
89 run_for(&mut session, &mut last_index, Duration::from_secs(2));
90 let (played, wall) = (session.now(), started.elapsed().as_secs_f64());
91 eprintln!("{name}: clock {played:.3}s over {wall:.3}s wall");
92 assert!(
93 (played - wall).abs() < wall * 0.15,
94 "clock ran at the wrong speed: {played:.3}s in {wall:.3}s"
95 );
96 assert!(last_index.is_some(), "no frames arrived");
97
98 session.pause();
99 let frozen = session.now();
100 run_for(&mut session, &mut last_index, Duration::from_millis(300));
101 assert!(
102 (session.now() - frozen).abs() < 0.025,
103 "paused clock moved: {frozen:.3}s -> {:.3}s",
104 session.now()
105 );
106
107 session.play();
108 run_for(&mut session, &mut last_index, Duration::from_millis(500));
109 let resumed = session.now();
110 assert!(
111 resumed > frozen + 0.3,
112 "clock did not resume: {frozen:.3}s -> {resumed:.3}s"
113 );
114 // No time was invented across the pause: 2.5 s of playing, not 2.8 s.
115 assert!(
116 resumed < wall + 0.7,
117 "the pause leaked into the timeline: {resumed:.3}s"
118 );
119}
120
121#[test]
122fn video_only_plays_at_real_speed() {
123 plays_at_real_speed("test_baseline.mp4");
124}
125
126#[test]
127fn audio_video_plays_at_real_speed() {
128 plays_at_real_speed("test_av.mp4");
129}
130
131/// The next frame off the (post-seek, freshly opened) channel.
132fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame {
133 let deadline = Instant::now() + Duration::from_secs(10);
134 loop {
135 if let Some(frame) = session.try_frame() {
136 return frame;
137 }
138 assert!(Instant::now() < deadline, "no frame after {what}");
139 sleep(Duration::from_millis(4));
140 }
141}
142
143fn next_index(session: &mut PlaybackSession, what: &str) -> u32 {
144 next_frame(session, what).index
145}
146
147/// Ticks like a front-end but takes every frame as fast as the decoder makes
148/// them, until the timeline is played out. Returns how many arrived and the
149/// last index.
150fn drain_to_eof(session: &mut PlaybackSession) -> (u32, Option<u32>) {
151 let deadline = Instant::now() + Duration::from_secs(20);
152 let (mut count, mut last) = (0, None);
153 loop {
154 session.tick();
155 while let Some(frame) = session.try_frame() {
156 count += 1;
157 last = Some(frame.index);
158 }
159 if session.is_eos() {
160 return (count, last);
161 }
162 assert!(Instant::now() < deadline, "still draining after 20 s");
163 sleep(Duration::from_millis(4));
164 }
165}
166
167/// The pixels of one source frame, decoded on its own -- the reference a
168/// timeline frame is checked against.
169fn source_frame(path: &Path, index: u32) -> Vec<u8> {
170 let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range");
171 let frame = rx
172 .recv_timeout(Duration::from_secs(10))
173 .expect("reference frame");
174 assert_eq!(frame.index, index, "open_range starts where it is told");
175 frame.bgra
176}
177
178/// Wall-clock seek: no audio track, so this runs anywhere.
179#[test]
180fn seek_repositions_video_and_clock() {
181 let mut session = open(asset("test_baseline.mp4"));
182 let fps = session.meta().frame_rate;
183 let mut last_index = None;
184
185 session.play();
186 run_for(&mut session, &mut last_index, Duration::from_millis(500));
187
188 session.seek(3.0);
189 assert!(
190 (session.now() - 3.0).abs() < 0.05,
191 "clock at {}",
192 session.now()
193 );
194 assert_eq!(
195 next_index(&mut session, "seek(3.0)"),
196 (3.0 * fps) as u32,
197 "the first frame after a seek is the target frame"
198 );
199 sleep(Duration::from_millis(200));
200 assert!(session.now() > 3.05, "clock stalled at {}", session.now());
201
202 // Run it out, then seek back: the old workers are gone, not steered.
203 let last_frame = session.meta().frame_count - 1;
204 assert_eq!(drain_to_eof(&mut session).1, Some(last_frame));
205 session.seek(0.0);
206 assert_eq!(next_index(&mut session, "seek(0.0) after EOF"), 0);
207 assert!(session.now() < 0.2, "clock at {}", session.now());
208}
209
210/// Past the end lands on the last frame instead of hanging, and the clock keeps
211/// running -- with audio that means falling through to wall time, because the
212/// device is never fed another sample.
213#[test]
214fn seek_past_the_end_clamps() {
215 let mut session = open(asset("test_av.mp4"));
216 let meta = *session.meta();
217 let duration = f64::from(meta.frame_count) / meta.frame_rate;
218
219 session.play();
220 session.seek(999.0);
221 assert!(
222 (session.now() - duration).abs() < 0.05,
223 "clock at {} for a {duration}s file",
224 session.now()
225 );
226 assert_eq!(
227 next_index(&mut session, "seek(999.0)"),
228 meta.frame_count - 1
229 );
230
231 let landed = session.now();
232 let deadline = Instant::now() + Duration::from_secs(2);
233 while session.now() <= landed + 0.05 {
234 session.tick();
235 assert!(Instant::now() < deadline, "clock froze at {landed}");
236 sleep(Duration::from_millis(8));
237 }
238}
239
240/// Scrubbing: seeks with no time in between must neither panic nor leave the
241/// abandoned workers behind, and the last one still wins.
242#[test]
243fn rapid_seeks_settle_on_the_last_one() {
244 let mut session = open(asset("test_av.mp4"));
245 let fps = session.meta().frame_rate;
246 let mut last_index = None;
247
248 session.play();
249 run_for(&mut session, &mut last_index, Duration::from_millis(300));
250 let before = session.live_workers();
251
252 for t in [4.0, 1.0, 3.5, 0.5, 2.0] {
253 session.seek(t);
254 }
255 assert_eq!(
256 next_index(&mut session, "5 rapid seeks"),
257 (2.0 * fps) as u32
258 );
259
260 sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
261 let after = session.live_workers();
262 eprintln!("rapid seeks: {before} workers -> {after}");
263 assert!(
264 after <= before + 3,
265 "workers piled up: {before} workers -> {after}"
266 );
267}
268
269/// The storm the deferred open exists for: 40 seeks with nothing in between.
270/// Each one abandons a worker and starts another, and since the open moved onto
271/// the worker (`DecodeSession::open_worker_deferred`) not one of them reads the
272/// file on this thread -- so the whole storm is 40 thread spawns, the parked
273/// workers are still reaped as they go (the session's own count says so), and
274/// the last seek still decides what is on screen.
275#[test]
276fn a_storm_of_seeks_stays_bounded_and_the_last_one_wins() {
277 let mut session = open(asset("test_av.mp4"));
278 let fps = session.meta().frame_rate;
279 let mut last_index = None;
280
281 session.play();
282 run_for(&mut session, &mut last_index, Duration::from_millis(300));
283 let before = session.live_workers();
284
285 let storm = Instant::now();
286 for i in 0..39 {
287 session.seek(f64::from(i % 5) * 0.8);
288 }
289 session.seek(2.0);
290 let issued = storm.elapsed();
291 eprintln!("40 seeks issued in {issued:?} ({before} workers before)");
292 assert!(
293 issued < Duration::from_secs(1),
294 "40 seeks cost the caller {issued:?} -- a seek is opening a file again"
295 );
296 assert_eq!(
297 next_index(&mut session, "40 rapid seeks"),
298 (2.0 * fps) as u32,
299 "the last seek is the one that decides"
300 );
301
302 sleep(Duration::from_millis(500)); // abandoned workers exit within an AU
303 let after = session.live_workers();
304 eprintln!("seek storm: {before} workers -> {after}");
305 assert!(
306 after <= before + 3,
307 "the retired list grew with the storm: {before} workers -> {after}"
308 );
309}
310
311/// The audio path proper: needs a PipeWire daemon and the output plugin next to
312/// the test binary (`LD_LIBRARY_PATH=target/release`).
313#[test]
314#[ignore = "needs a running PipeWire daemon"]
315fn seek_keeps_the_audio_clock() {
316 let mut session = open(asset("test_av.mp4"));
317 let meta = *session.meta();
318 let mut last_index = None;
319
320 session.play();
321 run_for(&mut session, &mut last_index, Duration::from_secs(1));
322
323 session.seek(3.0);
324 assert!(
325 (session.now() - 3.0).abs() < 0.05,
326 "clock at {}",
327 session.now()
328 );
329 // From here on the *sound* is what the clock counts, and the sound restarts
330 // at once -- the video decoder's reopen (up to a VA-API init) happens
331 // underneath a stream that is already playing, so the window `next_index`
332 // spends waiting for the first picture is time the timeline really moved
333 // through. Measured against the wall rather than assumed free: counting it
334 // is the fix for the offset an edit-while-playing used to leave behind
335 // (`invalidation.rs`), where the clock re-anchored onto an empty ring and
336 // the picture stayed that far behind the sound for good.
337 let from = Instant::now();
338 let first = next_index(&mut session, "seek(3.0)");
339 assert_eq!(first, (3.0 * meta.frame_rate) as u32);
340 let mut after_seek = None;
341 run_for(&mut session, &mut after_seek, Duration::from_millis(600));
342 let advanced = session.now();
343 let real = from.elapsed().as_secs_f64();
344 eprintln!(
345 "seek(3.0) -> {advanced:.3}s after {real:.3}s of real time, frames {first}..={after_seek:?}"
346 );
347 assert!(
348 (3.0 + real - 0.35..3.0 + real + 0.35).contains(&advanced),
349 "clock did not run at real speed after the seek: {advanced:.3}s after {real:.3}s"
350 );
351
352 // Everything from the target on, and nothing before it: ~2 s of frames.
353 let (drained, last) = drain_to_eof(&mut session);
354 let total = 1 + after_seek.map_or(0, |i| i - first) + drained;
355 eprintln!("frames from 3.0s to EOF: {total}");
356 // `run_for` pumps faster than real time, so it may have hit EOF by itself.
357 assert_eq!(last.or(after_seek), Some(meta.frame_count - 1), "no EOF");
358 assert!(
359 (55..=65).contains(&total),
360 "expected ~60 frames left, got {total}"
361 );
362
363 // A full second run after EOF, from zero.
364 session.seek(0.0);
365 session.play();
366 let mut second = None;
367 run_for(&mut session, &mut second, Duration::from_millis(800));
368 assert_eq!(second.map(|i| i > 0), Some(true), "second run stalled");
369 assert!(session.now() > 0.5, "second run clock at {}", session.now());
370 assert_eq!(
371 drain_to_eof(&mut session).1.or(second),
372 Some(meta.frame_count - 1),
373 "second run did not finish"
374 );
375}
376
377/// Drops `path` out of the page cache, so the next read of it is a real disk
378/// read. `posix_fadvise(POSIX_FADV_DONTNEED)`, glibc's own and declared here
379/// rather than pulled in as a dependency for one call.
380fn evict(path: &Path) {
381 unsafe extern "C" {
382 fn posix_fadvise(fd: i32, offset: i64, len: i64, advice: i32) -> i32;
383 }
384 let file = File::open(path).expect("open to evict");
385 // 0 length is "to the end of the file"; 4 is POSIX_FADV_DONTNEED on Linux.
386 let rc = unsafe { posix_fadvise(file.as_raw_fd(), 0, 0, 4) };
387 assert_eq!(rc, 0, "could not evict {}", path.display());
388}
389
390/// What a seek costs the *caller* when the sound has to be opened again off a
391/// cold page cache -- the audio half of the move
392/// [`a_storm_of_seeks_stays_bounded_and_the_last_one_wins`] measures for the
393/// picture. That open is a `pread` per track (21 s on a cold 25 GB film,
394/// measured at the seat) and it used to run on whoever called `seek`, which in
395/// the editor is the thread that paints: one ruler click froze the window for
396/// the whole of it. On the feeder it is a thread spawn, whatever the file.
397///
398/// And the clock still anchors on the first real sample, which is the invariant
399/// the wait threatens: the timeline holds where the seek put it for however
400/// long the open takes, and starts counting from *there* rather than from the
401/// silence the device played meanwhile.
402///
403/// `assets/test_av.mp4` by default, which makes this a regression guard;
404/// `EDITH_COLD_FILM=<a big film>` makes it the measurement.
405#[test]
406#[ignore = "needs a running PipeWire daemon"]
407fn a_cold_audio_open_does_not_block_the_seek() {
408 let path = std::env::var_os("EDITH_COLD_FILM")
409 .map(PathBuf::from)
410 .unwrap_or_else(|| asset("test_av.mp4"));
411 let mut session = open(&path);
412 let target = session.timeline_duration() * 0.5;
413 let mut last_index = None;
414 session.play();
415 run_for(&mut session, &mut last_index, Duration::from_millis(300));
416
417 // The seek's own reads and nothing else: the open above warmed every byte
418 // of this file that anything here touches.
419 evict(&path);
420 let issued = Instant::now();
421 session.seek(target);
422 let blocked = issued.elapsed();
423 eprintln!(
424 "cold seek on {}: caller blocked {blocked:?}",
425 path.display()
426 );
427 assert!(
428 blocked < Duration::from_millis(10),
429 "the caller opened the file itself: seek blocked {blocked:?}"
430 );
431 assert!(
432 (session.now() - target).abs() < 0.05,
433 "the seek did not land: clock at {}",
434 session.now()
435 );
436
437 // The sound arrives when it arrives, and the clock does not move until it
438 // does. Long deadline: that is the point of the test.
439 let waited = Instant::now();
440 let deadline = waited + Duration::from_secs(120);
441 while session.now() <= target + 0.001 {
442 session.tick();
443 while session.try_frame().is_some() {}
444 assert!(
445 Instant::now() < deadline,
446 "the clock never moved after a cold seek"
447 );
448 sleep(Duration::from_millis(8));
449 }
450 let (moved, waited) = (session.now(), waited.elapsed().as_secs_f64());
451 eprintln!("clock moved to {moved:.3}s (target {target:.3}s) after {waited:.3}s of open");
452 assert!(
453 moved - target < 0.5,
454 "the open leaked into the timeline: {waited:.3}s of it put the clock at \
455 {moved:.3}s instead of {target:.3}s"
456 );
457}
458
459/// The seek storm the *ear* is in: 20 random seeks into a cold file, each
460/// resuming playback, and not one starved quantum out of the device.
461///
462/// The device is started by the feeder's first real sample, never by the intent
463/// to play ([`PlaybackSession::play`] and the seek's own resume), because an
464/// audio open is not free -- seconds, on a cold film -- and a stream made active
465/// over an empty ring plays its own silence and counts every quantum of it as
466/// an underrun. It sounds identical either way; what it destroys is the meaning
467/// of the count, which is the only thing that says the decoder is keeping up.
468/// This is the regression guard for that: cold storm, count must be nil.
469///
470/// `assets/test_av.mp4` by default; `EDITH_COLD_FILM=<a big film>` and
471/// `EDITH_SEEKS=<n>` make it the measurement (the rubric's floor is 50 seeks
472/// into a two-hour film).
473#[test]
474#[ignore = "needs a running PipeWire daemon"]
475fn a_cold_seek_storm_starves_no_quantum() {
476 let path = std::env::var_os("EDITH_COLD_FILM")
477 .map(PathBuf::from)
478 .unwrap_or_else(|| asset("test_av.mp4"));
479 let seeks: u32 = std::env::var("EDITH_SEEKS")
480 .ok()
481 .and_then(|n| n.parse().ok())
482 .unwrap_or(20);
483 let mut session = open(&path);
484 let duration = session.timeline_duration();
485 let mut last_index = None;
486 session.play();
487 run_for(&mut session, &mut last_index, Duration::from_millis(300));
488 // Only a machine with the plugin *and* a daemon can starve at all; without
489 // one the session plays wall-paced and there is nothing to measure.
490 let Some((before, _)) = session.audio_underruns() else {
491 eprintln!("no audio device: seek storm not measured");
492 return;
493 };
494 evict(&path);
495
496 // xorshift64 off a fixed seed: the same storm every run, so two runs of
497 // this are comparable without a dependency to draw the numbers from.
498 let mut rng = 0x2545_f491_4f6c_dd1du64;
499 let storm = Instant::now();
500 for i in 0..seeks {
501 rng ^= rng << 13;
502 rng ^= rng >> 7;
503 rng ^= rng << 17;
504 // Off the end of the timeline is a seek with nothing to play; keep the
505 // storm inside the film.
506 let target = duration * 0.98 * (rng >> 11) as f64 / (1u64 << 53) as f64;
507 session.seek(target);
508 // The sound has to *come back*, which is the other half of this: a
509 // device that never plays starves no quantum either, so the count below
510 // means nothing unless every seek resumed. The clock is held at the
511 // target until the first real sample is queued, so it moving is the
512 // sound arriving ([`PlaybackSession::tick`]).
513 let mut landed = None;
514 let deadline = Instant::now() + Duration::from_secs(20);
515 while session.now() <= target + 0.05 {
516 pump(&mut session, &mut landed);
517 assert!(
518 Instant::now() < deadline,
519 "seek {i} to {target:.1}s never resumed: the clock stood still"
520 );
521 sleep(Duration::from_millis(8));
522 }
523 // ...and then plays for a moment, which is where a late decoder shows.
524 run_for(&mut session, &mut landed, Duration::from_millis(300));
525 }
526 let (now, last) = session.audio_underruns().expect("device still open");
527 let underruns = now - before;
528 eprintln!(
529 "{seeks} cold seeks into {} in {:?}: {underruns} underruns ({before} before the storm, \
530 last at {last:?})",
531 path.display(),
532 storm.elapsed()
533 );
534 assert_eq!(
535 underruns, 0,
536 "the device starved during the storm: {underruns} quanta of silence it \
537 counted as a late decoder"
538 );
539}
540
541/// What a *drag* costs in threads: 200 scrub steps across a cold film with no
542/// wait between them, which is a ruler dragged from end to end. Every step
543/// abandons an audio open and starts another, and an abandoned one used to run
544/// its read to the end anyway -- on a cold film that is seconds each, so the
545/// threads pile up behind the drag rather than following it.
546///
547/// The session's own count is the oracle (`live_workers`), and the process
548/// thread count beside it says what the OS saw.
549#[test]
550#[ignore = "needs a running PipeWire daemon"]
551fn a_cold_scrub_does_not_pile_up_threads() {
552 let path = std::env::var_os("EDITH_COLD_FILM")
553 .map(PathBuf::from)
554 .unwrap_or_else(|| asset("test_av.mp4"));
555 let steps: u32 = std::env::var("EDITH_STEPS")
556 .ok()
557 .and_then(|n| n.parse().ok())
558 .unwrap_or(200);
559 let mut session = open(&path);
560 let duration = session.timeline_duration();
561 let mut last_index = None;
562 session.play();
563 run_for(&mut session, &mut last_index, Duration::from_millis(300));
564 evict(&path);
565
566 let (mut peak, mut peak_os) = (0, 0);
567 let scrub = Instant::now();
568 for step in 0..steps {
569 session.seek(duration * f64::from(step) / f64::from(steps));
570 session.tick();
571 while session.try_frame().is_some() {}
572 peak = peak.max(session.live_workers());
573 peak_os = peak_os.max(os_threads());
574 sleep(Duration::from_millis(16)); // a drag reports at ~60 Hz
575 }
576 eprintln!(
577 "{steps} cold scrub steps in {:?}: peak {peak} session workers, {peak_os} process threads",
578 scrub.elapsed()
579 );
580 // The peak is *reported*, not asserted: three runs of one build over the
581 // same film measured 14, 101 and 137, because what decides it is how much
582 // disk the rest of the machine is using while the opens run. What the
583 // session owes is a different question and a real one -- every worker the
584 // drag started has to end, or a drag is a leak.
585 let deadline = Instant::now() + Duration::from_secs(120);
586 while session.live_workers() > 2 {
587 assert!(
588 Instant::now() < deadline,
589 "the scrub leaked workers: {} still running two minutes on",
590 session.live_workers()
591 );
592 sleep(Duration::from_millis(50));
593 }
594 eprintln!("all but {} of them returned", session.live_workers());
595}
596
597/// Threads in this process, out of `/proc/self/status`. Only ever a report
598/// beside the session's own count -- a suite decoding other files at the same
599/// time moves this number without touching the session under test.
600fn os_threads() -> usize {
601 std::fs::read_to_string("/proc/self/status")
602 .ok()
603 .and_then(|status| {
604 status
605 .lines()
606 .find_map(|line| line.strip_prefix("Threads:")?.trim().parse().ok())
607 })
608 .unwrap_or(0)
609}
610
611/// The edit list end to end: two cuts, drop the middle clip, play the result.
612/// What comes out is one contiguous timeline whose *pictures* skip the hole --
613/// no audio needed, so this runs anywhere.
614#[test]
615fn edits_traverse_cuts() {
616 let path = asset("test_baseline.mp4");
617 let mut session = open(&path);
618 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
619 let whole = f64::from(total) / fps;
620 assert!((session.timeline_duration() - whole).abs() < 1e-9);
621 assert_eq!(session.clip_spans(), vec![(0.0, whole)]);
622
623 assert!(session.cut_at(2.0), "cut at 2 s");
624 assert!(session.cut_at(3.5), "cut at 3.5 s");
625 assert!(
626 !session.cut_at(2.0),
627 "the same frame twice: already a boundary"
628 );
629 assert!(!session.cut_at(0.0), "nothing before the first frame");
630 assert_eq!(session.clip_spans().len(), 3);
631 // Cuts are metadata: the timeline is the same length as before.
632 assert!((session.timeline_duration() - whole).abs() < 1e-9);
633
634 let (cut, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
635 assert!(session.delete_clip(Lane::V1, 1), "drop the middle clip");
636 let kept = total - (hole_end - cut);
637 assert_eq!(session.clip_spans().len(), 2);
638 assert!(
639 (session.timeline_duration() - f64::from(kept) / fps).abs() < 1e-9,
640 "duration after the delete: {}",
641 session.timeline_duration()
642 );
643
644 // Play the whole edited timeline from the top.
645 session.seek(0.0);
646 session.play();
647 let deadline = Instant::now() + Duration::from_secs(20);
648 let (mut expect, mut boundary) = (0, None);
649 loop {
650 session.tick();
651 while let Some(frame) = session.try_frame() {
652 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
653 if frame.index == cut {
654 boundary = Some(frame.bgra);
655 }
656 expect += 1;
657 }
658 if session.is_eos() {
659 break;
660 }
661 assert!(Instant::now() < deadline, "still draining after 20 s");
662 sleep(Duration::from_millis(4));
663 }
664 assert_eq!(expect, kept, "the edited timeline, whole and nothing but");
665 // From here the playhead has to stand still: an edit reseeks to *now*, so a
666 // running clock would move the frame these assertions expect.
667 session.pause();
668
669 // The frames behind those indices skipped the deleted range: the picture at
670 // the boundary is source `hole_end`, not the source frame with that number.
671 let boundary = boundary.expect("no frame at the cut");
672 assert!(
673 boundary == source_frame(&path, hole_end),
674 "the boundary frame is not source {hole_end}"
675 );
676 assert!(
677 boundary != source_frame(&path, cut),
678 "the deleted range is still being decoded"
679 );
680
681 // Seek into the surviving second clip: timeline 3.0 s is source 3.0 s + the
682 // 1.5 s hole.
683 session.seek(3.0);
684 let landed = next_frame(&mut session, "seek(3.0) after edits");
685 assert_eq!(landed.index, (3.0 * fps) as u32);
686 assert!(
687 landed.bgra == source_frame(&path, (4.5 * fps) as u32),
688 "the seek landed on the wrong source frame"
689 );
690 assert!(!session.is_eos(), "a seek revives a played-out session");
691
692 assert!(session.undo(), "undo the delete");
693 assert_eq!(session.clip_spans().len(), 3);
694 assert!(
695 (session.timeline_duration() - whole).abs() < 1e-9,
696 "undo did not restore the duration: {}",
697 session.timeline_duration()
698 );
699 // The undo reseeks to the (still paused) playhead, and on the restored
700 // timeline 3.0 s is source 3.0 s again -- the hole is back.
701 let restored = next_frame(&mut session, "undo");
702 assert_eq!(restored.index, (3.0 * fps) as u32);
703 assert!(
704 restored.bgra == source_frame(&path, (3.0 * fps) as u32),
705 "undo did not restore the mapping"
706 );
707}
708
709/// A cut small enough to land *ahead* of the decoder rather than behind it:
710/// less than half a second of file removed, which is the shape a silence cut
711/// leaves at every boundary it makes. The picture worker reaches the next
712/// span by decoding forward and dropping (the plugin's forward skip, no
713/// flush) -- and what must survive that is the exactness of the landing: the
714/// first frame past the boundary is the source frame the cut ended on, pixel
715/// for pixel, exactly as the long cut above is asserted.
716#[test]
717fn a_small_cut_lands_frame_exact_across_the_boundary() {
718 let path = asset("test_baseline.mp4");
719 let mut session = open(&path);
720 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
721 // 0.2 s out of the middle: 6 frames at 30 fps, well inside the half a
722 // second a reposition may walk forward.
723 let (cut, hole_end) = ((1.0 * fps) as u32, (1.2 * fps) as u32);
724 assert!(session.cut_at(1.0), "cut at 1 s");
725 assert!(session.cut_at(1.2), "cut at 1.2 s");
726 assert!(session.delete_clip(Lane::V1, 1), "drop the hole");
727 let kept = total - (hole_end - cut);
728
729 // Play the whole edited timeline from the top, one frame at a time.
730 session.seek(0.0);
731 session.play();
732 let deadline = Instant::now() + Duration::from_secs(20);
733 let (mut expect, mut boundary) = (0, None);
734 loop {
735 session.tick();
736 while let Some(frame) = session.try_frame() {
737 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
738 if frame.index == cut {
739 boundary = Some(frame.bgra);
740 }
741 expect += 1;
742 }
743 if session.is_eos() {
744 break;
745 }
746 assert!(Instant::now() < deadline, "still draining after 20 s");
747 sleep(Duration::from_millis(4));
748 }
749 assert_eq!(expect, kept, "the edited timeline, whole and nothing but");
750 session.pause();
751
752 let boundary = boundary.expect("no frame at the cut");
753 assert!(
754 boundary == source_frame(&path, hole_end),
755 "the boundary frame is not source {hole_end}"
756 );
757 assert!(
758 boundary != source_frame(&path, cut),
759 "the deleted range is still being decoded"
760 );
761}
762
763/// The prime a picture restart spends, as the session reports it: owed from
764/// the moment a span is started until that span's first frame arrives. A
765/// front-end gates its late-picture restart on this, so what it reads has to
766/// be exactly this and nothing looser.
767#[test]
768fn picture_priming_spans_a_restart_and_ends_at_its_first_frame() {
769 let path = asset("test_baseline.mp4");
770 let mut session = open(&path);
771 // The open itself is a span that has not delivered yet.
772 assert!(session.picture_priming(), "a fresh session is priming");
773 let first = next_frame(&mut session, "the open");
774 assert!(!session.picture_priming(), "the first frame ends the prime");
775 assert_eq!(first.index, 0);
776
777 // A seek restarts the picture at its target: a new span, a new prime --
778 // the same start every clip boundary and edit takes.
779 session.seek(2.0);
780 assert!(session.picture_priming(), "the reseek is priming again");
781 let landed = next_frame(&mut session, "the reseek");
782 assert!(!session.picture_priming());
783 assert_eq!(landed.index, (2.0 * session.meta().frame_rate) as u32);
784}
785
786/// Copy and paste. A clipboard clip is a pair of *source* frame numbers, so the
787/// pasted stretch has to decode its own range -- not the frames the timeline
788/// used to hold at that position.
789#[test]
790fn paste_duplicates_a_clip_at_the_playhead() {
791 let path = asset("test_baseline.mp4");
792 let mut session = open(&path);
793 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
794 let whole = f64::from(total) / fps;
795
796 assert!(session.cut_at(2.0), "cut at 2 s");
797 let copied = session.clip_at(0).expect("clip 0");
798 let copied_len = copied.len();
799 assert_eq!(copied_len, (2.0 * fps) as u32);
800 assert!(session.clip_at(2).is_none(), "only two clips so far");
801
802 // Mid-clip: the paste splits clip 1 and lands between the halves.
803 let at = (4.0 * fps) as u32;
804 assert!(session.paste_at(4.0, copied), "paste at 4 s");
805 assert_eq!(session.clip_spans().len(), 4);
806 let grown = total + copied_len;
807 assert!(
808 (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
809 "duration after the paste: {}",
810 session.timeline_duration()
811 );
812
813 // Play the edited timeline from the top, keeping the two seam frames.
814 session.seek(0.0);
815 session.play();
816 let deadline = Instant::now() + Duration::from_secs(30);
817 let (mut expect, mut pasted, mut resumed) = (0, None, None);
818 loop {
819 session.tick();
820 while let Some(frame) = session.try_frame() {
821 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
822 if frame.index == at {
823 pasted = Some(frame.bgra);
824 } else if frame.index == at + copied_len {
825 resumed = Some(frame.bgra);
826 }
827 expect += 1;
828 }
829 if session.is_eos() {
830 break;
831 }
832 assert!(Instant::now() < deadline, "still draining after 30 s");
833 sleep(Duration::from_millis(4));
834 }
835 assert_eq!(expect, grown, "the pasted timeline, whole and nothing but");
836 // As above: an edit reseeks to *now*, so stop the clock before asserting.
837 session.pause();
838
839 // At the paste position the picture is the copied clip's first frame, and
840 // the split-off remainder resumes exactly where it was interrupted.
841 assert!(
842 pasted.expect("no frame at the paste") == source_frame(&path, copied.in_frame),
843 "the paste is not showing source {}",
844 copied.in_frame
845 );
846 assert!(
847 resumed.expect("no frame after the paste") == source_frame(&path, at),
848 "the timeline did not resume at source {at}"
849 );
850
851 assert!(session.undo(), "undo the paste");
852 assert_eq!(session.clip_spans().len(), 2, "one step, back to the cut");
853 assert!(
854 (session.timeline_duration() - whole).abs() < 1e-9,
855 "undo did not restore the duration: {}",
856 session.timeline_duration()
857 );
858}
859
860/// Pasting at the playhead while it is running: like a delete this moves every
861/// following frame, so the session reseeks under itself -- what must not happen
862/// is a stall, and the grown timeline still plays out whole. No audio needed.
863#[test]
864fn paste_while_playing_does_not_stall() {
865 let path = asset("test_baseline.mp4");
866 let mut session = open(&path);
867 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
868 let mut last_index = None;
869
870 assert!(session.cut_at(2.0), "cut at 2 s");
871 let copied = session.clip_at(0).expect("clip 0");
872 session.play();
873 run_for(&mut session, &mut last_index, Duration::from_millis(300));
874 assert!(last_index.is_some(), "no frames before the paste");
875
876 // Into the clip under the running playhead: the paste splits it in two and
877 // lands between the halves.
878 assert!(
879 session.paste_at(session.now(), copied),
880 "paste at the playhead"
881 );
882 assert!(session.is_playing(), "the paste stopped the clock");
883 assert_eq!(session.clip_spans().len(), 4);
884 let grown = total + copied.len();
885 assert!(
886 (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
887 "duration after the paste: {}",
888 session.timeline_duration()
889 );
890
891 // As after a mid-play import: the reseek makes the indices step backwards
892 // once, so this drains without `pump`'s index-order check.
893 let (count, last) = drain_to_eof(&mut session);
894 eprintln!("paste while playing: {count} more frames, last {last:?}");
895 assert_eq!(last, Some(grown - 1), "the grown timeline did not play out");
896}
897
898/// Pasting past the end of a played-out timeline appends, and the reseek every
899/// edit does clears `eos` -- so the session plays on into the pasted clip
900/// instead of staying dead.
901#[test]
902fn paste_at_eos_revives_the_session() {
903 let path = asset("test_baseline.mp4");
904 let mut session = open(&path);
905 let total = session.meta().frame_count;
906
907 assert!(session.cut_at(2.0), "cut at 2 s");
908 let copied = session.clip_at(0).expect("clip 0");
909 session.play();
910 assert_eq!(drain_to_eof(&mut session).1, Some(total - 1));
911 assert!(session.is_eos());
912
913 assert!(
914 session.paste_at(999.0, copied),
915 "paste past the end appends"
916 );
917 assert!(!session.is_eos(), "the paste did not revive the session");
918 assert_eq!(
919 session.clip_spans().len(),
920 3,
921 "two clips plus the pasted one"
922 );
923 // No assertion on *where* it resumes: an edit reseeks to `now()`, and at EOS
924 // that is wherever the wall clock got to while draining -- a race. What is
925 // fixed is that frames come again and the whole grown timeline plays out.
926 next_frame(&mut session, "paste at EOS");
927 assert_eq!(
928 drain_to_eof(&mut session).1,
929 Some(total + copied.len() - 1),
930 "the pasted clip did not play out"
931 );
932}
933
934/// Editing while the device is running. A cut must not disturb playback at all
935/// and a delete reseeks under it -- in both cases the audio keeps coming, which
936/// is what stops `tick` from handing the timeline back to wall time.
937#[test]
938#[ignore = "needs a running PipeWire daemon"]
939fn edits_keep_the_audio_clock() {
940 let mut session = open(asset("test_av.mp4"));
941 let fps = session.meta().frame_rate;
942 let mut last_index = None;
943
944 session.play();
945 run_for(&mut session, &mut last_index, Duration::from_millis(700));
946 let before = session.now();
947 assert!(before > 0.3, "clock stalled at {before:.3}s");
948
949 // Metadata only: no worker is touched, so the indices stay contiguous
950 // across the boundary `run_for` is about to cross.
951 assert!(session.cut_at(1.5), "cut at 1.5 s");
952 run_for(&mut session, &mut last_index, Duration::from_millis(900));
953 let after_cut = session.now();
954 assert!(
955 after_cut > before + 0.6,
956 "the clock stopped across the cut: {before:.3}s -> {after_cut:.3}s"
957 );
958 assert!(
959 last_index.map(|i| f64::from(i) > 1.5 * fps) == Some(true),
960 "playback never reached the cut: {last_index:?}"
961 );
962
963 // Deleting the head clip moves everything after it, so the session reseeks
964 // under the playhead: same timeline position, new source frame, and the
965 // frame numbering restarts at the landing frame.
966 assert!(session.delete_clip(Lane::V1, 0), "drop the head clip");
967 let landed = session.now();
968 assert!(
969 (landed - after_cut).abs() < 0.2,
970 "the delete moved the playhead: {after_cut:.3}s -> {landed:.3}s"
971 );
972 let first = next_frame(&mut session, "the delete reseek").index;
973 assert!(
974 first.abs_diff((landed * fps) as u32) <= 1,
975 "the delete landed at {first} instead of the playhead ({landed:.3}s)"
976 );
977 // No EOS assertion here: `run_for` drains a frame per 8 ms call, far faster
978 // than real time (ledger), so how much timeline is left after it is a race.
979 let mut after_delete = Some(first);
980 run_for(&mut session, &mut after_delete, Duration::from_millis(500));
981 assert!(after_delete > Some(first), "no frames after the delete");
982 assert!(
983 session.now() > landed + 0.3,
984 "the clock stopped after the delete: {landed:.3}s -> {:.3}s",
985 session.now()
986 );
987 eprintln!(
988 "edits: {before:.3}s -> cut -> {after_cut:.3}s -> delete -> {:.3}s of a {:.3}s timeline",
989 session.now(),
990 session.timeline_duration()
991 );
992}
993
994/// The two acts a second file on the timeline now takes, in the order a user
995/// does them: taken into the library, then dragged onto the end of the
996/// timeline. An import registers a source and places nothing
997/// (`PlaybackSession::import`), so every test that wants a second source *on*
998/// the lanes does both.
999fn import_and_place(session: &mut PlaybackSession, path: &Path) {
1000 session.import(path).expect("the file joins this timeline");
1001 let end = session.timeline_duration();
1002 assert!(
1003 session
1004 .place_stream_at(end, path, 0, None)
1005 .expect("a file just imported is on this timeline"),
1006 "the drag onto the end of the timeline"
1007 );
1008}
1009
1010/// Frame count straight from the container, without decoding anything.
1011fn frame_count(path: &Path) -> u32 {
1012 engine::demux::Demuxer::open(path)
1013 .expect("demux")
1014 .0
1015 .frame_count
1016}
1017
1018/// An imported file dragged onto the end of the timeline, played through as
1019/// one stream. No audio needed for the pictures, so this runs anywhere.
1020#[test]
1021fn a_placed_import_plays_across_the_join() {
1022 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1023 let mut session = open(&av);
1024 let (fps, first) = (session.meta().frame_rate, session.meta().frame_count);
1025 let second = frame_count(&av2);
1026 assert_eq!((first, second), (150, 120), "fixtures changed");
1027
1028 // The import alone fills the library: nothing on the lanes moved.
1029 session.import(&av2).expect("test_av2 matches test_av");
1030 assert_eq!(session.clip_spans().len(), 1, "an import placed a clip");
1031 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1032 assert_eq!(session.file_frames(&av2), second, "its own length is noted");
1033 // ...and the drag puts it at the end.
1034 let end = session.timeline_duration();
1035 assert!(
1036 session
1037 .place_stream_at(end, &av2, 0, None)
1038 .expect("a file just imported is on this timeline")
1039 );
1040 assert_eq!(session.clip_spans().len(), 2);
1041 assert_eq!(
1042 session
1043 .clip_spans_by_source()
1044 .iter()
1045 .map(|&(.., s)| s)
1046 .collect::<Vec<_>>(),
1047 vec![0, 1],
1048 "the placed clip plays the imported file"
1049 );
1050 assert!(
1051 (session.timeline_duration() - 9.0).abs() < 1e-9,
1052 "5 s + 4 s: {}",
1053 session.timeline_duration()
1054 );
1055
1056 // Play the joined timeline whole, keeping the picture at the join.
1057 session.seek(0.0);
1058 session.play();
1059 let deadline = Instant::now() + Duration::from_secs(30);
1060 let (mut expect, mut boundary) = (0, None);
1061 loop {
1062 session.tick();
1063 while let Some(frame) = session.try_frame() {
1064 assert_eq!(
1065 frame.index, expect,
1066 "timeline indices must be contiguous across a source join"
1067 );
1068 if frame.index == first {
1069 boundary = Some(frame.bgra);
1070 }
1071 expect += 1;
1072 }
1073 if session.is_eos() {
1074 break;
1075 }
1076 assert!(Instant::now() < deadline, "still draining after 30 s");
1077 sleep(Duration::from_millis(4));
1078 }
1079 assert_eq!(expect, first + second, "270 frames, whole and nothing but");
1080 // As everywhere else: stop the clock before asserting on landing frames.
1081 session.pause();
1082 assert!(
1083 boundary.expect("no frame at the join") == source_frame(&av2, 0),
1084 "timeline frame {first} is not the imported file's frame 0"
1085 );
1086
1087 // Edits across the join keep every clip pointing at its own file: cut one
1088 // second into the imported clip, then drop the whole original.
1089 assert!(session.cut_at(6.0), "cut 1 s into the imported clip");
1090 assert_eq!(session.clip_spans().len(), 3);
1091 assert!(session.delete_clip(Lane::V1, 0), "drop the first source");
1092 assert_eq!(session.clip_spans_by_source()[0].2, 1);
1093 assert!(
1094 (session.timeline_duration() - f64::from(second) / fps).abs() < 1e-9,
1095 "only the imported file is left: {}",
1096 session.timeline_duration()
1097 );
1098 session.seek(0.0);
1099 let landed = next_frame(&mut session, "seek(0.0) after the delete");
1100 assert_eq!(landed.index, 0);
1101 assert!(
1102 landed.bgra == source_frame(&av2, 0),
1103 "the delete lost the source mapping"
1104 );
1105
1106 assert!(session.undo(), "undo the delete");
1107 assert_eq!(session.clip_spans().len(), 3);
1108 let restored = next_frame(&mut session, "undo");
1109 assert_eq!(restored.index, 0);
1110 assert!(
1111 restored.bgra == source_frame(&av, 0),
1112 "undo did not restore the first source"
1113 );
1114}
1115
1116/// The first import into a window with nothing open: the file fills the library
1117/// and the timeline stays *empty*, and the drag that follows is what puts it on
1118/// a lane -- at the file's own length, which nothing on the timeline could have
1119/// told the session. The whole point of an import that places nothing.
1120#[test]
1121fn the_first_import_opens_a_library_over_an_empty_timeline() {
1122 let av = asset("test_av.mp4");
1123 let mut session = PlaybackSession::open_library(&av).expect("open into the library");
1124 session.set_gain(0.0);
1125 assert!(session.is_empty(), "the timeline must start empty");
1126 assert_eq!(session.timeline_duration(), 0.0);
1127 assert!(session.clip_spans().is_empty());
1128 // But it is a session: the file's own picture, rate and clock, and its row.
1129 assert_eq!(session.sources().len(), 1, "the library row");
1130 assert_eq!(session.resolution(), (1280, 720));
1131 assert_eq!(session.meta().frame_rate, 30.0);
1132 assert_eq!(session.file_frames(&av), 150, "5 s at 30 fps, never placed");
1133 assert!(!session.undo(), "opening a library is not an undo step");
1134
1135 // The drag: the row goes onto the timeline whole, and it plays from there.
1136 assert!(
1137 session
1138 .place_stream_at(0.0, &av, 0, None)
1139 .expect("its own file is on this timeline")
1140 );
1141 assert!(!session.is_empty(), "the drag left the timeline empty");
1142 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1143 session.seek(0.0);
1144 let landed = next_frame(&mut session, "the dragged clip");
1145 assert_eq!(landed.index, 0);
1146 assert!(
1147 landed.bgra == source_frame(&av, 0),
1148 "the placed clip is not playing its file"
1149 );
1150 // ...and it is an edit like any other, so one `z` takes it back to empty.
1151 assert!(session.undo(), "undo the drag");
1152 assert!(session.is_empty());
1153 assert_eq!(session.sources().len(), 1, "the row survives the undo");
1154}
1155
1156/// One timeline, one frame rate and one set of audio parameters: what is left
1157/// is refused by name and changes nothing.
1158#[test]
1159fn import_refuses_what_does_not_match() {
1160 let mut session = open(asset("test_av.mp4"));
1161
1162 // A different *codec* is not among them any more -- every clip opens its
1163 // own decoder. The only refusal left on that axis is a decoder this machine
1164 // cannot open, and it is the plugin's own words, not the timeline's.
1165 match session.import(&asset("test_vp9.mp4")) {
1166 Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"),
1167 Err(e) => assert_eq!(
1168 e.to_string(),
1169 Codec::Vp9.needs_plugin(),
1170 "the only codec refusal left is the missing decoder"
1171 ),
1172 }
1173 let rows = session.sources().len();
1174
1175 // A different resolution is no longer among the refusals -- it is placed on
1176 // the project canvas instead -- and neither is a file with no sound: it
1177 // contributes silence over its span.
1178 session
1179 .import(&asset("test_mismatch.mp4"))
1180 .expect("a silent 640x360 file joins a timeline with sound");
1181
1182 // A frame rate of its own is no longer a refusal either: 25 fps joins a
1183 // 30 fps timeline and is read at `Rate` against it -- see
1184 // `tests/mixed_fps.rs` for what it then plays like.
1185 session
1186 .import(&asset("test_25fps.mp4"))
1187 .expect("25 fps may join a 30 fps timeline");
1188 session
1189 .remove_source(&asset("test_25fps.mp4"), 0)
1190 .expect("...and the row it made comes back off");
1191
1192 // A sample *rate* of its own is no longer a refusal either: one output
1193 // device means one rate, and the segment's own resampler is what makes two
1194 // into one now ([`engine::audio::Resample`]).
1195 session
1196 .import(&asset("test_tone_48k.wav"))
1197 .expect("48 kHz may join a 44.1 kHz timeline");
1198 session
1199 .remove_source(&asset("test_tone_48k.wav"), 0)
1200 .expect("...and the row it made comes back off");
1201
1202 // What is still refused, and all that is: one output device carries one
1203 // layout, and a mono track is not the stereo pair this timeline plays.
1204 let err = session
1205 .import(&asset("test_ac3.mp4"))
1206 .expect_err("a mono track cannot join a stereo timeline")
1207 .to_string();
1208 assert_eq!(err, "audio 1 ch does not match the timeline's 2 ch");
1209
1210 assert!(
1211 session.import(&asset("no_such_file.mp4")).is_err(),
1212 "a missing file is an error, not a panic"
1213 );
1214 assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
1215 assert_eq!(
1216 session.sources().len(),
1217 rows + 1,
1218 "only the silent file was taken in"
1219 );
1220 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1221
1222 // The mirror is still refused: the device was opened on source 0's track
1223 // and a silent timeline has none to open, so a file with sound cannot be
1224 // heard on one.
1225 let mut silent = open(asset("test_baseline.mp4"));
1226 let err = silent
1227 .import(&asset("test_av.mp4"))
1228 .expect_err("audio into a silent timeline")
1229 .to_string();
1230 assert!(err.contains("audio"), "refusal must name the audio: {err}");
1231}
1232
1233/// The user path a silent take goes down: a file with no audio track lands on a
1234/// timeline that has one, is placed as the grouped take every video file is,
1235/// and plays -- pictures over its span, silence under them. The sound itself is
1236/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is
1237/// that nothing about the *timeline* is refused or lost.
1238#[test]
1239fn a_silent_file_joins_a_timeline_with_sound_and_plays() {
1240 let mut session = open(asset("test_av.mp4"));
1241 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1242 // 150 frames of test_av, then 60 of the silent file, at 30 fps.
1243 assert_eq!(session.clip_spans().len(), 2, "the silent take landed");
1244 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1245 // Both lanes carry it: a silent file is a normal grouped take, and its
1246 // audio clip is the span the worker fills with silence.
1247 assert_eq!(session.lane_clips(Lane::V1).len(), 2);
1248 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
1249
1250 // ...and it decodes: a picture from inside the silent clip's span, at the
1251 // project's resolution like every other clip.
1252 session.seek(6.0);
1253 let frame = next_frame(&mut session, "the silent clip");
1254 assert_eq!((frame.width, frame.height), session.resolution());
1255}
1256
1257/// The user-facing point of a project resolution: media of two sizes on one
1258/// timeline, each composed onto the project's own canvas.
1259///
1260/// 640x360 joins a 1280x720 timeline (it would have been refused before this
1261/// slice), and both clips come out of `try_frame` at the project's size --
1262/// which is what makes the export, the window and the renderer one shape.
1263#[test]
1264fn media_of_two_resolutions_share_one_timeline() {
1265 let mut session = open(asset("test_baseline.mp4"));
1266 assert_eq!(session.resolution(), (1280, 720), "source 0's picture");
1267 assert_eq!(session.native_resolution(), (1280, 720));
1268 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1269 // 150 frames of the first file, then 60 of the second, at 30 fps.
1270 assert_eq!(session.clip_spans().len(), 2);
1271 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1272
1273 for (at, what) in [(1.0, "the 1280x720 clip"), (6.0, "the 640x360 clip")] {
1274 session.seek(at);
1275 let frame = next_frame(&mut session, what);
1276 assert_eq!(
1277 (frame.width, frame.height),
1278 (1280, 720),
1279 "{what} did not come out at the project resolution"
1280 );
1281 assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
1282 }
1283}
1284
1285/// The geometry, asserted on the pixels: on a canvas whose aspect the media does
1286/// not share, a `Fit` clip is letterboxed -- bars exactly black, picture where
1287/// `scale::fit_rect` puts it -- and `Fill` crops the bars away.
1288#[test]
1289fn a_fitted_clip_is_letterboxed_and_a_filled_one_is_not() {
1290 let mut session = open(asset("test_baseline.mp4"));
1291 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1292 // A 4:3 project: both clips are 16:9, so both are letterboxed on it. 960x720
1293 // holds the whole 640x360 picture as 960x540 with 90 rows of bar either way
1294 // (fit_rect's own arithmetic, asserted in scale.rs).
1295 assert!(session.set_resolution(960, 720), "4:3 project");
1296 session.seek(6.0);
1297 let frame = next_frame(&mut session, "the 640x360 clip on a 4:3 canvas");
1298 assert_eq!((frame.width, frame.height), (960, 720));
1299 let row = |frame: &Frame, y: usize| {
1300 frame.bgra[y * 960 * 4..][..960 * 4]
1301 .chunks_exact(4)
1302 .map(|px| (px[0], px[1], px[2]))
1303 .collect::<Vec<_>>()
1304 };
1305 let black = |row: &[(u8, u8, u8)]| row.iter().all(|&px| px == (0, 0, 0));
1306 assert!(black(&row(&frame, 0)), "top bar is not black");
1307 assert!(black(&row(&frame, 89)), "the bar stops one row early");
1308 assert!(black(&row(&frame, 719)), "bottom bar is not black");
1309 assert!(
1310 !black(&row(&frame, 360)),
1311 "the picture area is black: nothing was composed"
1312 );
1313 // Same clip, filled: the canvas is covered, so no row is a bar.
1314 let (lane, idx) = session.video_clip_at(6.0).expect("a clip at 6 s");
1315 assert!(session.set_fit(lane, idx, engine::scale::FitPolicy::Fill));
1316 session.seek(6.0);
1317 let filled = next_frame(&mut session, "the same clip filled");
1318 assert_eq!((filled.width, filled.height), (960, 720));
1319 assert!(!black(&row(&filled, 0)), "Fill left a top bar");
1320 assert!(!black(&row(&filled, 719)), "Fill left a bottom bar");
1321 assert_ne!(
1322 row(&frame, 360),
1323 row(&filled, 360),
1324 "Fill showed the same pixels as Fit: the crop did nothing"
1325 );
1326}
1327
1328/// The clip that pays nothing: a project at its media's own size must hand the
1329/// decoder's bytes through untouched, not merely equal ones. Same frame, same
1330/// bytes, whether or not the composition path exists.
1331#[test]
1332fn a_project_at_the_media_size_is_the_decoder_untouched() {
1333 let mut session = open(asset("test_baseline.mp4"));
1334 session.seek(1.0);
1335 let frame = next_frame(&mut session, "seek to 1 s");
1336 assert_eq!((frame.width, frame.height), (1280, 720));
1337 assert_eq!(
1338 frame.bgra,
1339 source_frame(&asset("test_baseline.mp4"), frame.index),
1340 "the pass-through path changed a byte"
1341 );
1342}
1343
1344/// The same file twice is one library row -- a source index is handed out once
1345/// and reused, which is what keeps clipboard clips valid forever -- and two
1346/// drags of that one row are two clips of it.
1347#[test]
1348fn importing_one_file_twice_reuses_its_source() {
1349 let mut session = open(asset("test_av.mp4"));
1350 let av2 = asset("test_av2.mp4");
1351 assert_eq!(session.import(&av2).expect("first import"), 1);
1352 assert_eq!(
1353 session.import(&av2).expect("second import"),
1354 1,
1355 "the second import is the same row"
1356 );
1357 assert_eq!(session.sources().len(), 2, "one row for one file");
1358 import_and_place(&mut session, &av2);
1359 import_and_place(&mut session, &av2);
1360 assert_eq!(session.sources().len(), 2, "and still one row");
1361 assert_eq!(
1362 session
1363 .clip_spans_by_source()
1364 .iter()
1365 .map(|&(.., s)| s)
1366 .collect::<Vec<_>>(),
1367 vec![0, 1, 1],
1368 "one new source, two clips of it"
1369 );
1370 assert!(
1371 (session.timeline_duration() - 13.0).abs() < 1e-9,
1372 "5 s + 4 s + 4 s: {}",
1373 session.timeline_duration()
1374 );
1375}
1376
1377/// A library row placed after the timeline has been played out revives the
1378/// session: the placement reseeks like every other edit, and that is what
1379/// clears `eos`. The import itself changes nothing, played out or not.
1380///
1381/// Where it resumes is not asserted, for the reason `paste_at_eos_revives_the_
1382/// session` does not assert it either: an edit reseeks to `now()`, and at EOS
1383/// the free-running clock has gone past the end.
1384#[test]
1385fn a_placement_at_eos_revives_the_session() {
1386 let av2 = asset("test_av2.mp4");
1387 let mut session = open(asset("test_av.mp4"));
1388 let first = session.meta().frame_count;
1389
1390 session.play();
1391 assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
1392 assert!(session.is_eos());
1393
1394 session.import(&av2).expect("import at EOS");
1395 assert!(
1396 session.is_eos(),
1397 "an import is not an edit: it cannot revive"
1398 );
1399 assert!(
1400 session
1401 .place_stream_at(session.timeline_duration(), &av2, 0, None)
1402 .expect("a file just imported is on this timeline")
1403 );
1404 assert!(
1405 !session.is_eos(),
1406 "the placement did not revive the session"
1407 );
1408 assert_eq!(
1409 session.timeline_duration(),
1410 f64::from(first + frame_count(&av2)) / session.meta().frame_rate
1411 );
1412 assert_eq!(session.clip_spans().len(), 2);
1413}
1414
1415/// A source deleted mid-session: the clip that names it contributes no pictures
1416/// and the timeline still ends, instead of stalling on the missing file.
1417#[test]
1418fn a_vanished_source_is_skipped() {
1419 let scratch = Scratch::file("video_editor_vanish", "mp4");
1420 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
1421 let mut session = open(asset("test_av.mp4"));
1422 let first = session.meta().frame_count;
1423 import_and_place(&mut session, &scratch);
1424 std::fs::remove_file(&scratch).expect("unlink");
1425
1426 session.seek(0.0);
1427 session.play();
1428 let (count, last) = drain_to_eof(&mut session);
1429 assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
1430 assert_eq!(count, first, "the first source still played whole");
1431 assert!(session.is_eos(), "the timeline still ends");
1432}
1433
1434/// Importing and placing while the device is running: the placement reseeks
1435/// under the playhead, so what must not happen is a stall -- the joined
1436/// timeline still plays out whole. No audio needed, so this runs anywhere.
1437#[test]
1438fn import_during_play_does_not_stall() {
1439 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1440 let mut session = open(&av);
1441 let first = session.meta().frame_count;
1442 let mut last_index = None;
1443
1444 session.play();
1445 run_for(&mut session, &mut last_index, Duration::from_millis(300));
1446 assert!(last_index.is_some(), "no frames before the import");
1447
1448 import_and_place(&mut session, &av2);
1449 assert_eq!(session.clip_spans().len(), 2);
1450 assert!(session.is_playing(), "the placement stopped the clock");
1451
1452 // From here on the indices go *backwards* once: `run_for` decodes far ahead
1453 // of the clock (ledger), and the import reseeks to `now()` -- which is why
1454 // this drains with `drain_to_eof` instead of the order-checking `pump`.
1455 let (count, last) = drain_to_eof(&mut session);
1456 eprintln!("import while playing: {count} more frames, last {last:?}");
1457 assert_eq!(
1458 last,
1459 Some(first + frame_count(&av2) - 1),
1460 "the joined timeline did not play out"
1461 );
1462}
1463
1464/// An import is *not* an undo step -- a library row changes nothing playable,
1465/// so there is nothing for `z` to take back -- and the placement that follows
1466/// is one. Undoing it leaves the row in the library, where the user put it.
1467#[test]
1468fn an_import_is_not_an_undo_step_but_its_placement_is() {
1469 let av2 = asset("test_av2.mp4");
1470 let mut session = open(asset("test_av.mp4"));
1471 session.import(&av2).expect("import");
1472 assert!(!session.undo(), "an import must not be undoable");
1473 assert_eq!(session.sources().len(), 2, "and it is still in the library");
1474
1475 import_and_place(&mut session, &av2);
1476 assert_eq!(session.clip_spans().len(), 2);
1477 assert!((session.timeline_duration() - 9.0).abs() < 1e-9);
1478
1479 assert!(session.undo(), "undo the placement");
1480 assert_eq!(session.clip_spans().len(), 1, "one step, back to one clip");
1481 assert!(
1482 (session.timeline_duration() - 5.0).abs() < 1e-9,
1483 "undo did not restore the duration: {}",
1484 session.timeline_duration()
1485 );
1486 assert_eq!(
1487 session.sources().len(),
1488 2,
1489 "the library row survives an undo of the clip that used it"
1490 );
1491
1492 // Still playable: the undo reseeked to the (paused) playhead at zero.
1493 session.play();
1494 assert_eq!(next_index(&mut session, "undo of a placement"), 0);
1495}
1496
1497/// The audio path across a source join: one worker spans both files, so the
1498/// clock must keep running at real speed through the boundary. (Whether it is
1499/// still the *audio* clock is not observable from outside -- a device that ran
1500/// dry would fall back to wall time at the same speed -- so this catches a
1501/// stall, not a silent fallback.)
1502#[test]
1503#[ignore = "needs a running PipeWire daemon"]
1504fn audio_runs_across_a_source_join() {
1505 let mut session = open(asset("test_av.mp4"));
1506 import_and_place(&mut session, &asset("test_av2.mp4"));
1507 let first = session.meta().frame_count;
1508
1509 session.seek(4.5); // half a second before the join
1510 session.play();
1511 let mut last_index = None;
1512 run_for(&mut session, &mut last_index, Duration::from_millis(1500));
1513 let now = session.now();
1514 eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
1515 assert!(
1516 (5.4..6.6).contains(&now),
1517 "the clock did not run at real speed across the join: {now:.3}s"
1518 );
1519 assert!(
1520 last_index.map(|i| i > first) == Some(true),
1521 "playback never crossed the join: {last_index:?}"
1522 );
1523 // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
1524 // real time, so the decoder may well have reached 9 s while the clock is at
1525 // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
1526}
1527
1528/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap*
1529/// rather than closing up, and a gap plays: the timeline keeps its length, the
1530/// frame numbering stays contiguous straight through, and every picture over
1531/// the hole is black. No audio needed, so this runs anywhere.
1532#[test]
1533fn a_video_gap_plays_black_without_shortening_the_timeline() {
1534 let path = asset("test_baseline.mp4");
1535 let mut session = open(&path);
1536 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
1537 let whole = session.timeline_duration();
1538
1539 assert!(session.cut_at(2.0), "split at 2 s");
1540 assert!(session.cut_at(3.5), "split at 3.5 s");
1541 assert!(
1542 session.lift_clip(Lane::V1, 1),
1543 "lift the middle picture out"
1544 );
1545 assert_eq!(
1546 session.clip_spans().len(),
1547 2,
1548 "two placements, and a hole between them"
1549 );
1550 assert!(
1551 (session.timeline_duration() - whole).abs() < 1e-9,
1552 "a lift leaves a gap: the timeline is exactly as long as it was"
1553 );
1554
1555 let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
1556 session.seek(0.0);
1557 session.play();
1558 let deadline = Instant::now() + Duration::from_secs(20);
1559 let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32);
1560 loop {
1561 session.tick();
1562 while let Some(frame) = session.try_frame() {
1563 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
1564 let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]);
1565 if (hole..hole_end).contains(&frame.index) {
1566 assert!(is_black, "frame {} is inside the gap", frame.index);
1567 black += 1;
1568 } else {
1569 lit += 1;
1570 }
1571 expect += 1;
1572 }
1573 if session.is_eos() {
1574 break;
1575 }
1576 assert!(Instant::now() < deadline, "still draining after 20 s");
1577 sleep(Duration::from_millis(4));
1578 }
1579 assert_eq!(expect, total, "the whole timeline, gap included");
1580 assert_eq!(black, hole_end - hole, "every frame of the hole was black");
1581 assert!(lit > 0, "and the clips around it still decoded");
1582
1583 // The gap is one undo step back to the clip that was there.
1584 assert!(session.undo());
1585 assert_eq!(session.clip_spans().len(), 3);
1586}
1587
1588/// A hole in the *audio* lane, with the device running: the master clock counts
1589/// samples the device has been fed, so silence has to be fed as real chunks or
1590/// the timeline would stall on the hole. Needs a PipeWire daemon and the output
1591/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`).
1592///
1593/// Muted like every other device test: what it asserts is the clock and the
1594/// frame numbering, both of which count fed samples and not their loudness. The
1595/// silence of a gap is proved off the decoder instead, with no device involved,
1596/// in `audio_segments::a_gap_segment_is_silence_of_its_own_length`.
1597#[test]
1598#[ignore = "needs a running PipeWire daemon"]
1599fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
1600 let mut session = open(asset("test_av.mp4"));
1601 assert!(session.cut_at(1.0), "split at 1 s");
1602 assert!(session.cut_at(2.0), "split at 2 s");
1603 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1604 assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
1605 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1606 let duration = session.timeline_duration();
1607
1608 session.seek(0.0);
1609 let mut last_index = None;
1610 session.play();
1611 // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at
1612 // 1 s, so a stall anywhere inside it cannot hide.
1613 run_for(&mut session, &mut last_index, Duration::from_millis(2_400));
1614 let now = session.now();
1615 assert!(
1616 now > 2.2 && now < duration,
1617 "the clock stalled on the audio gap at {now:.3}s"
1618 );
1619 assert!(
1620 last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true),
1621 "pictures stopped over the silence: {last_index:?}"
1622 );
1623 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
1624}
1625
1626/// The emptied timeline, end to end: the last clip deletes like any other, what
1627/// is left plays as black and silence with a duration of zero, it saves and
1628/// loads back as the project it is, and one undo brings the clip back. Silent
1629/// fixture, so this runs anywhere.
1630#[test]
1631fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1632 let path = asset("test_baseline.mp4");
1633 let mut session = open(&path);
1634 let whole = session.timeline_duration();
1635 assert!(whole > 0.0);
1636
1637 // The sole take goes -- picture and sound of it, on every lane at once.
1638 assert!(
1639 session.delete_clip(Lane::V1, 0),
1640 "the last clip deletes like any other"
1641 );
1642 assert!(session.is_empty(), "and the timeline is empty");
1643 assert_eq!(session.timeline_duration(), 0.0);
1644 assert!(session.clip_spans().is_empty());
1645 assert_eq!(session.lanes().len(), 2, "the lanes are still there");
1646
1647 // It scrubs: every seek lands at zero and shows black rather than the
1648 // picture of the clip that was deleted.
1649 for t in [0.0, -1.0, whole, 1e9] {
1650 session.seek(t);
1651 assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline");
1652 let deadline = Instant::now() + Duration::from_secs(5);
1653 let mut black = None;
1654 while black.is_none() && Instant::now() < deadline {
1655 session.tick();
1656 black = session.try_frame();
1657 sleep(Duration::from_millis(4));
1658 }
1659 let frame = black.expect("an empty timeline shows one black frame");
1660 assert_eq!(frame.index, 0);
1661 assert!(
1662 frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
1663 "and it is black"
1664 );
1665 }
1666 // It plays: nothing to show, so it is at its end at once, and nothing hangs.
1667 session.play();
1668 let mut last_index = None;
1669 run_for(&mut session, &mut last_index, Duration::from_millis(200));
1670 assert!(session.is_eos(), "an empty timeline is played out at once");
1671 session.pause();
1672
1673 // Exporting nothing is a refusal in words, not a file of no frames -- and
1674 // in the *same* words whichever format asked, because the fence sits in
1675 // `export::start` ahead of the format, not in the mp4 path alone.
1676 for format in [Format::Mp4, Format::Wav, Format::Flac] {
1677 let dir = Scratch::dir("ve_nothing");
1678 let out = dir.join("ve_nothing");
1679 let handle = session.export_to_with(
1680 &out,
1681 &ExportSettings {
1682 format,
1683 ..ExportSettings::default()
1684 },
1685 );
1686 let deadline = Instant::now() + Duration::from_secs(10);
1687 let err = loop {
1688 if let Some(result) = handle.result() {
1689 break result.expect_err("an empty timeline cannot be exported");
1690 }
1691 assert!(Instant::now() < deadline, "{format:?} export never settled");
1692 sleep(Duration::from_millis(10));
1693 };
1694 assert_eq!(
1695 err.to_string(),
1696 "the timeline is empty: there is nothing to export",
1697 "{format:?}"
1698 );
1699 assert!(!out.exists(), "{format:?} wrote a file anyway");
1700 }
1701
1702 // It saves and loads back -- still a project, still two lanes, and still
1703 // naming the file whose frame rate the timeline counts in.
1704 let dir = Scratch::dir("ve_empty");
1705 let project = dir.join("empty.edith");
1706 session
1707 .save_project(&project)
1708 .expect("save an empty timeline");
1709 let loaded = PlaybackSession::open_project(&project).expect("load it back");
1710 assert!(loaded.is_empty(), "what came back is the empty timeline");
1711 assert_eq!(loaded.lanes().len(), 2);
1712 assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not");
1713 assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate);
1714 drop(loaded);
1715 let _ = std::fs::remove_dir_all(&dir);
1716
1717 // ...and one gesture is one undo: the take comes back whole.
1718 assert!(session.undo(), "the delete undoes");
1719 assert!(!session.is_empty());
1720 assert!((session.timeline_duration() - whole).abs() < 1e-9);
1721 assert_eq!(session.clip_spans().len(), 1);
1722}
1723
1724/// The session half of the late-frame policy: a *watched* session still lands
1725/// exactly on the frame a seek asked for. The floor the worker drops against is
1726/// the playhead mapped back into the file own frames, and a floor even one
1727/// frame ahead of the landing would eat the very picture the seek exists to
1728/// show ([`PlaybackSession::drop_late_pictures`]).
1729#[test]
1730fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() {
1731 let mut session = open(asset("test_baseline.mp4"));
1732 session.drop_late_pictures(true);
1733 let fps = session.meta().frame_rate;
1734 session.seek(3.0);
1735 assert_eq!(
1736 next_index(&mut session, "seek(3.0) on a watched session"),
1737 (3.0 * fps) as u32,
1738 "the landing frame was dropped as late"
1739 );
1740 // ...and again backwards: a floor left where the last span ended would drop
1741 // every picture of a seek that went back.
1742 session.seek(1.0);
1743 assert_eq!(
1744 next_index(&mut session, "seek(1.0) on a watched session"),
1745 (1.0 * fps) as u32
1746 );
1747}
1748
1749/// The pixels a *reused* decoder hands back are the pixels a fresh one does.
1750/// One session takes three seeks -- forwards, backwards, forwards again -- and
1751/// the worker survives all of them (`Worker::reseek`: the file stays open, the
1752/// hardware session is repositioned rather than reopened), so a decoder left
1753/// holding one span references while another span is asked for would show here
1754/// as a smear and nowhere else. The reference is the file-level API, which
1755/// opens a decoder of its own per frame.
1756#[test]
1757fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() {
1758 let path = asset("test_baseline.mp4");
1759 let mut session = open(&path);
1760 let fps = session.meta().frame_rate;
1761 // Small targets on purpose: the fixture's only sync sample is frame 0, so
1762 // every one of these decodes from the start of the file and a debug-build
1763 // software decoder is what runs the suite.
1764 for target in [20u32, 5, 35] {
1765 session.seek(f64::from(target) / fps);
1766 let frame = next_frame(&mut session, "a seek onto a worker already open");
1767 assert_eq!(frame.index, target, "the seek landed elsewhere");
1768 assert!(
1769 frame.bgra == source_frame(&path, target),
1770 "frame {target} off the reused decoder is not the picture a fresh one decodes"
1771 );
1772 }
1773}
1774
1775/// What the drop policy must never do: thin a picture the decoder was keeping up
1776/// with. `pump`'s own contiguity assert covers every *pull* consumer above;
1777/// nothing there bounds what a **watched** session delivers, and a one-in-N
1778/// regression inside the worker would pass the whole suite otherwise.
1779///
1780/// The fixture is the smallest one here (320x180) so the question can be asked
1781/// on a debug build at the file's own rate -- no retime, because a retimed
1782/// timeline legitimately shows only every n-th source frame and the sharp half
1783/// of this test is that the indices arrive one at a time. A box too slow even
1784/// for this says so and stops: thinning the picture there is the policy working
1785/// (`LATE_RUN`), not a regression.
1786#[test]
1787fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() {
1788 let path = asset("test_speed_sync.mp4");
1789
1790 // What this box decodes, flat out, with nothing dropped: frames per second.
1791 let mut measure = open(&path);
1792 let fps = measure.meta().frame_rate;
1793 measure.play();
1794 let mut decoded = 0u32;
1795 let taken = Instant::now();
1796 while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() {
1797 measure.tick();
1798 while measure.try_frame().is_some() {
1799 decoded += 1;
1800 }
1801 sleep(Duration::from_millis(2));
1802 }
1803 let capable = f64::from(decoded) / taken.elapsed().as_secs_f64();
1804 drop(measure);
1805 eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}");
1806 if capable < fps * 1.2 {
1807 eprintln!("SKIP: too slow to ask the question at all");
1808 return;
1809 }
1810
1811 // Watched, playing at its own rate, drained like a front-end that keeps up:
1812 // every picture is due when it arrives and none of them may be dropped.
1813 let mut session = open(&path);
1814 session.drop_late_pictures(true);
1815 session.play();
1816 let mut delivered = 0u32;
1817 let mut last: Option<u32> = None;
1818 let watched = Instant::now();
1819 while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() {
1820 session.tick();
1821 while let Some(frame) = session.try_frame() {
1822 delivered += 1;
1823 if let Some(previous) = last {
1824 assert_eq!(
1825 frame.index,
1826 previous + 1,
1827 "a picture was dropped while the decoder was keeping up"
1828 );
1829 }
1830 last = Some(frame.index);
1831 }
1832 sleep(Duration::from_millis(2));
1833 }
1834 // Frames the clock went over, which is what the timeline owed the screen.
1835 let passed = session.now() * fps;
1836 let density = f64::from(delivered) / passed.max(1.0);
1837 eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock");
1838 assert!(
1839 density >= 0.9,
1840 "the worker thinned a picture it was keeping up with: {delivered} of \
1841 {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps"
1842 );
1843}
1844
1845/// The decode-ahead a **freshly opened** file gets. Every session opens its first
1846/// worker pass-through -- a file just opened *is* the project resolution -- and
1847/// asking a pass-through canvas how deep to queue answers 2, the bound this
1848/// engine had before there was any decode-ahead: the whole file would then play
1849/// at that depth until the first seek built a real canvas. The depth is taken
1850/// from the stream instead (`scale::queue_depth`), and this is where that is
1851/// visible from outside: a paused session left alone fills its queue, and the
1852/// burst that comes off it is the depth plus the picture in the worker's hand.
1853///
1854/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so
1855/// the burst is 17 and the regression it guards against is a burst of 3.
1856#[test]
1857fn a_freshly_opened_file_queues_more_than_two_pictures() {
1858 let mut session = open(asset("test_baseline.mp4"));
1859 // Paused throughout: no seek, no play, nothing that would build a canvas.
1860 // The best of three attempts, because filling the queue is the decoder's own
1861 // work and this box shares itself with whatever else is running.
1862 let mut burst = 0;
1863 for _ in 0..3 {
1864 sleep(Duration::from_millis(1500));
1865 let mut n = 0;
1866 while session.try_frame().is_some() {
1867 n += 1;
1868 }
1869 burst = burst.max(n);
1870 }
1871 eprintln!("burst off a freshly opened file: {burst} pictures");
1872 assert!(
1873 burst > 8,
1874 "a freshly opened file queued {burst} pictures: the first worker is \
1875 still sizing its queue from a pass-through canvas"
1876 );
1877
1878 // ...and the same worker still answers. Four and a half seconds parked is
1879 // well past the idle mark at which it closes its hardware session
1880 // (`decode`'s `IDLE`), so this is the seek that has to reopen one lazily --
1881 // the one path that would have gone quiet if closing it left the worker
1882 // holding a decoder it could no longer use.
1883 let fps = session.meta().frame_rate;
1884 session.seek(2.0);
1885 assert_eq!(
1886 next_index(&mut session, "a seek after the worker went idle"),
1887 (2.0 * fps) as u32,
1888 "the worker did not come back from its idle park"
1889 );
1890}