forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

playback.rs1910 lines, 77.0 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::{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.clone()), "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 // Frames arriving is the decoder's work, which a loaded machine delays: wait
875 // for the first one instead of betting on 300 ms.
876 let deadline = Instant::now() + Duration::from_secs(20);
877 while last_index.is_none() {
878 assert!(Instant::now() < deadline, "no frames before the paste");
879 run_for(&mut session, &mut last_index, Duration::from_millis(50));
880 }
881
882 // Into the clip under the running playhead: the paste splits it in two and
883 // lands between the halves.
884 assert!(
885 session.paste_at(session.now(), copied.clone()),
886 "paste at the playhead"
887 );
888 assert!(session.is_playing(), "the paste stopped the clock");
889 assert_eq!(session.clip_spans().len(), 4);
890 let grown = total + copied.len();
891 assert!(
892 (session.timeline_duration() - f64::from(grown) / fps).abs() < 1e-9,
893 "duration after the paste: {}",
894 session.timeline_duration()
895 );
896
897 // As after a mid-play import: the reseek makes the indices step backwards
898 // once, so this drains without `pump`'s index-order check.
899 let (count, last) = drain_to_eof(&mut session);
900 eprintln!("paste while playing: {count} more frames, last {last:?}");
901 assert_eq!(last, Some(grown - 1), "the grown timeline did not play out");
902}
903
904/// Pasting past the end of a played-out timeline appends, and the reseek every
905/// edit does clears `eos` -- so the session plays on into the pasted clip
906/// instead of staying dead.
907#[test]
908fn paste_at_eos_revives_the_session() {
909 let path = asset("test_baseline.mp4");
910 let mut session = open(&path);
911 let total = session.meta().frame_count;
912
913 assert!(session.cut_at(2.0), "cut at 2 s");
914 let copied = session.clip_at(0).expect("clip 0");
915 session.play();
916 assert_eq!(drain_to_eof(&mut session).1, Some(total - 1));
917 assert!(session.is_eos());
918 // The clock does not stop at the end: it runs on, on wall time. A slow
919 // drain (a loaded machine) leaves it past the pasted clip's end by the time
920 // the paste happens, so make that the case on purpose, at 4x to keep it short.
921 let fps = session.meta().frame_rate;
922 session.set_rate(4.0);
923 let past = f64::from(total + copied.len()) / fps + 0.1;
924 let deadline = Instant::now() + Duration::from_secs(20);
925 while session.now() < past {
926 assert!(Instant::now() < deadline, "the clock never ran on");
927 sleep(Duration::from_millis(10));
928 }
929
930 assert!(
931 session.paste_at(999.0, copied.clone()),
932 "paste past the end appends"
933 );
934 assert!(!session.is_eos(), "the paste did not revive the session");
935 assert_eq!(
936 session.clip_spans().len(),
937 3,
938 "two clips plus the pasted one"
939 );
940 // It resumes where the viewer saw the timeline end -- the pasted clip's first
941 // frame -- not where the wall clock has since got to, so the whole pasted
942 // clip plays rather than only its last frame (or none of it).
943 assert_eq!(
944 next_index(&mut session, "paste at EOS"),
945 total,
946 "the paste did not resume at the old end"
947 );
948 assert_eq!(
949 drain_to_eof(&mut session).1,
950 Some(total + copied.len() - 1),
951 "the pasted clip did not play out"
952 );
953}
954
955/// Editing while the device is running. A cut must not disturb playback at all
956/// and a delete reseeks under it -- in both cases the audio keeps coming, which
957/// is what stops `tick` from handing the timeline back to wall time.
958#[test]
959#[ignore = "needs a running PipeWire daemon"]
960fn edits_keep_the_audio_clock() {
961 let mut session = open(asset("test_av.mp4"));
962 let fps = session.meta().frame_rate;
963 let mut last_index = None;
964
965 session.play();
966 run_for(&mut session, &mut last_index, Duration::from_millis(700));
967 let before = session.now();
968 assert!(before > 0.3, "clock stalled at {before:.3}s");
969
970 // Metadata only: no worker is touched, so the indices stay contiguous
971 // across the boundary `run_for` is about to cross.
972 assert!(session.cut_at(1.5), "cut at 1.5 s");
973 run_for(&mut session, &mut last_index, Duration::from_millis(900));
974 let after_cut = session.now();
975 assert!(
976 after_cut > before + 0.6,
977 "the clock stopped across the cut: {before:.3}s -> {after_cut:.3}s"
978 );
979 assert!(
980 last_index.map(|i| f64::from(i) > 1.5 * fps) == Some(true),
981 "playback never reached the cut: {last_index:?}"
982 );
983
984 // Deleting the head clip moves everything after it, so the session reseeks
985 // under the playhead: same timeline position, new source frame, and the
986 // frame numbering restarts at the landing frame.
987 assert!(session.delete_clip(Lane::V1, 0), "drop the head clip");
988 let landed = session.now();
989 assert!(
990 (landed - after_cut).abs() < 0.2,
991 "the delete moved the playhead: {after_cut:.3}s -> {landed:.3}s"
992 );
993 let first = next_frame(&mut session, "the delete reseek").index;
994 assert!(
995 first.abs_diff((landed * fps) as u32) <= 1,
996 "the delete landed at {first} instead of the playhead ({landed:.3}s)"
997 );
998 // No EOS assertion here: `run_for` drains a frame per 8 ms call, far faster
999 // than real time (ledger), so how much timeline is left after it is a race.
1000 let mut after_delete = Some(first);
1001 run_for(&mut session, &mut after_delete, Duration::from_millis(500));
1002 assert!(after_delete > Some(first), "no frames after the delete");
1003 assert!(
1004 session.now() > landed + 0.3,
1005 "the clock stopped after the delete: {landed:.3}s -> {:.3}s",
1006 session.now()
1007 );
1008 eprintln!(
1009 "edits: {before:.3}s -> cut -> {after_cut:.3}s -> delete -> {:.3}s of a {:.3}s timeline",
1010 session.now(),
1011 session.timeline_duration()
1012 );
1013}
1014
1015/// The two acts a second file on the timeline now takes, in the order a user
1016/// does them: taken into the library, then dragged onto the end of the
1017/// timeline. An import registers a source and places nothing
1018/// (`PlaybackSession::import`), so every test that wants a second source *on*
1019/// the lanes does both.
1020fn import_and_place(session: &mut PlaybackSession, path: &Path) {
1021 session.import(path).expect("the file joins this timeline");
1022 let end = session.timeline_duration();
1023 assert!(
1024 session
1025 .place_stream_at(end, path, 0, None)
1026 .expect("a file just imported is on this timeline"),
1027 "the drag onto the end of the timeline"
1028 );
1029}
1030
1031/// Frame count straight from the container, without decoding anything.
1032fn frame_count(path: &Path) -> u32 {
1033 engine::demux::Demuxer::open(path)
1034 .expect("demux")
1035 .0
1036 .frame_count
1037}
1038
1039/// An imported file dragged onto the end of the timeline, played through as
1040/// one stream. No audio needed for the pictures, so this runs anywhere.
1041#[test]
1042fn a_placed_import_plays_across_the_join() {
1043 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1044 let mut session = open(&av);
1045 let (fps, first) = (session.meta().frame_rate, session.meta().frame_count);
1046 let second = frame_count(&av2);
1047 assert_eq!((first, second), (150, 120), "fixtures changed");
1048
1049 // The import alone fills the library: nothing on the lanes moved.
1050 session.import(&av2).expect("test_av2 matches test_av");
1051 assert_eq!(session.clip_spans().len(), 1, "an import placed a clip");
1052 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1053 assert_eq!(session.file_frames(&av2), second, "its own length is noted");
1054 // ...and the drag puts it at the end.
1055 let end = session.timeline_duration();
1056 assert!(
1057 session
1058 .place_stream_at(end, &av2, 0, None)
1059 .expect("a file just imported is on this timeline")
1060 );
1061 assert_eq!(session.clip_spans().len(), 2);
1062 assert_eq!(
1063 session
1064 .clip_spans_by_source()
1065 .iter()
1066 .map(|&(.., s)| s)
1067 .collect::<Vec<_>>(),
1068 vec![0, 1],
1069 "the placed clip plays the imported file"
1070 );
1071 assert!(
1072 (session.timeline_duration() - 9.0).abs() < 1e-9,
1073 "5 s + 4 s: {}",
1074 session.timeline_duration()
1075 );
1076
1077 // Play the joined timeline whole, keeping the picture at the join.
1078 session.seek(0.0);
1079 session.play();
1080 let deadline = Instant::now() + Duration::from_secs(30);
1081 let (mut expect, mut boundary) = (0, None);
1082 loop {
1083 session.tick();
1084 while let Some(frame) = session.try_frame() {
1085 assert_eq!(
1086 frame.index, expect,
1087 "timeline indices must be contiguous across a source join"
1088 );
1089 if frame.index == first {
1090 boundary = Some(frame.bgra);
1091 }
1092 expect += 1;
1093 }
1094 if session.is_eos() {
1095 break;
1096 }
1097 assert!(Instant::now() < deadline, "still draining after 30 s");
1098 sleep(Duration::from_millis(4));
1099 }
1100 assert_eq!(expect, first + second, "270 frames, whole and nothing but");
1101 // As everywhere else: stop the clock before asserting on landing frames.
1102 session.pause();
1103 assert!(
1104 boundary.expect("no frame at the join") == source_frame(&av2, 0),
1105 "timeline frame {first} is not the imported file's frame 0"
1106 );
1107
1108 // Edits across the join keep every clip pointing at its own file: cut one
1109 // second into the imported clip, then drop the whole original.
1110 assert!(session.cut_at(6.0), "cut 1 s into the imported clip");
1111 assert_eq!(session.clip_spans().len(), 3);
1112 assert!(session.delete_clip(Lane::V1, 0), "drop the first source");
1113 assert_eq!(session.clip_spans_by_source()[0].2, 1);
1114 assert!(
1115 (session.timeline_duration() - f64::from(second) / fps).abs() < 1e-9,
1116 "only the imported file is left: {}",
1117 session.timeline_duration()
1118 );
1119 session.seek(0.0);
1120 let landed = next_frame(&mut session, "seek(0.0) after the delete");
1121 assert_eq!(landed.index, 0);
1122 assert!(
1123 landed.bgra == source_frame(&av2, 0),
1124 "the delete lost the source mapping"
1125 );
1126
1127 assert!(session.undo(), "undo the delete");
1128 assert_eq!(session.clip_spans().len(), 3);
1129 let restored = next_frame(&mut session, "undo");
1130 assert_eq!(restored.index, 0);
1131 assert!(
1132 restored.bgra == source_frame(&av, 0),
1133 "undo did not restore the first source"
1134 );
1135}
1136
1137/// The first import into a window with nothing open: the file fills the library
1138/// and the timeline stays *empty*, and the drag that follows is what puts it on
1139/// a lane -- at the file's own length, which nothing on the timeline could have
1140/// told the session. The whole point of an import that places nothing.
1141#[test]
1142fn the_first_import_opens_a_library_over_an_empty_timeline() {
1143 let av = asset("test_av.mp4");
1144 let mut session = PlaybackSession::open_library(&av).expect("open into the library");
1145 session.set_gain(0.0);
1146 assert!(session.is_empty(), "the timeline must start empty");
1147 assert_eq!(session.timeline_duration(), 0.0);
1148 assert!(session.clip_spans().is_empty());
1149 // But it is a session: the file's own picture, rate and clock, and its row.
1150 assert_eq!(session.sources().len(), 1, "the library row");
1151 assert_eq!(session.resolution(), (1280, 720));
1152 assert_eq!(session.meta().frame_rate, 30.0);
1153 assert_eq!(session.file_frames(&av), 150, "5 s at 30 fps, never placed");
1154 assert!(!session.undo(), "opening a library is not an undo step");
1155
1156 // The drag: the row goes onto the timeline whole, and it plays from there.
1157 assert!(
1158 session
1159 .place_stream_at(0.0, &av, 0, None)
1160 .expect("its own file is on this timeline")
1161 );
1162 assert!(!session.is_empty(), "the drag left the timeline empty");
1163 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1164 session.seek(0.0);
1165 let landed = next_frame(&mut session, "the dragged clip");
1166 assert_eq!(landed.index, 0);
1167 assert!(
1168 landed.bgra == source_frame(&av, 0),
1169 "the placed clip is not playing its file"
1170 );
1171 // ...and it is an edit like any other, so one `z` takes it back to empty.
1172 assert!(session.undo(), "undo the drag");
1173 assert!(session.is_empty());
1174 assert_eq!(session.sources().len(), 1, "the row survives the undo");
1175}
1176
1177/// One timeline, one frame rate and one set of audio parameters: what is left
1178/// is refused by name and changes nothing.
1179#[test]
1180fn import_refuses_what_does_not_match() {
1181 let mut session = open(asset("test_av.mp4"));
1182
1183 // A different *codec* is not among them any more -- every clip opens its
1184 // own software decoder, so VP9 joins the H.264 timeline without the plugin.
1185 match session.import(&asset("test_vp9.mp4")) {
1186 Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"),
1187 Err(e) => panic!("VP9 must join the timeline through its software seat: {e}"),
1188 }
1189 let rows = session.sources().len();
1190
1191 // A different resolution is no longer among the refusals -- it is placed on
1192 // the project canvas instead -- and neither is a file with no sound: it
1193 // contributes silence over its span.
1194 session
1195 .import(&asset("test_mismatch.mp4"))
1196 .expect("a silent 640x360 file joins a timeline with sound");
1197
1198 // A frame rate of its own is no longer a refusal either: 25 fps joins a
1199 // 30 fps timeline and is read at `Rate` against it -- see
1200 // `tests/mixed_fps.rs` for what it then plays like.
1201 session
1202 .import(&asset("test_25fps.mp4"))
1203 .expect("25 fps may join a 30 fps timeline");
1204 session
1205 .remove_source(&asset("test_25fps.mp4"), 0)
1206 .expect("...and the row it made comes back off");
1207
1208 // A sample *rate* of its own is no longer a refusal either: one output
1209 // device means one rate, and the segment's own resampler is what makes two
1210 // into one now ([`engine::audio::Resample`]).
1211 session
1212 .import(&asset("test_tone_48k.wav"))
1213 .expect("48 kHz may join a 44.1 kHz timeline");
1214 session
1215 .remove_source(&asset("test_tone_48k.wav"), 0)
1216 .expect("...and the row it made comes back off");
1217
1218 // A mono track is no longer a refusal either (DEBT #46): [`engine::audio`]
1219 // duplicates its one channel into both of this stereo timeline's, the same
1220 // way a wider file is already folded down to it.
1221 session
1222 .import(&asset("test_ac3.mp4"))
1223 .expect("a mono track up-mixes onto a stereo timeline");
1224
1225 assert!(
1226 session.import(&asset("no_such_file.mp4")).is_err(),
1227 "a missing file is an error, not a panic"
1228 );
1229 assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
1230 assert_eq!(
1231 session.sources().len(),
1232 rows + 2,
1233 "the silent file and the mono file were both taken in"
1234 );
1235 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
1236
1237 // The mirror is no longer a refusal either: a silent timeline (no audio
1238 // track in any source) takes a file with sound, and that sound becomes the
1239 // timeline's own -- the session re-arms its device on the sounding file
1240 // (`tests/silent_first_source.rs` hears it through playback). Before that
1241 // change this was refused by name, which pinned a timeline to its silent
1242 // first source for good.
1243 let mut silent = open(asset("test_baseline.mp4"));
1244 silent
1245 .import(&asset("test_av.mp4"))
1246 .expect("sound joins a silent timeline");
1247 assert_eq!(silent.sources().len(), 2, "the sounding file was taken in");
1248}
1249
1250/// The user path a silent take goes down: a file with no audio track lands on a
1251/// timeline that has one, is placed as the grouped take every video file is,
1252/// and plays -- pictures over its span, silence under them. The sound itself is
1253/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is
1254/// that nothing about the *timeline* is refused or lost.
1255#[test]
1256fn a_silent_file_joins_a_timeline_with_sound_and_plays() {
1257 let mut session = open(asset("test_av.mp4"));
1258 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1259 // 150 frames of test_av, then 60 of the silent file, at 30 fps.
1260 assert_eq!(session.clip_spans().len(), 2, "the silent take landed");
1261 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1262 // Both lanes carry it: a silent file is a normal grouped take, and its
1263 // audio clip is the span the worker fills with silence.
1264 assert_eq!(session.lane_clips(Lane::V1).len(), 2);
1265 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
1266
1267 // ...and it decodes: a picture from inside the silent clip's span, at the
1268 // project's resolution like every other clip.
1269 session.seek(6.0);
1270 let frame = next_frame(&mut session, "the silent clip");
1271 assert_eq!((frame.width, frame.height), session.resolution());
1272}
1273
1274/// The user-facing point of a project resolution: media of two sizes on one
1275/// timeline, each composed onto the project's own canvas.
1276///
1277/// 640x360 joins a 1280x720 timeline (it would have been refused before this
1278/// slice), and both clips come out of `try_frame` at the project's size --
1279/// which is what makes the export, the window and the renderer one shape.
1280#[test]
1281fn media_of_two_resolutions_share_one_timeline() {
1282 let mut session = open(asset("test_baseline.mp4"));
1283 assert_eq!(session.resolution(), (1280, 720), "source 0's picture");
1284 assert_eq!(session.native_resolution(), (1280, 720));
1285 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1286 // 150 frames of the first file, then 60 of the second, at 30 fps.
1287 assert_eq!(session.clip_spans().len(), 2);
1288 assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
1289
1290 for (at, what) in [(1.0, "the 1280x720 clip"), (6.0, "the 640x360 clip")] {
1291 session.seek(at);
1292 let frame = next_frame(&mut session, what);
1293 assert_eq!(
1294 (frame.width, frame.height),
1295 (1280, 720),
1296 "{what} did not come out at the project resolution"
1297 );
1298 assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
1299 }
1300}
1301
1302/// The geometry, asserted on the pixels: on a canvas whose aspect the media does
1303/// not share, a `Fit` clip is letterboxed -- bars exactly black, picture where
1304/// `scale::fit_rect` puts it -- and `Fill` crops the bars away.
1305#[test]
1306fn a_fitted_clip_is_letterboxed_and_a_filled_one_is_not() {
1307 let mut session = open(asset("test_baseline.mp4"));
1308 import_and_place(&mut session, &asset("test_mismatch.mp4"));
1309 // A 4:3 project: both clips are 16:9, so both are letterboxed on it. 960x720
1310 // holds the whole 640x360 picture as 960x540 with 90 rows of bar either way
1311 // (fit_rect's own arithmetic, asserted in scale.rs).
1312 assert!(session.set_resolution(960, 720), "4:3 project");
1313 session.seek(6.0);
1314 let frame = next_frame(&mut session, "the 640x360 clip on a 4:3 canvas");
1315 assert_eq!((frame.width, frame.height), (960, 720));
1316 let row = |frame: &Frame, y: usize| {
1317 frame.bgra[y * 960 * 4..][..960 * 4]
1318 .as_chunks::<4>().0.iter()
1319 .map(|px| (px[0], px[1], px[2]))
1320 .collect::<Vec<_>>()
1321 };
1322 let black = |row: &[(u8, u8, u8)]| row.iter().all(|&px| px == (0, 0, 0));
1323 assert!(black(&row(&frame, 0)), "top bar is not black");
1324 assert!(black(&row(&frame, 89)), "the bar stops one row early");
1325 assert!(black(&row(&frame, 719)), "bottom bar is not black");
1326 assert!(
1327 !black(&row(&frame, 360)),
1328 "the picture area is black: nothing was composed"
1329 );
1330 // Same clip, filled: the canvas is covered, so no row is a bar.
1331 let (lane, idx) = session.video_clip_at(6.0).expect("a clip at 6 s");
1332 assert!(session.set_fit(lane, idx, engine::scale::FitPolicy::Fill));
1333 session.seek(6.0);
1334 let filled = next_frame(&mut session, "the same clip filled");
1335 assert_eq!((filled.width, filled.height), (960, 720));
1336 assert!(!black(&row(&filled, 0)), "Fill left a top bar");
1337 assert!(!black(&row(&filled, 719)), "Fill left a bottom bar");
1338 assert_ne!(
1339 row(&frame, 360),
1340 row(&filled, 360),
1341 "Fill showed the same pixels as Fit: the crop did nothing"
1342 );
1343}
1344
1345/// The clip that pays nothing: a project at its media's own size must hand the
1346/// decoder's bytes through untouched, not merely equal ones. Same frame, same
1347/// bytes, whether or not the composition path exists.
1348#[test]
1349fn a_project_at_the_media_size_is_the_decoder_untouched() {
1350 let mut session = open(asset("test_baseline.mp4"));
1351 session.seek(1.0);
1352 let frame = next_frame(&mut session, "seek to 1 s");
1353 assert_eq!((frame.width, frame.height), (1280, 720));
1354 assert_eq!(
1355 frame.bgra,
1356 source_frame(&asset("test_baseline.mp4"), frame.index),
1357 "the pass-through path changed a byte"
1358 );
1359}
1360
1361/// The same file twice is one library row -- a source index is handed out once
1362/// and reused, which is what keeps clipboard clips valid forever -- and two
1363/// drags of that one row are two clips of it.
1364#[test]
1365fn importing_one_file_twice_reuses_its_source() {
1366 let mut session = open(asset("test_av.mp4"));
1367 let av2 = asset("test_av2.mp4");
1368 assert_eq!(session.import(&av2).expect("first import"), 1);
1369 assert_eq!(
1370 session.import(&av2).expect("second import"),
1371 1,
1372 "the second import is the same row"
1373 );
1374 assert_eq!(session.sources().len(), 2, "one row for one file");
1375 import_and_place(&mut session, &av2);
1376 import_and_place(&mut session, &av2);
1377 assert_eq!(session.sources().len(), 2, "and still one row");
1378 assert_eq!(
1379 session
1380 .clip_spans_by_source()
1381 .iter()
1382 .map(|&(.., s)| s)
1383 .collect::<Vec<_>>(),
1384 vec![0, 1, 1],
1385 "one new source, two clips of it"
1386 );
1387 assert!(
1388 (session.timeline_duration() - 13.0).abs() < 1e-9,
1389 "5 s + 4 s + 4 s: {}",
1390 session.timeline_duration()
1391 );
1392}
1393
1394/// A library row placed after the timeline has been played out revives the
1395/// session: the placement reseeks like every other edit, and that is what
1396/// clears `eos`. The import itself changes nothing, played out or not.
1397///
1398/// Where it resumes is not asserted, for the reason `paste_at_eos_revives_the_
1399/// session` does not assert it either: an edit reseeks to `now()`, and at EOS
1400/// the free-running clock has gone past the end.
1401#[test]
1402fn a_placement_at_eos_revives_the_session() {
1403 let av2 = asset("test_av2.mp4");
1404 let mut session = open(asset("test_av.mp4"));
1405 let first = session.meta().frame_count;
1406
1407 session.play();
1408 assert_eq!(drain_to_eof(&mut session).1, Some(first - 1));
1409 assert!(session.is_eos());
1410
1411 session.import(&av2).expect("import at EOS");
1412 assert!(
1413 session.is_eos(),
1414 "an import is not an edit: it cannot revive"
1415 );
1416 assert!(
1417 session
1418 .place_stream_at(session.timeline_duration(), &av2, 0, None)
1419 .expect("a file just imported is on this timeline")
1420 );
1421 assert!(
1422 !session.is_eos(),
1423 "the placement did not revive the session"
1424 );
1425 assert_eq!(
1426 session.timeline_duration(),
1427 f64::from(first + frame_count(&av2)) / session.meta().frame_rate
1428 );
1429 assert_eq!(session.clip_spans().len(), 2);
1430}
1431
1432/// A source deleted mid-session: the clip that names it contributes no pictures
1433/// and the timeline still ends, instead of stalling on the missing file.
1434#[test]
1435fn a_vanished_source_is_skipped() {
1436 let scratch = Scratch::file("video_editor_vanish", "mp4");
1437 std::fs::copy(asset("test_av2.mp4"), &scratch).expect("copy the fixture");
1438 let mut session = open(asset("test_av.mp4"));
1439 let first = session.meta().frame_count;
1440 import_and_place(&mut session, &scratch);
1441 std::fs::remove_file(&scratch).expect("unlink");
1442
1443 session.seek(0.0);
1444 session.play();
1445 let (count, last) = drain_to_eof(&mut session);
1446 assert_eq!(last, Some(first - 1), "the vanished clip made pictures");
1447 assert_eq!(count, first, "the first source still played whole");
1448 assert!(session.is_eos(), "the timeline still ends");
1449}
1450
1451/// Importing and placing while the device is running: the placement reseeks
1452/// under the playhead, so what must not happen is a stall -- the joined
1453/// timeline still plays out whole. No audio needed, so this runs anywhere.
1454#[test]
1455fn import_during_play_does_not_stall() {
1456 let (av, av2) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1457 let mut session = open(&av);
1458 let first = session.meta().frame_count;
1459 let mut last_index = None;
1460
1461 session.play();
1462 run_for(&mut session, &mut last_index, Duration::from_millis(300));
1463 assert!(last_index.is_some(), "no frames before the import");
1464
1465 import_and_place(&mut session, &av2);
1466 assert_eq!(session.clip_spans().len(), 2);
1467 assert!(session.is_playing(), "the placement stopped the clock");
1468
1469 // From here on the indices go *backwards* once: `run_for` decodes far ahead
1470 // of the clock (ledger), and the import reseeks to `now()` -- which is why
1471 // this drains with `drain_to_eof` instead of the order-checking `pump`.
1472 let (count, last) = drain_to_eof(&mut session);
1473 eprintln!("import while playing: {count} more frames, last {last:?}");
1474 assert_eq!(
1475 last,
1476 Some(first + frame_count(&av2) - 1),
1477 "the joined timeline did not play out"
1478 );
1479}
1480
1481/// An import is *not* an undo step -- a library row changes nothing playable,
1482/// so there is nothing for `z` to take back -- and the placement that follows
1483/// is one. Undoing it leaves the row in the library, where the user put it.
1484#[test]
1485fn an_import_is_not_an_undo_step_but_its_placement_is() {
1486 let av2 = asset("test_av2.mp4");
1487 let mut session = open(asset("test_av.mp4"));
1488 session.import(&av2).expect("import");
1489 assert!(!session.undo(), "an import must not be undoable");
1490 assert_eq!(session.sources().len(), 2, "and it is still in the library");
1491
1492 import_and_place(&mut session, &av2);
1493 assert_eq!(session.clip_spans().len(), 2);
1494 assert!((session.timeline_duration() - 9.0).abs() < 1e-9);
1495
1496 assert!(session.undo(), "undo the placement");
1497 assert_eq!(session.clip_spans().len(), 1, "one step, back to one clip");
1498 assert!(
1499 (session.timeline_duration() - 5.0).abs() < 1e-9,
1500 "undo did not restore the duration: {}",
1501 session.timeline_duration()
1502 );
1503 assert_eq!(
1504 session.sources().len(),
1505 2,
1506 "the library row survives an undo of the clip that used it"
1507 );
1508
1509 // Still playable: the undo reseeked to the (paused) playhead at zero.
1510 session.play();
1511 assert_eq!(next_index(&mut session, "undo of a placement"), 0);
1512}
1513
1514/// The audio path across a source join: one worker spans both files, so the
1515/// clock must keep running at real speed through the boundary. (Whether it is
1516/// still the *audio* clock is not observable from outside -- a device that ran
1517/// dry would fall back to wall time at the same speed -- so this catches a
1518/// stall, not a silent fallback.)
1519#[test]
1520#[ignore = "needs a running PipeWire daemon"]
1521fn audio_runs_across_a_source_join() {
1522 let mut session = open(asset("test_av.mp4"));
1523 import_and_place(&mut session, &asset("test_av2.mp4"));
1524 let first = session.meta().frame_count;
1525
1526 session.seek(4.5); // half a second before the join
1527 session.play();
1528 let mut last_index = None;
1529 run_for(&mut session, &mut last_index, Duration::from_millis(1500));
1530 let now = session.now();
1531 eprintln!("join: clock {now:.3}s, frames ..={last_index:?}");
1532 assert!(
1533 (5.4..6.6).contains(&now),
1534 "the clock did not run at real speed across the join: {now:.3}s"
1535 );
1536 assert!(
1537 last_index.map(|i| i > first) == Some(true),
1538 "playback never crossed the join: {last_index:?}"
1539 );
1540 // No EOS assertion: `run_for` takes a frame per 8 ms call, far faster than
1541 // real time, so the decoder may well have reached 9 s while the clock is at
1542 // 6 s (ledger; same reason `edits_keep_the_audio_clock` has none).
1543}
1544
1545/// A hole in the video lane. Lifting a clip out of one lane leaves a *gap*
1546/// rather than closing up, and a gap plays: the timeline keeps its length, the
1547/// frame numbering stays contiguous straight through, and every picture over
1548/// the hole is black. No audio needed, so this runs anywhere.
1549#[test]
1550fn a_video_gap_plays_black_without_shortening_the_timeline() {
1551 let path = asset("test_baseline.mp4");
1552 let mut session = open(&path);
1553 let (fps, total) = (session.meta().frame_rate, session.meta().frame_count);
1554 let whole = session.timeline_duration();
1555
1556 assert!(session.cut_at(2.0), "split at 2 s");
1557 assert!(session.cut_at(3.5), "split at 3.5 s");
1558 assert!(
1559 session.lift_clip(Lane::V1, 1),
1560 "lift the middle picture out"
1561 );
1562 assert_eq!(
1563 session.clip_spans().len(),
1564 2,
1565 "two placements, and a hole between them"
1566 );
1567 assert!(
1568 (session.timeline_duration() - whole).abs() < 1e-9,
1569 "a lift leaves a gap: the timeline is exactly as long as it was"
1570 );
1571
1572 let (hole, hole_end) = ((2.0 * fps) as u32, (3.5 * fps) as u32);
1573 session.seek(0.0);
1574 session.play();
1575 let deadline = Instant::now() + Duration::from_secs(20);
1576 let (mut expect, mut black, mut lit) = (0u32, 0u32, 0u32);
1577 loop {
1578 session.tick();
1579 while let Some(frame) = session.try_frame() {
1580 assert_eq!(frame.index, expect, "timeline indices must be contiguous");
1581 let is_black = frame.bgra.as_chunks::<4>().0.iter().all(|p| p[..3] == [0, 0, 0]);
1582 if (hole..hole_end).contains(&frame.index) {
1583 assert!(is_black, "frame {} is inside the gap", frame.index);
1584 black += 1;
1585 } else {
1586 lit += 1;
1587 }
1588 expect += 1;
1589 }
1590 if session.is_eos() {
1591 break;
1592 }
1593 assert!(Instant::now() < deadline, "still draining after 20 s");
1594 sleep(Duration::from_millis(4));
1595 }
1596 assert_eq!(expect, total, "the whole timeline, gap included");
1597 assert_eq!(black, hole_end - hole, "every frame of the hole was black");
1598 assert!(lit > 0, "and the clips around it still decoded");
1599
1600 // The gap is one undo step back to the clip that was there.
1601 assert!(session.undo());
1602 assert_eq!(session.clip_spans().len(), 3);
1603}
1604
1605/// A hole in the *audio* lane, with the device running: the master clock counts
1606/// samples the device has been fed, so silence has to be fed as real chunks or
1607/// the timeline would stall on the hole. Needs a PipeWire daemon and the output
1608/// plugin next to the test binary (`LD_LIBRARY_PATH=target/release`).
1609///
1610/// Muted like every other device test: what it asserts is the clock and the
1611/// frame numbering, both of which count fed samples and not their loudness. The
1612/// silence of a gap is proved off the decoder instead, with no device involved,
1613/// in `audio_segments::a_gap_segment_is_silence_of_its_own_length`.
1614#[test]
1615#[ignore = "needs a running PipeWire daemon"]
1616fn an_audio_gap_is_silent_and_the_clock_keeps_counting() {
1617 let mut session = open(asset("test_av.mp4"));
1618 assert!(session.cut_at(1.0), "split at 1 s");
1619 assert!(session.cut_at(2.0), "split at 2 s");
1620 // Silence over [1, 2) s while the picture plays on -- the two lanes part.
1621 assert!(session.lift_clip(Lane::A1, 1), "lift the middle sound out");
1622 assert_eq!(session.clip_spans().len(), 3, "the video lane is untouched");
1623 let duration = session.timeline_duration();
1624
1625 session.seek(0.0);
1626 let mut last_index = None;
1627 session.play();
1628 // Straight across the hole: 2.4 s of wall time over a 1 s gap starting at
1629 // 1 s, so a stall anywhere inside it cannot hide.
1630 run_for(&mut session, &mut last_index, Duration::from_millis(2_400));
1631 let now = session.now();
1632 assert!(
1633 now > 2.2 && now < duration,
1634 "the clock stalled on the audio gap at {now:.3}s"
1635 );
1636 assert!(
1637 last_index.map(|i| f64::from(i) > 2.0 * session.meta().frame_rate) == Some(true),
1638 "pictures stopped over the silence: {last_index:?}"
1639 );
1640 eprintln!("audio gap: clock at {now:.3}s of {duration:.3}s, frame {last_index:?}");
1641}
1642
1643/// The emptied timeline, end to end: the last clip deletes like any other, what
1644/// is left plays as black and silence with a duration of zero, it saves and
1645/// loads back as the project it is, and one undo brings the clip back. Silent
1646/// fixture, so this runs anywhere.
1647#[test]
1648fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1649 let path = asset("test_baseline.mp4");
1650 let mut session = open(&path);
1651 let whole = session.timeline_duration();
1652 assert!(whole > 0.0);
1653
1654 // The sole take goes -- picture and sound of it, on every lane at once.
1655 assert!(
1656 session.delete_clip(Lane::V1, 0),
1657 "the last clip deletes like any other"
1658 );
1659 assert!(session.is_empty(), "and the timeline is empty");
1660 assert_eq!(session.timeline_duration(), 0.0);
1661 assert!(session.clip_spans().is_empty());
1662 assert_eq!(session.lanes().len(), 2, "the lanes are still there");
1663
1664 // It scrubs: every seek lands at zero and shows black rather than the
1665 // picture of the clip that was deleted.
1666 for t in [0.0, -1.0, whole, 1e9] {
1667 session.seek(t);
1668 assert_eq!(session.now(), 0.0, "seek to {t} on an empty timeline");
1669 let deadline = Instant::now() + Duration::from_secs(5);
1670 let mut black = None;
1671 while black.is_none() && Instant::now() < deadline {
1672 session.tick();
1673 black = session.try_frame();
1674 sleep(Duration::from_millis(4));
1675 }
1676 let frame = black.expect("an empty timeline shows one black frame");
1677 assert_eq!(frame.index, 0);
1678 assert!(
1679 frame.bgra.as_chunks::<4>().0.iter().all(|p| p[..3] == [0, 0, 0]),
1680 "and it is black"
1681 );
1682 }
1683 // It plays: nothing to show, so it is at its end at once, and nothing hangs.
1684 session.play();
1685 let mut last_index = None;
1686 run_for(&mut session, &mut last_index, Duration::from_millis(200));
1687 assert!(session.is_eos(), "an empty timeline is played out at once");
1688 session.pause();
1689
1690 // Exporting nothing is a refusal in words, not a file of no frames -- and
1691 // in the *same* words whichever format asked, because the fence sits in
1692 // `export::start` ahead of the format, not in the mp4 path alone.
1693 for format in [Format::Mp4, Format::Wav, Format::Flac] {
1694 let dir = Scratch::dir("ve_nothing");
1695 let out = dir.join("ve_nothing");
1696 let handle = session.export_to_with(
1697 &out,
1698 &ExportSettings {
1699 format,
1700 ..ExportSettings::default()
1701 },
1702 );
1703 let deadline = Instant::now() + Duration::from_secs(10);
1704 let err = loop {
1705 if let Some(result) = handle.result() {
1706 break result.expect_err("an empty timeline cannot be exported");
1707 }
1708 assert!(Instant::now() < deadline, "{format:?} export never settled");
1709 sleep(Duration::from_millis(10));
1710 };
1711 assert_eq!(
1712 err.to_string(),
1713 "the timeline is empty: there is nothing to export",
1714 "{format:?}"
1715 );
1716 assert!(!out.exists(), "{format:?} wrote a file anyway");
1717 }
1718
1719 // It saves and loads back -- still a project, still two lanes, and still
1720 // naming the file whose frame rate the timeline counts in.
1721 let dir = Scratch::dir("ve_empty");
1722 let project = dir.join("empty.edith");
1723 session
1724 .save_project(&project)
1725 .expect("save an empty timeline");
1726 let loaded = PlaybackSession::open_project(&project).expect("load it back");
1727 assert!(loaded.is_empty(), "what came back is the empty timeline");
1728 assert_eq!(loaded.lanes().len(), 2);
1729 assert_eq!(loaded.sources().len(), 1, "source 0 is kept, orphan or not");
1730 assert_eq!(loaded.meta().frame_rate, session.meta().frame_rate);
1731 drop(loaded);
1732 let _ = std::fs::remove_dir_all(&dir);
1733
1734 // ...and one gesture is one undo: the take comes back whole.
1735 assert!(session.undo(), "the delete undoes");
1736 assert!(!session.is_empty());
1737 assert!((session.timeline_duration() - whole).abs() < 1e-9);
1738 assert_eq!(session.clip_spans().len(), 1);
1739}
1740
1741/// The session half of the late-frame policy: a *watched* session still lands
1742/// exactly on the frame a seek asked for. The floor the worker drops against is
1743/// the playhead mapped back into the file own frames, and a floor even one
1744/// frame ahead of the landing would eat the very picture the seek exists to
1745/// show ([`PlaybackSession::drop_late_pictures`]).
1746#[test]
1747fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() {
1748 let mut session = open(asset("test_baseline.mp4"));
1749 session.drop_late_pictures(true);
1750 let fps = session.meta().frame_rate;
1751 session.seek(3.0);
1752 assert_eq!(
1753 next_index(&mut session, "seek(3.0) on a watched session"),
1754 (3.0 * fps) as u32,
1755 "the landing frame was dropped as late"
1756 );
1757 // ...and again backwards: a floor left where the last span ended would drop
1758 // every picture of a seek that went back.
1759 session.seek(1.0);
1760 assert_eq!(
1761 next_index(&mut session, "seek(1.0) on a watched session"),
1762 (1.0 * fps) as u32
1763 );
1764}
1765
1766/// The pixels a *reused* decoder hands back are the pixels a fresh one does.
1767/// One session takes three seeks -- forwards, backwards, forwards again -- and
1768/// the worker survives all of them (`Worker::reseek`: the file stays open, the
1769/// hardware session is repositioned rather than reopened), so a decoder left
1770/// holding one span references while another span is asked for would show here
1771/// as a smear and nowhere else. The reference is the file-level API, which
1772/// opens a decoder of its own per frame.
1773#[test]
1774fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() {
1775 let path = asset("test_baseline.mp4");
1776 let mut session = open(&path);
1777 let fps = session.meta().frame_rate;
1778 // Small targets on purpose: the fixture's only sync sample is frame 0, so
1779 // every one of these decodes from the start of the file and a debug-build
1780 // software decoder is what runs the suite.
1781 for target in [20u32, 5, 35] {
1782 session.seek(f64::from(target) / fps);
1783 let frame = next_frame(&mut session, "a seek onto a worker already open");
1784 assert_eq!(frame.index, target, "the seek landed elsewhere");
1785 assert!(
1786 frame.bgra == source_frame(&path, target),
1787 "frame {target} off the reused decoder is not the picture a fresh one decodes"
1788 );
1789 }
1790}
1791
1792/// What the drop policy must never do: thin a picture the decoder was keeping up
1793/// with. `pump`'s own contiguity assert covers every *pull* consumer above;
1794/// nothing there bounds what a **watched** session delivers, and a one-in-N
1795/// regression inside the worker would pass the whole suite otherwise.
1796///
1797/// The fixture is the smallest one here (320x180) so the question can be asked
1798/// on a debug build at the file's own rate -- no retime, because a retimed
1799/// timeline legitimately shows only every n-th source frame and the sharp half
1800/// of this test is that the indices arrive one at a time. A box too slow even
1801/// for this says so and stops: thinning the picture there is the policy working
1802/// (`LATE_RUN`), not a regression.
1803#[test]
1804fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() {
1805 let path = asset("test_speed_sync.mp4");
1806
1807 // What this box decodes, flat out, with nothing dropped: frames per second.
1808 let mut measure = open(&path);
1809 let fps = measure.meta().frame_rate;
1810 measure.play();
1811 let mut decoded = 0u32;
1812 let taken = Instant::now();
1813 while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() {
1814 measure.tick();
1815 while measure.try_frame().is_some() {
1816 decoded += 1;
1817 }
1818 sleep(Duration::from_millis(2));
1819 }
1820 let capable = f64::from(decoded) / taken.elapsed().as_secs_f64();
1821 drop(measure);
1822 eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}");
1823 if capable < fps * 1.2 {
1824 eprintln!("SKIP: too slow to ask the question at all");
1825 return;
1826 }
1827
1828 // Watched, playing at its own rate, drained like a front-end that keeps up:
1829 // every picture is due when it arrives and none of them may be dropped.
1830 let mut session = open(&path);
1831 session.drop_late_pictures(true);
1832 session.play();
1833 let mut delivered = 0u32;
1834 let mut last: Option<u32> = None;
1835 let watched = Instant::now();
1836 while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() {
1837 session.tick();
1838 while let Some(frame) = session.try_frame() {
1839 delivered += 1;
1840 if let Some(previous) = last {
1841 assert_eq!(
1842 frame.index,
1843 previous + 1,
1844 "a picture was dropped while the decoder was keeping up"
1845 );
1846 }
1847 last = Some(frame.index);
1848 }
1849 sleep(Duration::from_millis(2));
1850 }
1851 // Frames the clock went over, which is what the timeline owed the screen.
1852 let passed = session.now() * fps;
1853 let density = f64::from(delivered) / passed.max(1.0);
1854 eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock");
1855 assert!(
1856 density >= 0.9,
1857 "the worker thinned a picture it was keeping up with: {delivered} of \
1858 {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps"
1859 );
1860}
1861
1862/// The decode-ahead a **freshly opened** file gets. Every session opens its first
1863/// worker pass-through -- a file just opened *is* the project resolution -- and
1864/// asking a pass-through canvas how deep to queue answers 2, the bound this
1865/// engine had before there was any decode-ahead: the whole file would then play
1866/// at that depth until the first seek built a real canvas. The depth is taken
1867/// from the stream instead (`scale::queue_depth`), and this is where that is
1868/// visible from outside: a paused session left alone fills its queue, and the
1869/// burst that comes off it is the depth plus the picture in the worker's hand.
1870///
1871/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so
1872/// the burst is 17 and the regression it guards against is a burst of 3.
1873#[test]
1874fn a_freshly_opened_file_queues_more_than_two_pictures() {
1875 let mut session = open(asset("test_baseline.mp4"));
1876 // Paused throughout: no seek, no play, nothing that would build a canvas.
1877 // The best of three attempts, because filling the queue is the decoder's own
1878 // work and this box shares itself with whatever else is running.
1879 let mut burst = 0;
1880 for _ in 0..10 {
1881 if burst > 8 {
1882 break;
1883 }
1884 sleep(Duration::from_millis(1500));
1885 let mut n = 0;
1886 while session.try_frame().is_some() {
1887 n += 1;
1888 }
1889 burst = burst.max(n);
1890 }
1891 eprintln!("burst off a freshly opened file: {burst} pictures");
1892 assert!(
1893 burst > 8,
1894 "a freshly opened file queued {burst} pictures: the first worker is \
1895 still sizing its queue from a pass-through canvas"
1896 );
1897
1898 // ...and the same worker still answers. Four and a half seconds parked is
1899 // well past the idle mark at which it closes its hardware session
1900 // (`decode`'s `IDLE`), so this is the seek that has to reopen one lazily --
1901 // the one path that would have gone quiet if closing it left the worker
1902 // holding a decoder it could no longer use.
1903 let fps = session.meta().frame_rate;
1904 session.seek(2.0);
1905 assert_eq!(
1906 next_index(&mut session, "a seek after the worker went idle"),
1907 (2.0 * fps) as u32,
1908 "the worker did not come back from its idle park"
1909 );
1910}