forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

playback.rs1889 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 // A mono track is no longer a refusal either (DEBT #46): [`engine::audio`]
1203 // duplicates its one channel into both of this stereo timeline's, the same
1204 // way a wider file is already folded down to it.
1205 session
1206 .import(&asset("test_ac3.mp4"))
1207 .expect("a mono track up-mixes onto a stereo timeline");
1208
1209 assert!(
1210 session.import(&asset("no_such_file.mp4")).is_err(),
1211 "a missing file is an error, not a panic"
1212 );
1213 assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
1214 assert_eq!(
1215 session.sources().len(),
1216 rows + 2,
1217 "the silent file and the mono file were both taken in"
1218 );
1219 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1220
1221 // The mirror is still refused: the device was opened on source 0's track
1222 // and a silent timeline has none to open, so a file with sound cannot be
1223 // heard on one.
1224 let mut silent = open(asset("test_baseline.mp4"));
1225 let err = silent
1226 .import(&asset("test_av.mp4"))
1227 .expect_err("audio into a silent timeline")
1228 .to_string();
1229 assert!(err.contains("audio"), "refusal must name the audio: {err}");
1230}
1231
1232/// The user path a silent take goes down: a file with no audio track lands on a
1233/// timeline that has one, is placed as the grouped take every video file is,
1234/// and plays -- pictures over its span, silence under them. The sound itself is
1235/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is
1236/// that nothing about the *timeline* is refused or lost.
1237#[test]
1238fn a_silent_file_joins_a_timeline_with_sound_and_plays() {
1239 let mut session = open(asset("test_av.mp4"));
1240 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1241 // 150 frames of test_av, then 60 of the silent file, at 30 fps.
1242 assert_eq!(session.clip_spans().len(), 2, "the silent take landed");
1243 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1244 // Both lanes carry it: a silent file is a normal grouped take, and its
1245 // audio clip is the span the worker fills with silence.
1246 assert_eq!(session.lane_clips(Lane::V1).len(), 2);
1247 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
1248
1249 // ...and it decodes: a picture from inside the silent clip's span, at the
1250 // project's resolution like every other clip.
1251 session.seek(6.0);
1252 let frame = next_frame(&mut session, "the silent clip");
1253 assert_eq!((frame.width, frame.height), session.resolution());
1254}
1255
1256/// The user-facing point of a project resolution: media of two sizes on one
1257/// timeline, each composed onto the project's own canvas.
1258///
1259/// 640x360 joins a 1280x720 timeline (it would have been refused before this
1260/// slice), and both clips come out of `try_frame` at the project's size --
1261/// which is what makes the export, the window and the renderer one shape.
1262#[test]
1263fn media_of_two_resolutions_share_one_timeline() {
1264 let mut session = open(asset("test_baseline.mp4"));
1265 assert_eq!(session.resolution(), (1280, 720), "source 0's picture");
1266 assert_eq!(session.native_resolution(), (1280, 720));
1267 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1268 // 150 frames of the first file, then 60 of the second, at 30 fps.
1269 assert_eq!(session.clip_spans().len(), 2);
1270 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1271
1272 for (at, what) in [(1.0, "the 1280x720 clip"), (6.0, "the 640x360 clip")] {
1273 session.seek(at);
1274 let frame = next_frame(&mut session, what);
1275 assert_eq!(
1276 (frame.width, frame.height),
1277 (1280, 720),
1278 "{what} did not come out at the project resolution"
1279 );
1280 assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
1281 }
1282}
1283
1284/// The geometry, asserted on the pixels: on a canvas whose aspect the media does
1285/// not share, a `Fit` clip is letterboxed -- bars exactly black, picture where
1286/// `scale::fit_rect` puts it -- and `Fill` crops the bars away.
1287#[test]
1288fn a_fitted_clip_is_letterboxed_and_a_filled_one_is_not() {
1289 let mut session = open(asset("test_baseline.mp4"));
1290 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1291 // A 4:3 project: both clips are 16:9, so both are letterboxed on it. 960x720
1292 // holds the whole 640x360 picture as 960x540 with 90 rows of bar either way
1293 // (fit_rect's own arithmetic, asserted in scale.rs).
1294 assert!(session.set_resolution(960, 720), "4:3 project");
1295 session.seek(6.0);
1296 let frame = next_frame(&mut session, "the 640x360 clip on a 4:3 canvas");
1297 assert_eq!((frame.width, frame.height), (960, 720));
1298 let row = |frame: &Frame, y: usize| {
1299 frame.bgra[y * 960 * 4..][..960 * 4]
1300 .chunks_exact(4)
1301 .map(|px| (px[0], px[1], px[2]))
1302 .collect::<Vec<_>>()
1303 };
1304 let black = |row: &[(u8, u8, u8)]| row.iter().all(|&px| px == (0, 0, 0));
1305 assert!(black(&row(&frame, 0)), "top bar is not black");
1306 assert!(black(&row(&frame, 89)), "the bar stops one row early");
1307 assert!(black(&row(&frame, 719)), "bottom bar is not black");
1308 assert!(
1309 !black(&row(&frame, 360)),
1310 "the picture area is black: nothing was composed"
1311 );
1312 // Same clip, filled: the canvas is covered, so no row is a bar.
1313 let (lane, idx) = session.video_clip_at(6.0).expect("a clip at 6 s");
1314 assert!(session.set_fit(lane, idx, engine::scale::FitPolicy::Fill));
1315 session.seek(6.0);
1316 let filled = next_frame(&mut session, "the same clip filled");
1317 assert_eq!((filled.width, filled.height), (960, 720));
1318 assert!(!black(&row(&filled, 0)), "Fill left a top bar");
1319 assert!(!black(&row(&filled, 719)), "Fill left a bottom bar");
1320 assert_ne!(
1321 row(&frame, 360),
1322 row(&filled, 360),
1323 "Fill showed the same pixels as Fit: the crop did nothing"
1324 );
1325}
1326
1327/// The clip that pays nothing: a project at its media's own size must hand the
1328/// decoder's bytes through untouched, not merely equal ones. Same frame, same
1329/// bytes, whether or not the composition path exists.
1330#[test]
1331fn a_project_at_the_media_size_is_the_decoder_untouched() {
1332 let mut session = open(asset("test_baseline.mp4"));
1333 session.seek(1.0);
1334 let frame = next_frame(&mut session, "seek to 1 s");
1335 assert_eq!((frame.width, frame.height), (1280, 720));
1336 assert_eq!(
1337 frame.bgra,
1338 source_frame(&asset("test_baseline.mp4"), frame.index),
1339 "the pass-through path changed a byte"
1340 );
1341}
1342
1343/// The same file twice is one library row -- a source index is handed out once
1344/// and reused, which is what keeps clipboard clips valid forever -- and two
1345/// drags of that one row are two clips of it.
1346#[test]
1347fn importing_one_file_twice_reuses_its_source() {
1348 let mut session = open(asset("test_av.mp4"));
1349 let av2 = asset("test_av2.mp4");
1350 assert_eq!(session.import(&av2).expect("first import"), 1);
1351 assert_eq!(
1352 session.import(&av2).expect("second import"),
1353 1,
1354 "the second import is the same row"
1355 );
1356 assert_eq!(session.sources().len(), 2, "one row for one file");
1357 import_and_place(&mut session, &av2);
1358 import_and_place(&mut session, &av2);
1359 assert_eq!(session.sources().len(), 2, "and still one row");
1360 assert_eq!(
1361 session
1362 .clip_spans_by_source()
1363 .iter()
1364 .map(|&(.., s)| s)
1365 .collect::<Vec<_>>(),
1366 vec![0, 1, 1],
1367 "one new source, two clips of it"
1368 );
1369 assert!(
1370 (session.timeline_duration() - 13.0).abs() < 1e-9,
1371 "5 s + 4 s + 4 s: {}",
1372 session.timeline_duration()
1373 );
1374}
1375
1376/// A library row placed after the timeline has been played out revives the
1377/// session: the placement reseeks like every other edit, and that is what
1378/// clears `eos`. The import itself changes nothing, played out or not.
1379///
1380/// Where it resumes is not asserted, for the reason `paste_at_eos_revives_the_
1381/// session` does not assert it either: an edit reseeks to `now()`, and at EOS
1382/// the free-running clock has gone past the end.
1383#[test]
1384fn a_placement_at_eos_revives_the_session() {
1385 let av2 = asset("test_av2.mp4");
1386 let mut session = open(asset("test_av.mp4"));
1387 let first = session.meta().frame_count;
1388
1389 session.play();
1390 assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
1391 assert!(session.is_eos());
1392
1393 session.import(&av2).expect("import at EOS");
1394 assert!(
1395 session.is_eos(),
1396 "an import is not an edit: it cannot revive"
1397 );
1398 assert!(
1399 session
1400 .place_stream_at(session.timeline_duration(), &av2, 0, None)
1401 .expect("a file just imported is on this timeline")
1402 );
1403 assert!(
1404 !session.is_eos(),
1405 "the placement did not revive the session"
1406 );
1407 assert_eq!(
1408 session.timeline_duration(),
1409 f64::from(first + frame_count(&av2)) / session.meta().frame_rate
1410 );
1411 assert_eq!(session.clip_spans().len(), 2);
1412}
1413
1414/// A source deleted mid-session: the clip that names it contributes no pictures
1415/// and the timeline still ends, instead of stalling on the missing file.
1416#[test]
1417fn a_vanished_source_is_skipped() {
1418 let scratch = Scratch::file("video_editor_vanish", "mp4");
1419 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
1420 let mut session = open(asset("test_av.mp4"));
1421 let first = session.meta().frame_count;
1422 import_and_place(&mut session, &scratch);
1423 std::fs::remove_file(&scratch).expect("unlink");
1424
1425 session.seek(0.0);
1426 session.play();
1427 let (count, last) = drain_to_eof(&mut session);
1428 assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
1429 assert_eq!(count, first, "the first source still played whole");
1430 assert!(session.is_eos(), "the timeline still ends");
1431}
1432
1433/// Importing and placing while the device is running: the placement reseeks
1434/// under the playhead, so what must not happen is a stall -- the joined
1435/// timeline still plays out whole. No audio needed, so this runs anywhere.
1436#[test]
1437fn import_during_play_does_not_stall() {
1438 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1439 let mut session = open(&av);
1440 let first = session.meta().frame_count;
1441 let mut last_index = None;
1442
1443 session.play();
1444 run_for(&mut session, &mut last_index, Duration::from_millis(300));
1445 assert!(last_index.is_some(), "no frames before the import");
1446
1447 import_and_place(&mut session, &av2);
1448 assert_eq!(session.clip_spans().len(), 2);
1449 assert!(session.is_playing(), "the placement stopped the clock");
1450
1451 // From here on the indices go *backwards* once: `run_for` decodes far ahead
1452 // of the clock (ledger), and the import reseeks to `now()` -- which is why
1453 // this drains with `drain_to_eof` instead of the order-checking `pump`.
1454 let (count, last) = drain_to_eof(&mut session);
1455 eprintln!("import while playing: {count} more frames, last {last:?}");
1456 assert_eq!(
1457 last,
1458 Some(first + frame_count(&av2) - 1),
1459 "the joined timeline did not play out"
1460 );
1461}
1462
1463/// An import is *not* an undo step -- a library row changes nothing playable,
1464/// so there is nothing for `z` to take back -- and the placement that follows
1465/// is one. Undoing it leaves the row in the library, where the user put it.
1466#[test]
1467fn an_import_is_not_an_undo_step_but_its_placement_is() {
1468 let av2 = asset("test_av2.mp4");
1469 let mut session = open(asset("test_av.mp4"));
1470 session.import(&av2).expect("import");
1471 assert!(!session.undo(), "an import must not be undoable");
1472 assert_eq!(session.sources().len(), 2, "and it is still in the library");
1473
1474 import_and_place(&mut session, &av2);
1475 assert_eq!(session.clip_spans().len(), 2);
1476 assert!((session.timeline_duration() - 9.0).abs() < 1e-9);
1477
1478 assert!(session.undo(), "undo the placement");
1479 assert_eq!(session.clip_spans().len(), 1, "one step, back to one clip");
1480 assert!(
1481 (session.timeline_duration() - 5.0).abs() < 1e-9,
1482 "undo did not restore the duration: {}",
1483 session.timeline_duration()
1484 );
1485 assert_eq!(
1486 session.sources().len(),
1487 2,
1488 "the library row survives an undo of the clip that used it"
1489 );
1490
1491 // Still playable: the undo reseeked to the (paused) playhead at zero.
1492 session.play();
1493 assert_eq!(next_index(&mut session, "undo of a placement"), 0);
1494}
1495
1496/// The audio path across a source join: one worker spans both files, so the
1497/// clock must keep running at real speed through the boundary. (Whether it is
1498/// still the *audio* clock is not observable from outside -- a device that ran
1499/// dry would fall back to wall time at the same speed -- so this catches a
1500/// stall, not a silent fallback.)
1501#[test]
1502#[ignore = "needs a running PipeWire daemon"]
1503fn audio_runs_across_a_source_join() {
1504 let mut session = open(asset("test_av.mp4"));
1505 import_and_place(&mut session, &asset("test_av2.mp4"));
1506 let first = session.meta().frame_count;
1507
1508 session.seek(4.5); // half a second before the join
1509 session.play();
1510 let mut last_index = None;
1511 run_for(&mut session, &mut last_index, Duration::from_millis(1500));
1512 let now = session.now();
1513 eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
1514 assert!(
1515 (5.4..6.6).contains(&now),
1516 "the clock did not run at real speed across the join: {now:.3}s"
1517 );
1518 assert!(
1519 last_index.map(|i| i > first) == Some(true),
1520 "playback never crossed the join: {last_index:?}"
1521 );
1522 // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
1523 // real time, so the decoder may well have reached 9 s while the clock is at
1524 // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
1525}
1526
1527/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap*
1528/// rather than closing up, and a gap plays: the timeline keeps its length, the
1529/// frame numbering stays contiguous straight through, and every picture over
1530/// the hole is black. No audio needed, so this runs anywhere.
1531#[test]
1532fn a_video_gap_plays_black_without_shortening_the_timeline() {
1533 let path = asset("test_baseline.mp4");
1534 let mut session = open(&path);
1535 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
1536 let whole = session.timeline_duration();
1537
1538 assert!(session.cut_at(2.0), "split at 2 s");
1539 assert!(session.cut_at(3.5), "split at 3.5 s");
1540 assert!(
1541 session.lift_clip(Lane::V1, 1),
1542 "lift the middle picture out"
1543 );
1544 assert_eq!(
1545 session.clip_spans().len(),
1546 2,
1547 "two placements, and a hole between them"
1548 );
1549 assert!(
1550 (session.timeline_duration() - whole).abs() < 1e-9,
1551 "a lift leaves a gap: the timeline is exactly as long as it was"
1552 );
1553
1554 let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
1555 session.seek(0.0);
1556 session.play();
1557 let deadline = Instant::now() + Duration::from_secs(20);
1558 let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32);
1559 loop {
1560 session.tick();
1561 while let Some(frame) = session.try_frame() {
1562 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
1563 let is_black = frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]);
1564 if (hole..hole_end).contains(&frame.index) {
1565 assert!(is_black, "frame {} is inside the gap", frame.index);
1566 black += 1;
1567 } else {
1568 lit += 1;
1569 }
1570 expect += 1;
1571 }
1572 if session.is_eos() {
1573 break;
1574 }
1575 assert!(Instant::now() < deadline, "still draining after 20 s");
1576 sleep(Duration::from_millis(4));
1577 }
1578 assert_eq!(expect, total, "the whole timeline, gap included");
1579 assert_eq!(black, hole_end - hole, "every frame of the hole was black");
1580 assert!(lit > 0, "and the clips around it still decoded");
1581
1582 // The gap is one undo step back to the clip that was there.
1583 assert!(session.undo());
1584 assert_eq!(session.clip_spans().len(), 3);
1585}
1586
1587/// A hole in the *audio* lane, with the device running: the master clock counts
1588/// samples the device has been fed, so silence has to be fed as real chunks or
1589/// the timeline would stall on the hole. Needs a PipeWire daemon and the output
1590/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`).
1591///
1592/// Muted like every other device test: what it asserts is the clock and the
1593/// frame numbering, both of which count fed samples and not their loudness. The
1594/// silence of a gap is proved off the decoder instead, with no device involved,
1595/// in `audio_segments::a_gap_segment_is_silence_of_its_own_length`.
1596#[test]
1597#[ignore = "needs a running PipeWire daemon"]
1598fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
1599 let mut session = open(asset("test_av.mp4"));
1600 assert!(session.cut_at(1.0), "split at 1 s");
1601 assert!(session.cut_at(2.0), "split at 2 s");
1602 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1603 assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
1604 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1605 let duration = session.timeline_duration();
1606
1607 session.seek(0.0);
1608 let mut last_index = None;
1609 session.play();
1610 // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at
1611 // 1 s, so a stall anywhere inside it cannot hide.
1612 run_for(&mut session, &mut last_index, Duration::from_millis(2_400));
1613 let now = session.now();
1614 assert!(
1615 now > 2.2 && now < duration,
1616 "the clock stalled on the audio gap at {now:.3}s"
1617 );
1618 assert!(
1619 last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true),
1620 "pictures stopped over the silence: {last_index:?}"
1621 );
1622 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
1623}
1624
1625/// The emptied timeline, end to end: the last clip deletes like any other, what
1626/// is left plays as black and silence with a duration of zero, it saves and
1627/// loads back as the project it is, and one undo brings the clip back. Silent
1628/// fixture, so this runs anywhere.
1629#[test]
1630fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1631 let path = asset("test_baseline.mp4");
1632 let mut session = open(&path);
1633 let whole = session.timeline_duration();
1634 assert!(whole > 0.0);
1635
1636 // The sole take goes -- picture and sound of it, on every lane at once.
1637 assert!(
1638 session.delete_clip(Lane::V1, 0),
1639 "the last clip deletes like any other"
1640 );
1641 assert!(session.is_empty(), "and the timeline is empty");
1642 assert_eq!(session.timeline_duration(), 0.0);
1643 assert!(session.clip_spans().is_empty());
1644 assert_eq!(session.lanes().len(), 2, "the lanes are still there");
1645
1646 // It scrubs: every seek lands at zero and shows black rather than the
1647 // picture of the clip that was deleted.
1648 for t in [0.0, -1.0, whole, 1e9] {
1649 session.seek(t);
1650 assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline");
1651 let deadline = Instant::now() + Duration::from_secs(5);
1652 let mut black = None;
1653 while black.is_none() && Instant::now() < deadline {
1654 session.tick();
1655 black = session.try_frame();
1656 sleep(Duration::from_millis(4));
1657 }
1658 let frame = black.expect("an empty timeline shows one black frame");
1659 assert_eq!(frame.index, 0);
1660 assert!(
1661 frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
1662 "and it is black"
1663 );
1664 }
1665 // It plays: nothing to show, so it is at its end at once, and nothing hangs.
1666 session.play();
1667 let mut last_index = None;
1668 run_for(&mut session, &mut last_index, Duration::from_millis(200));
1669 assert!(session.is_eos(), "an empty timeline is played out at once");
1670 session.pause();
1671
1672 // Exporting nothing is a refusal in words, not a file of no frames -- and
1673 // in the *same* words whichever format asked, because the fence sits in
1674 // `export::start` ahead of the format, not in the mp4 path alone.
1675 for format in [Format::Mp4, Format::Wav, Format::Flac] {
1676 let dir = Scratch::dir("ve_nothing");
1677 let out = dir.join("ve_nothing");
1678 let handle = session.export_to_with(
1679 &out,
1680 &ExportSettings {
1681 format,
1682 ..ExportSettings::default()
1683 },
1684 );
1685 let deadline = Instant::now() + Duration::from_secs(10);
1686 let err = loop {
1687 if let Some(result) = handle.result() {
1688 break result.expect_err("an empty timeline cannot be exported");
1689 }
1690 assert!(Instant::now() < deadline, "{format:?} export never settled");
1691 sleep(Duration::from_millis(10));
1692 };
1693 assert_eq!(
1694 err.to_string(),
1695 "the timeline is empty: there is nothing to export",
1696 "{format:?}"
1697 );
1698 assert!(!out.exists(), "{format:?} wrote a file anyway");
1699 }
1700
1701 // It saves and loads back -- still a project, still two lanes, and still
1702 // naming the file whose frame rate the timeline counts in.
1703 let dir = Scratch::dir("ve_empty");
1704 let project = dir.join("empty.edith");
1705 session
1706 .save_project(&project)
1707 .expect("save an empty timeline");
1708 let loaded = PlaybackSession::open_project(&project).expect("load it back");
1709 assert!(loaded.is_empty(), "what came back is the empty timeline");
1710 assert_eq!(loaded.lanes().len(), 2);
1711 assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not");
1712 assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate);
1713 drop(loaded);
1714 let _ = std::fs::remove_dir_all(&dir);
1715
1716 // ...and one gesture is one undo: the take comes back whole.
1717 assert!(session.undo(), "the delete undoes");
1718 assert!(!session.is_empty());
1719 assert!((session.timeline_duration() - whole).abs() < 1e-9);
1720 assert_eq!(session.clip_spans().len(), 1);
1721}
1722
1723/// The session half of the late-frame policy: a *watched* session still lands
1724/// exactly on the frame a seek asked for. The floor the worker drops against is
1725/// the playhead mapped back into the file own frames, and a floor even one
1726/// frame ahead of the landing would eat the very picture the seek exists to
1727/// show ([`PlaybackSession::drop_late_pictures`]).
1728#[test]
1729fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() {
1730 let mut session = open(asset("test_baseline.mp4"));
1731 session.drop_late_pictures(true);
1732 let fps = session.meta().frame_rate;
1733 session.seek(3.0);
1734 assert_eq!(
1735 next_index(&mut session, "seek(3.0) on a watched session"),
1736 (3.0 * fps) as u32,
1737 "the landing frame was dropped as late"
1738 );
1739 // ...and again backwards: a floor left where the last span ended would drop
1740 // every picture of a seek that went back.
1741 session.seek(1.0);
1742 assert_eq!(
1743 next_index(&mut session, "seek(1.0) on a watched session"),
1744 (1.0 * fps) as u32
1745 );
1746}
1747
1748/// The pixels a *reused* decoder hands back are the pixels a fresh one does.
1749/// One session takes three seeks -- forwards, backwards, forwards again -- and
1750/// the worker survives all of them (`Worker::reseek`: the file stays open, the
1751/// hardware session is repositioned rather than reopened), so a decoder left
1752/// holding one span references while another span is asked for would show here
1753/// as a smear and nowhere else. The reference is the file-level API, which
1754/// opens a decoder of its own per frame.
1755#[test]
1756fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() {
1757 let path = asset("test_baseline.mp4");
1758 let mut session = open(&path);
1759 let fps = session.meta().frame_rate;
1760 // Small targets on purpose: the fixture's only sync sample is frame 0, so
1761 // every one of these decodes from the start of the file and a debug-build
1762 // software decoder is what runs the suite.
1763 for target in [20u32, 5, 35] {
1764 session.seek(f64::from(target) / fps);
1765 let frame = next_frame(&mut session, "a seek onto a worker already open");
1766 assert_eq!(frame.index, target, "the seek landed elsewhere");
1767 assert!(
1768 frame.bgra == source_frame(&path, target),
1769 "frame {target} off the reused decoder is not the picture a fresh one decodes"
1770 );
1771 }
1772}
1773
1774/// What the drop policy must never do: thin a picture the decoder was keeping up
1775/// with. `pump`'s own contiguity assert covers every *pull* consumer above;
1776/// nothing there bounds what a **watched** session delivers, and a one-in-N
1777/// regression inside the worker would pass the whole suite otherwise.
1778///
1779/// The fixture is the smallest one here (320x180) so the question can be asked
1780/// on a debug build at the file's own rate -- no retime, because a retimed
1781/// timeline legitimately shows only every n-th source frame and the sharp half
1782/// of this test is that the indices arrive one at a time. A box too slow even
1783/// for this says so and stops: thinning the picture there is the policy working
1784/// (`LATE_RUN`), not a regression.
1785#[test]
1786fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() {
1787 let path = asset("test_speed_sync.mp4");
1788
1789 // What this box decodes, flat out, with nothing dropped: frames per second.
1790 let mut measure = open(&path);
1791 let fps = measure.meta().frame_rate;
1792 measure.play();
1793 let mut decoded = 0u32;
1794 let taken = Instant::now();
1795 while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() {
1796 measure.tick();
1797 while measure.try_frame().is_some() {
1798 decoded += 1;
1799 }
1800 sleep(Duration::from_millis(2));
1801 }
1802 let capable = f64::from(decoded) / taken.elapsed().as_secs_f64();
1803 drop(measure);
1804 eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}");
1805 if capable < fps * 1.2 {
1806 eprintln!("SKIP: too slow to ask the question at all");
1807 return;
1808 }
1809
1810 // Watched, playing at its own rate, drained like a front-end that keeps up:
1811 // every picture is due when it arrives and none of them may be dropped.
1812 let mut session = open(&path);
1813 session.drop_late_pictures(true);
1814 session.play();
1815 let mut delivered = 0u32;
1816 let mut last: Option<u32> = None;
1817 let watched = Instant::now();
1818 while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() {
1819 session.tick();
1820 while let Some(frame) = session.try_frame() {
1821 delivered += 1;
1822 if let Some(previous) = last {
1823 assert_eq!(
1824 frame.index,
1825 previous + 1,
1826 "a picture was dropped while the decoder was keeping up"
1827 );
1828 }
1829 last = Some(frame.index);
1830 }
1831 sleep(Duration::from_millis(2));
1832 }
1833 // Frames the clock went over, which is what the timeline owed the screen.
1834 let passed = session.now() * fps;
1835 let density = f64::from(delivered) / passed.max(1.0);
1836 eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock");
1837 assert!(
1838 density >= 0.9,
1839 "the worker thinned a picture it was keeping up with: {delivered} of \
1840 {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps"
1841 );
1842}
1843
1844/// The decode-ahead a **freshly opened** file gets. Every session opens its first
1845/// worker pass-through -- a file just opened *is* the project resolution -- and
1846/// asking a pass-through canvas how deep to queue answers 2, the bound this
1847/// engine had before there was any decode-ahead: the whole file would then play
1848/// at that depth until the first seek built a real canvas. The depth is taken
1849/// from the stream instead (`scale::queue_depth`), and this is where that is
1850/// visible from outside: a paused session left alone fills its queue, and the
1851/// burst that comes off it is the depth plus the picture in the worker's hand.
1852///
1853/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so
1854/// the burst is 17 and the regression it guards against is a burst of 3.
1855#[test]
1856fn a_freshly_opened_file_queues_more_than_two_pictures() {
1857 let mut session = open(asset("test_baseline.mp4"));
1858 // Paused throughout: no seek, no play, nothing that would build a canvas.
1859 // The best of three attempts, because filling the queue is the decoder's own
1860 // work and this box shares itself with whatever else is running.
1861 let mut burst = 0;
1862 for _ in 0..3 {
1863 sleep(Duration::from_millis(1500));
1864 let mut n = 0;
1865 while session.try_frame().is_some() {
1866 n += 1;
1867 }
1868 burst = burst.max(n);
1869 }
1870 eprintln!("burst off a freshly opened file: {burst} pictures");
1871 assert!(
1872 burst > 8,
1873 "a freshly opened file queued {burst} pictures: the first worker is \
1874 still sizing its queue from a pass-through canvas"
1875 );
1876
1877 // ...and the same worker still answers. Four and a half seconds parked is
1878 // well past the idle mark at which it closes its hardware session
1879 // (`decode`'s `IDLE`), so this is the seek that has to reopen one lazily --
1880 // the one path that would have gone quiet if closing it left the worker
1881 // holding a decoder it could no longer use.
1882 let fps = session.meta().frame_rate;
1883 session.seek(2.0);
1884 assert_eq!(
1885 next_index(&mut session, "a seek after the worker went idle"),
1886 (2.0 * fps) as u32,
1887 "the worker did not come back from its idle park"
1888 );
1889}