forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

lanes.rs655 lines, 25.2 KiBHistoryRawDownload
1//! N lanes, composited: what a timeline with a `V2` over its `V1` and an `A2`
2//! over its `A1` plays, and that an export of it is the same thing.
3//!
4//! The fixtures are the two video assets, which differ picture for picture, so
5//! "which lane is showing" is answered by comparing the decoded frame against
6//! each source rather than by trusting the edit list.
7//!
8//! ```text
9//! cargo test -p engine --release --test lanes -- --nocapture
10//! ```
11
12use std::path::{Path, PathBuf};
13use std::sync::Once;
14use std::time::{Duration, Instant};
15
16use engine::export::{ExportSettings, Format};
17use engine::project::{Clip, Lane, LaneKind, Source, Speed};
18use engine::scale::FitPolicy;
19use engine::scratch::Scratch;
20use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
21
22const FPS: f64 = 30.0;
23/// `test_av.mp4` is 150 frames, `test_av2.mp4` 120; the top lane covers the
24/// middle third of the first.
25const TOTAL: u32 = 150;
26const TOP_IN: u32 = 50;
27const TOP_OUT: u32 = 100;
28
29fn asset(name: &str) -> PathBuf {
30 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
31 .join("../../assets")
32 .join(name)
33}
34
35/// Software on both halves, so this suite proves the composite on any machine
36/// rather than whatever the local VA-API driver does.
37fn pin_software() {
38 static PIN: Once = Once::new();
39 PIN.call_once(|| {
40 engine::envcfg::set("VE_SW", "1");
41 engine::envcfg::set("VE_SW_ENC", "1");
42 });
43}
44
45/// Its own directory, gone with the value: two suites at once must not write
46/// each other's files, and nothing may outlive the test that wrote it.
47fn out_path(name: &str, ext: &str) -> Scratch {
48 Scratch::file(&format!("ve_lanes_{name}"), ext)
49}
50
51/// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle
52/// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`.
53/// Exactly the file a user would write by hand, parsed by the real loader.
54///
55/// `name` is the caller's own, because [`out_path`] is unique per *run* and not
56/// per test: two tests sharing one name run in parallel over one file, and the
57/// first to finish deletes it out from under the second -- which then fails on
58/// a file that is simply not there any more.
59fn three_lane_file(name: &str) -> Scratch {
60 let path = out_path(name, "edith");
61 // `source <audio stream> <path>`: the number is which audio track of the
62 // file plays, not the source index -- both of these are on their first.
63 let text = format!(
64 "edith 4\nplayhead 0\nsource 0 {}\nsource 0 {}\n\
65 video 1 0 0 {TOTAL} 0 -\naudio 1 0 0 {TOTAL} 0 -\n\
66 video 2 {TOP_IN} 0 {} 1 -\n",
67 asset("test_av.mp4").display(),
68 asset("test_av2.mp4").display(),
69 TOP_OUT - TOP_IN,
70 );
71 std::fs::write(&path, text).expect("write the project file");
72 path
73}
74
75/// One frame of `path` by absolute index, BGRA.
76fn frame_at(path: &Path, index: u32) -> Vec<u8> {
77 let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source");
78 frames.recv().expect("frame present").bgra
79}
80
81fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
82 assert_eq!(a.len(), b.len(), "frame sizes differ");
83 a.iter()
84 .zip(b)
85 .map(|(x, y)| f64::from(x.abs_diff(*y)))
86 .sum::<f64>()
87 / a.len() as f64
88}
89
90/// Which of the two sources `frame` came from, by picture: the near one wins,
91/// and the assertion is that the other is nowhere near.
92fn assert_from(frame: &[u8], source: &str, source_frame: u32, timeline: u32) {
93 let other = match source {
94 "test_av.mp4" => "test_av2.mp4",
95 _ => "test_av.mp4",
96 };
97 let mine = mean_abs_diff(frame, &frame_at(&asset(source), source_frame));
98 let theirs = mean_abs_diff(frame, &frame_at(&asset(other), source_frame));
99 println!("timeline {timeline}: {source} {source_frame} diff {mine:.2}, {other} {theirs:.2}");
100 assert!(
101 mine < 6.0,
102 "timeline frame {timeline} drifted by {mine:.2} from {source} frame {source_frame}"
103 );
104 assert!(
105 theirs > 4.0 * mine.max(0.5),
106 "the two sources are too alike at frame {source_frame} for this test to mean anything"
107 );
108}
109
110fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
111 let started = Instant::now();
112 while !handle.is_finished() {
113 assert!(
114 started.elapsed() < limit,
115 "export did not finish in {limit:?}"
116 );
117 std::thread::sleep(Duration::from_millis(20));
118 }
119 handle.result().expect("a finished export has an outcome")
120}
121
122/// Plays the session up to `timeline` and hands back the frame shown there.
123/// Times it, because a lane change costs exactly one decoder reopen -- the
124/// composite is one span list, so N video lanes never mean N decoders.
125fn frame_of(session: &mut PlaybackSession, timeline: u32) -> Vec<u8> {
126 let started = Instant::now();
127 session.seek(f64::from(timeline) / FPS);
128 let deadline = Instant::now() + Duration::from_secs(20);
129 loop {
130 session.tick();
131 if let Some(frame) = session.try_frame() {
132 assert_eq!(frame.index, timeline, "a seek shows the frame it landed on");
133 println!(
134 "frame {timeline} ready {:.0} ms after the seek",
135 started.elapsed().as_secs_f64() * 1000.0
136 );
137 return frame.bgra;
138 }
139 assert!(Instant::now() < deadline, "no frame at timeline {timeline}");
140 std::thread::sleep(Duration::from_millis(5));
141 }
142}
143
144/// The slice, from the front door: a hand-written project with a second video
145/// lane opens and *plays* the top lane where it has a clip, the one under it
146/// everywhere else.
147#[test]
148fn playback_shows_the_topmost_video_lane() {
149 pin_software();
150 let project = three_lane_file("playback");
151 let mut session = PlaybackSession::open_project(&project).expect("open the project");
152 session.set_gain(0.0);
153 assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS);
154
155 // Before the top lane starts, inside it, and after it ends.
156 let head = frame_of(&mut session, 10);
157 assert_from(&head, "test_av.mp4", 10, 10);
158 let over = frame_of(&mut session, TOP_IN + 10);
159 assert_from(&over, "test_av2.mp4", 10, TOP_IN + 10);
160 let tail = frame_of(&mut session, TOP_OUT + 10);
161 assert_from(&tail, "test_av.mp4", TOP_OUT + 10, TOP_OUT + 10);
162
163 std::fs::remove_file(&project).unwrap();
164}
165
166/// Export is playback: the same project written out and decoded back shows the
167/// same lane at the same frame.
168#[test]
169fn export_writes_the_same_composite() {
170 pin_software();
171 let file = three_lane_file("export");
172 let session = PlaybackSession::open_project(&file).expect("open the project");
173 let out = out_path("composite", "mp4");
174
175 let started = Instant::now();
176 let handle = session.export_to(&out);
177 wait(&handle, Duration::from_secs(300)).expect("export");
178 println!(
179 "composite export: {TOTAL} frames in {:.2} s",
180 started.elapsed().as_secs_f64()
181 );
182
183 let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
184 assert_eq!(meta.frame_count, TOTAL, "timeline frames written");
185 let (_, frames) = DecodeSession::open(&out).expect("decode the export");
186 let frames: Vec<Vec<u8>> = frames.into_iter().map(|f| f.bgra).collect();
187 assert_eq!(frames.len() as u32, TOTAL);
188 assert_from(&frames[10], "test_av.mp4", 10, 10);
189 assert_from(
190 &frames[(TOP_IN + 10) as usize],
191 "test_av2.mp4",
192 10,
193 TOP_IN + 10,
194 );
195 assert_from(
196 &frames[(TOP_OUT + 10) as usize],
197 "test_av.mp4",
198 TOP_OUT + 10,
199 TOP_OUT + 10,
200 );
201
202 std::fs::remove_file(&file).unwrap();
203 std::fs::remove_file(&out).unwrap();
204}
205
206/// Every sample of `path`'s first audio stream, interleaved -- what the export
207/// wrote, read back through the engine's own decoder.
208fn decoded_audio(path: &Path) -> Vec<f32> {
209 let sources = [(path.to_path_buf(), 0)];
210 let (_, chunks) =
211 engine::AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
212 .expect("open the audio")
213 .expect("there is an audio track");
214 chunks.into_iter().flat_map(|c| c.samples).collect()
215}
216
217fn rms(samples: &[f32]) -> f64 {
218 assert!(!samples.is_empty(), "no samples to measure");
219 (samples
220 .iter()
221 .map(|s| f64::from(*s) * f64::from(*s))
222 .sum::<f64>()
223 / samples.len() as f64)
224 .sqrt()
225}
226
227/// The sound need not be on `A1`: a project that leaves `A1` empty and places
228/// everything on `A2` is still *one* audio lane, so the mp4 export copies it
229/// rather than refusing -- and rather than writing a file with no audio track
230/// at all, which is what pinning the copy to `A1` did (verifier's repro: the
231/// export succeeded, ffprobe showed video only, and nobody would notice until
232/// they played it).
233#[test]
234fn the_mp4_copy_follows_the_lane_that_holds_the_sound() {
235 pin_software();
236 let source = asset("test_av.mp4");
237 let clip = Clip {
238 speed_keys: Vec::new(),
239 reversed: false,
240 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
241 angle: Default::default(),
242 fade_in: 0,
243 transition_out: 0,
244 transition_kind: Default::default(),
245 visualizer: 0,
246 viz_paint: 0,
247 gain_db: 0.0,
248 gain_keys: Vec::new(),
249 pan: 0,
250 pitch: 0.0,
251 transform_keys: Vec::new(),
252 opacity_keys: Vec::new(),
253 color_keys: Vec::new(),
254 effects: Vec::new(),
255 fade_out: 0,
256 start: 0,
257 in_frame: 0,
258 out_frame: TOTAL,
259 source: 0,
260 link: None,
261 eq: None,
262 color: None,
263 transform: None,
264 fit: FitPolicy::default(),
265 speed: Speed::NORMAL,
266 };
267 let project = Project::from_parts(
268 vec![Source::new(&source, 0)],
269 vec![
270 (LaneKind::Video, vec![clip.clone()]),
271 (LaneKind::Audio, Vec::new()),
272 (LaneKind::Audio, vec![clip.clone()]),
273 ],
274 vec![],
275 vec![],
276 vec![],
277 )
278 .expect("valid parts");
279 assert_eq!(
280 project.audio_segments_from(0, FPS).len(),
281 1,
282 "one lane holds sound, so this is not a mix"
283 );
284
285 let out = out_path("a2_only", "mp4");
286 let (meta, _) = engine::demux::Demuxer::open(&source).unwrap();
287 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
288 wait(&handle, Duration::from_secs(300)).expect("export the A2-only timeline");
289
290 let written = decoded_audio(&out);
291 let played = decoded_audio(&source);
292 println!(
293 "A2-only export: {} samples rms {:.4}, source {} samples rms {:.4}",
294 written.len(),
295 rms(&written),
296 played.len(),
297 rms(&played)
298 );
299 assert!(rms(&written) > 0.001, "the export has to carry the sound");
300 assert!(
301 (rms(&written) / rms(&played) - 1.0).abs() < 0.05,
302 "the exported audio is not the lane's content"
303 );
304 std::fs::remove_file(&out).unwrap();
305}
306
307/// `A1` and `A2` playing the *same* source range at the same place: over that
308/// stretch the mix is that audio twice over, so it measures at exactly double
309/// the level the one-lane export of the same timeline has there -- and outside
310/// it, at the same level. The comparison is against the same window of the same
311/// content, because the fixture's own level moves and comparing two *stretches*
312/// would measure the fixture rather than the mixer.
313#[test]
314fn two_audio_lanes_are_summed() {
315 pin_software();
316 let one_lane = Project::single(asset("test_av.mp4"), TOTAL);
317 let mut project = one_lane.clone();
318 let doubled = Clip {
319 speed_keys: Vec::new(),
320 reversed: false,
321 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
322 angle: Default::default(),
323 fade_in: 0,
324 fade_out: 0,
325 transition_out: 0,
326 transition_kind: Default::default(),
327 visualizer: 0,
328 viz_paint: 0,
329 gain_db: 0.0,
330 gain_keys: Vec::new(),
331 pan: 0,
332 pitch: 0.0,
333 transform_keys: Vec::new(),
334 opacity_keys: Vec::new(),
335 color_keys: Vec::new(),
336 effects: Vec::new(),
337 start: TOP_IN,
338 in_frame: TOP_IN,
339 out_frame: TOP_OUT,
340 source: 0,
341 link: None,
342 eq: None,
343 color: None,
344 transform: None,
345 fit: FitPolicy::default(),
346 speed: Speed::NORMAL,
347 };
348 let a2 = project.add_lane(LaneKind::Audio);
349 assert!(project.place(a2, TOP_IN, doubled), "place the second lane");
350 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
351 assert_eq!(lanes.len(), 3, "V1, A1 and the new A2");
352 let project = Project::from_parts(sources, lanes, eq, color, transform).expect("valid parts");
353
354 let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap();
355 let wav = |name: &str, project: Project| {
356 let out = out_path(name, "wav");
357 let settings = ExportSettings {
358 format: Format::Wav,
359 ..Default::default()
360 };
361 let handle = engine::export::start(project, meta, &out, &settings, None);
362 wait(&handle, Duration::from_secs(120)).expect("wav export");
363 let mut reader = ec_riff::WavReader::open(&out).expect("reopen the wav");
364 let spec = reader.spec();
365 let samples: Vec<f64> = reader
366 .read_all_i32()
367 .expect("samples")
368 .into_iter()
369 .map(f64::from)
370 .collect();
371 std::fs::remove_file(&out).unwrap();
372 (spec, samples)
373 };
374 let (spec, plain) = wav("one_lane", one_lane);
375 let (_, mixed) = wav("mixed", project.clone());
376 assert_eq!(plain.len(), mixed.len(), "both are the timeline's length");
377
378 let rms = |samples: &[f64], from: u32, to: u32| {
379 let per = f64::from(spec.sample_rate) / FPS * f64::from(spec.channels);
380 let (a, b) = (
381 (f64::from(from) * per) as usize,
382 (f64::from(to) * per) as usize,
383 );
384 let window = &samples[a..b.min(samples.len())];
385 (window.iter().map(|s| s * s).sum::<f64>() / window.len() as f64).sqrt()
386 };
387 // A margin inside each region: a segment boundary lands on a packet edge,
388 // and this measures the middle of a stretch, not the seam.
389 let (over_one, over_two) = (
390 rms(&plain, TOP_IN + 5, TOP_OUT - 5),
391 rms(&mixed, TOP_IN + 5, TOP_OUT - 5),
392 );
393 let (out_one, out_two) = (
394 rms(&plain, TOP_OUT + 5, TOTAL - 5),
395 rms(&mixed, TOP_OUT + 5, TOTAL - 5),
396 );
397 println!("rms under A2: one lane {over_one:.1}, mixed {over_two:.1}");
398 println!("rms past A2: one lane {out_one:.1}, mixed {out_two:.1}");
399 assert!(over_one > 100.0, "the fixture has to be audible to measure");
400 assert!(
401 (over_two / over_one - 2.0).abs() < 0.05,
402 "the overlap is {:.3}x one lane, not 2x",
403 over_two / over_one
404 );
405 assert!(
406 (out_two / out_one - 1.0).abs() < 0.05,
407 "past the second lane the level is back to one lane's ({:.3}x)",
408 out_two / out_one
409 );
410
411 // ...and the mp4 of the same timeline carries that very mix. It used to be
412 // a refusal by name -- the mp4 path *copies* AAC packets and a mix is not a
413 // copy -- and a refusal is what a file missing half its sound deserves;
414 // this decodes both lanes and encodes the sum instead (`export::copy_audio`
415 // routes to `encode_audio`), which is the same mix the WAV above measured.
416 let out = out_path("mixed", "mp4");
417 let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
418 wait(&handle, Duration::from_secs(180)).expect("an mp4 of two audio lanes");
419 let (audio, chunks) = engine::AudioSession::open(&out)
420 .expect("reopen the export")
421 .expect("it has an audio track");
422 let coded: Vec<f64> = chunks
423 .into_iter()
424 .flat_map(|c| c.samples)
425 .map(|s| f64::from(s) * f64::from(i16::MAX))
426 .collect();
427 let per = f64::from(audio.sample_rate) / FPS * f64::from(audio.channels);
428 let window = |from: u32, to: u32| {
429 let (a, b) = (
430 (f64::from(from) * per) as usize,
431 (f64::from(to) * per) as usize,
432 );
433 let w = &coded[a.min(coded.len())..b.min(coded.len())];
434 (w.iter().map(|s| s * s).sum::<f64>() / w.len().max(1) as f64).sqrt()
435 };
436 let (coded_over, coded_out) = (
437 window(TOP_IN + 5, TOP_OUT - 5),
438 window(TOP_OUT + 5, TOTAL - 5),
439 );
440 println!("mp4 rms: under A2 {coded_over:.1}, past it {coded_out:.1}");
441 // Against the WAV of the same timeline, not against a figure: one lossy
442 // generation moves the level by a fraction of a dB and nothing here is
443 // measuring the encoder.
444 assert!(
445 (coded_over / over_two - 1.0).abs() < 0.1,
446 "the mp4's overlap is {coded_over:.1} against the mix's {over_two:.1}"
447 );
448 assert!(
449 (coded_out / out_two - 1.0).abs() < 0.1,
450 "past A2 the mp4 is {coded_out:.1} against the mix's {out_two:.1}"
451 );
452 std::fs::remove_file(&out).unwrap();
453}
454
455/// A project with one lane of each kind is what it always was: the composite of
456/// a single video lane is that lane, and its audio is one un-mixed stream.
457#[test]
458fn one_lane_projects_are_untouched() {
459 let project = Project::single(asset("test_av.mp4"), TOTAL);
460 assert_eq!(
461 project.composite_spans_from(0),
462 project.spans_from(engine::project::Lane::V1, 0)
463 );
464 let lists = project.audio_segments_from(0, FPS);
465 assert_eq!(lists, vec![project.segments_from(0, FPS)]);
466 assert_eq!(project.sources(), [Source::new(asset("test_av.mp4"), 0)]);
467}
468
469/// The burden a third lane kind carries: a subtitle lane is a lane like the
470/// others everywhere a *lane* is the subject -- it is added, labelled, ordered,
471/// snapshotted and removed by one code path -- and every path that is about
472/// media refuses it, by the bounds check it already had or by name.
473///
474/// One test rather than a dozen because the claim is one claim: nothing about
475/// a caption was threaded through the media machinery.
476#[test]
477fn a_subtitle_lane_is_a_peer_and_every_media_path_refuses_it() {
478 use engine::project::{Edge, SubClip};
479
480 let mut project = Project::single(asset("test_av.mp4"), TOTAL);
481 let subs = engine::subtitle::open(&asset("test_subs.srt"), None);
482 assert!(project.add_subtitles(&subs), "the palette takes the track");
483 let s1 = project.add_lane(LaneKind::Subtitle);
484 assert_eq!(project.lanes(), [Lane::V1, Lane::A1, s1], "a peer in the stack");
485 assert_eq!(s1.label(), "S1");
486
487 let caption = SubClip {
488 start: 0,
489 frames: 60,
490 track: 0,
491 in_us: 0,
492 out_us: 2_000_000,
493 link: None,
494 };
495 project.place_sub(s1, 0, caption).expect("a caption goes down");
496
497 // Nothing about the *picture* or the *mix* learned about it.
498 assert_eq!(
499 project.composite_spans_from(0),
500 project.spans_from(Lane::V1, 0),
501 "the composite is still V1 alone: a subtitle lane is not a video lane"
502 );
503 assert_eq!(project.composite_clip_at(0), Some((Lane::V1, 0)));
504 assert_eq!(project.audio_lanes(), [Lane::A1], "and the mix is A1 alone");
505 assert_eq!(project.audio_gains().len(), 1);
506 assert_eq!(
507 project.lane_gains().len(),
508 3,
509 "a save's gain list holds one entry per lane, in step with its lane list -- \
510 this one's at the 0.0 a subtitle lane is pinned to"
511 );
512
513 // The clip-shaped calls: the lane holds no `Clip`, so each refuses by the
514 // check it always made, and none of them costs an undo step.
515 assert!(project.lane(s1).is_empty(), "there is no clip on a subtitle lane");
516 assert!(!project.set_lane_gain_db(s1, -6.0), "words have no loudness");
517 assert_eq!(project.lane_gain_db(s1), 0.0);
518 assert!(!project.set_eq(s1, 0, None), "and no equalizer");
519 assert!(!project.set_color(s1, 0, None), "and no colour grade");
520 assert!(!project.set_fit(s1, 0, engine::scale::FitPolicy::Fill), "and no fit");
521 let err = project
522 .set_speed(s1, 0, Speed::from_permille(2000))
523 .expect_err("and no speed");
524 assert!(err.to_string().contains("there is no clip 0 on S1"), "{err}");
525 assert!(!project.trim(s1, 0, Edge::End, 10, &[TOTAL]), "nothing to trim");
526 assert!(!project.lift(s1, 0), "nothing to lift");
527 assert!(!project.delete_in(s1, 0), "nothing to delete");
528
529 // ...and the three doors that could still have put a picture on one.
530 let clip = project.lane(Lane::V1).first().expect("V1 holds the film").clone();
531 assert!(!project.place(s1, 0, clip.clone()), "a picture may not be placed on it");
532 assert!(!project.place_take(s1, 0, clip.clone()), "nor a whole take");
533 assert!(!project.move_clip(Lane::V1, 0, s1, 0), "nor dragged onto it");
534 project.append_clip(0, 30);
535 assert!(
536 project.lane(s1).is_empty(),
537 "an import lands on the media lanes and skips this one"
538 );
539 assert!(project.undo(), "the import is one step");
540 let refused = Project::from_parts(
541 vec![Source::new(asset("test_av.mp4"), 0)],
542 vec![(LaneKind::Subtitle, vec![clip.clone()])],
543 Vec::new(),
544 Vec::new(),
545 Vec::new(),
546 )
547 .expect_err("a file may not name one either");
548 assert!(
549 refused.to_string().contains("S1 is a subtitle track"),
550 "the refusal says which lane and why: {refused}"
551 );
552
553 // The lane's own life cycle, which is the machinery it *does* use.
554 let held = project.remove_lane(s1).expect_err("it still holds a caption");
555 assert!(
556 held.to_string().contains("at frame 0")
557 && held.to_string().contains("drag them to another track"),
558 "the refusal names the caption and the way out: {held}"
559 );
560 assert!(project.lift_sub(s1, 0), "the caption comes off");
561 project.remove_lane(s1).expect("and then so does the lane");
562 assert_eq!(project.lanes(), [Lane::V1, Lane::A1], "the last one may go");
563 assert!(project.undo() && project.undo(), "both steps walk back");
564 assert_eq!(project.sub_lane(s1), [caption], "caption and lane restored");
565}
566
567/// A paste inserts media, the words keep their clock; co-travel is what a
568/// group is for. The rippling insert used to open room on the subtitle lanes
569/// too -- splitting the caption it landed inside and sliding the tail behind
570/// the picture -- so the hand asked for an add and got a cut it never made.
571/// What goes down at frame 20 is the paste's business; the caption stays
572/// byte for byte the placement it was given.
573#[test]
574fn a_paste_never_touches_the_captions() {
575 use engine::project::SubClip;
576
577 let mut project = Project::single(asset("test_av.mp4"), TOTAL);
578 project.add_subtitles(&engine::subtitle::open(&asset("test_subs.srt"), None));
579 let s1 = project.add_lane(LaneKind::Subtitle);
580 project
581 .place_sub(
582 s1,
583 0,
584 SubClip {
585 start: 0,
586 frames: 60,
587 track: 0,
588 in_us: 0,
589 out_us: 2_000_000,
590 link: None,
591 },
592 )
593 .expect("a caption over the first two seconds");
594 let before = project.sub_lane(s1).to_vec();
595
596 let clip = project.lane(Lane::V1).first().expect("V1 holds the film").clone();
597 let pasted = Clip {
598 fade_in: 0,
599 fade_out: 0,
600 out_frame: 30,
601 ..clip
602 };
603 assert!(project.paste(20, pasted), "thirty frames go in at frame 20");
604 assert_eq!(project.sub_lane(s1), &before[..], "the caption keeps its clock");
605 assert_eq!(project.sub_lane(s1).len(), 1, "and uncut");
606 assert_eq!(
607 project.lane(Lane::V1).len(),
608 3,
609 "the media lanes took the split, not the words"
610 );
611 assert!(project.undo(), "and the paste is one step for the lot");
612 assert_eq!(project.sub_lane(s1), &before[..], "the caption never noticed");
613}
614
615/// One edit, by name, on a fresh session of `test_av.mp4`. Every one is a
616/// single history step; the depth it moves by is what this test pins down.
617fn edit_by_name(s: &mut PlaybackSession, name: &str) -> bool {
618 match name {
619 "cut_at" => s.cut_at(2.0),
620 "move_clip_to" => s.move_clip_to(Lane::V1, 0, Lane::V1, 150),
621 "trim_clip" => s.trim_clip(Lane::V1, 0, engine::project::Edge::End, 60),
622 "delete_clip" => s.delete_clip(Lane::V1, 0),
623 "set_fade_in" => s.set_fade_in(Lane::V1, 0, 10),
624 "set_lane_gain_db" => s.set_lane_gain_db(Lane::A1, -3.0),
625 other => panic!("no edit named {other}"),
626 }
627}
628
629#[test]
630fn undo_depth_counts_one_step_per_edit() {
631 let mut counts = Vec::new();
632 for name in [
633 "cut_at",
634 "move_clip_to",
635 "trim_clip",
636 "delete_clip",
637 "set_fade_in",
638 "set_lane_gain_db",
639 ] {
640 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open");
641 s.set_gain(0.0);
642 assert_eq!((s.undo_depth(), s.redo_depth()), (0, 0), "{name}: fresh");
643 let before = s.undo_depth();
644 assert!(edit_by_name(&mut s, name), "{name} applied");
645 let pushed = s.undo_depth() - before;
646 counts.push((name, pushed));
647 assert_eq!(pushed, 1, "{name} pushes exactly one snapshot");
648 // An undo moves that one step onto the redo side, and a redo brings it back.
649 assert!(s.undo());
650 assert_eq!((s.undo_depth(), s.redo_depth()), (0, 1), "{name}: undone");
651 assert!(s.redo());
652 assert_eq!((s.undo_depth(), s.redo_depth()), (1, 0), "{name}: redone");
653 }
654 eprintln!("undo snapshots per edit: {counts:?}");
655}