forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

project.rs1571 lines, 60.9 KiBHistoryRawDownload
1//! Edit list: two lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds a video lane and an audio lane. Each lane is a list of
4//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
5//! *source* frames it plays, which file it plays it from, and -- the whole model
6//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
7//! offset rather than queued end to end, so:
8//!
9//! * a **gap** is not an object, it is the absence of a placement. Nothing has
10//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
11//! a hole cannot disagree with its neighbours about how long it is;
12//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
13//! splice of the list;
14//! * the lanes are independent: deleting audio under a picture is one lane's
15//! business, and the picture does not shift.
16//!
17//! The price is one invariant this module enforces at every mutation and every
18//! constructor: within a lane, clips are **sorted by `start` and never overlap**
19//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
20//! walk over that order.
21//!
22//! Two frame spaces meet here and are never mixed: *source* frames index the
23//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
24//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
25//!
26//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
27//! same take and move together. [`Project::split`] cuts every lane at a timeline
28//! frame and hands the two sides two fresh ids; [`Project::regroup`] is its
29//! inverse and rejoins them.
30//!
31//! Editing is metadata only. [`Project::split`] changes no timeline->source
32//! mapping, so a running decoder stays correct across it; everything else does
33//! and the caller must reseek. Every successful edit snapshots both lanes, so
34//! [`Project::undo`] is an exact restore.
35//!
36//! A clip names its file by *index* into [`Project::sources`], which is
37//! append-only: an index handed out once stays valid forever, so a clip on the
38//! clipboard or inside an undo snapshot can never dangle. An index -- not an
39//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
40//! plain assignment.
41
42use std::path::{Path, PathBuf};
43
44/// A half-open `[in_frame, out_frame)` range of frames of source
45/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
46/// Never empty.
47#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub struct Clip {
49 /// Timeline frame the clip's first frame is shown at. Meaningless on a
50 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
51 /// with where the caller asked for.
52 pub start: u32,
53 pub in_frame: u32,
54 pub out_frame: u32,
55 /// Index into [`Project::sources`].
56 pub source: usize,
57 /// Group id: clips sharing one were split from the same take. `None` for a
58 /// clip that belongs to no group.
59 pub link: Option<u32>,
60}
61
62impl Clip {
63 /// Frame count; `>= 1` by the never-empty invariant.
64 pub fn len(&self) -> u32 {
65 self.out_frame - self.in_frame
66 }
67
68 /// One past the last timeline frame it covers.
69 pub fn end(&self) -> u32 {
70 self.start + self.len()
71 }
72}
73
74/// Which lane an operation acts on. The lanes are peers: no operation reads one
75/// to decide what to do to the other, except the grouped ones that say so.
76#[derive(Clone, Copy, PartialEq, Eq, Debug)]
77pub enum Lane {
78 Video,
79 Audio,
80}
81
82impl Lane {
83 pub const ALL: [Lane; 2] = [Lane::Video, Lane::Audio];
84
85 fn index(self) -> usize {
86 self as usize
87 }
88}
89
90/// What a lane holds over one stretch of the timeline: either a placed clip or
91/// a gap. Returned already trimmed to the position it was asked about, so a
92/// caller can hand `len` straight to a decoder (or to a black-frame generator).
93#[derive(Clone, Copy, PartialEq, Eq, Debug)]
94pub struct Span {
95 /// Timeline frame the span starts at.
96 pub start: u32,
97 /// Frames it covers; `>= 1`.
98 pub len: u32,
99 /// `(source index, first source frame)`, or `None` for a gap -- which the
100 /// engine renders as black frames and as silence.
101 pub from: Option<(usize, u32)>,
102}
103
104impl Span {
105 /// One past the last timeline frame it covers.
106 pub fn end(&self) -> u32 {
107 self.start + self.len
108 }
109}
110
111/// The edit list plus its undo history.
112#[derive(Clone, Debug)]
113pub struct Project {
114 /// Append-only: never popped, never reordered. See the module docs.
115 sources: Vec<PathBuf>,
116 /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.
117 lanes: [Vec<Clip>; 2],
118 /// Snapshots pushed *before* each successful edit; `undo` pops one.
119 history: Vec<[Vec<Clip>; 2]>,
120 /// Never rolled back by an undo: an id retired by an undone split must not
121 /// come back and group two clips that were never together.
122 next_link: u32,
123}
124
125impl Project {
126 /// One clip per lane covering the whole of `path`, the two grouped -- the
127 /// state of a freshly opened video, where the timeline is the source.
128 /// `frame_count` of 0 would break the never-empty invariant, so it is
129 /// clamped to one frame.
130 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
131 let clip = Clip {
132 start: 0,
133 in_frame: 0,
134 out_frame: frame_count.max(1),
135 source: 0,
136 link: Some(0),
137 };
138 Self {
139 sources: vec![canonical(path.as_ref())],
140 lanes: [vec![clip], vec![clip]],
141 history: Vec::new(),
142 next_link: 1,
143 }
144 }
145
146 /// A project rebuilt from a saved edit list -- the load half of
147 /// [`crate::edith`]. History is *not* saved, so [`Project::undo`] is
148 /// `false` until the first edit of the new session. This is the one door
149 /// untrusted parts come in through, so every invariant every other
150 /// constructor keeps is checked here, by name and in release: both lanes
151 /// empty, an empty clip, a clip naming a source that is not there, a clip
152 /// whose end overflows, a lane that is unsorted or self-overlapping, and
153 /// the grouping rules of [`Clip::link`] below.
154 pub fn from_parts(
155 sources: Vec<PathBuf>,
156 video: Vec<Clip>,
157 audio: Vec<Clip>,
158 ) -> crate::Result<Self> {
159 if video.is_empty() && audio.is_empty() {
160 return Err("both lanes are empty: that is not a project".into());
161 }
162 let lanes = [video, audio];
163 for (lane, name) in lanes.iter().zip(["video", "audio"]) {
164 for c in lane {
165 if c.out_frame <= c.in_frame {
166 return Err(format!(
167 "{name} clip at {} plays the empty range [{}, {})",
168 c.start, c.in_frame, c.out_frame
169 )
170 .into());
171 }
172 if c.source >= sources.len() {
173 return Err(format!(
174 "{name} clip at {} names source {} of {}",
175 c.start,
176 c.source,
177 sources.len()
178 )
179 .into());
180 }
181 if c.start.checked_add(c.len()).is_none() {
182 return Err(format!(
183 "{name} clip at {} runs past the last frame there is",
184 c.start
185 )
186 .into());
187 }
188 }
189 if !sorted_disjoint(lane) {
190 return Err(format!("the {name} lane is out of order or overlaps itself").into());
191 }
192 }
193 links_are_consistent(&lanes)?;
194 let next_link = lanes
195 .iter()
196 .flatten()
197 .filter_map(|c| c.link)
198 .max()
199 // Saturating so a crafted file cannot make the counter wrap: at the
200 // ceiling ids stop being fresh, which loses grouping, not memory.
201 .map_or(0, |m| m.saturating_add(1));
202 Ok(Self {
203 sources: sources.iter().map(|s| canonical(s)).collect(),
204 lanes,
205 history: Vec::new(),
206 next_link,
207 })
208 }
209
210 /// The video lane -- what an export renders and what a single-lane caller
211 /// still means by "the clips".
212 pub fn clips(&self) -> &[Clip] {
213 self.lane(Lane::Video)
214 }
215
216 pub fn lane(&self, lane: Lane) -> &[Clip] {
217 &self.lanes[lane.index()]
218 }
219
220 /// The files the clips index into, in import order; index 0 is the file the
221 /// project was opened with.
222 pub fn sources(&self) -> &[PathBuf] {
223 &self.sources
224 }
225
226 /// Index for `path`, appending it if it is new. Deduped by
227 /// `fs::canonicalize`, so the same file reached by two paths imports once.
228 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
229 /// no history: a source entry alone changes nothing playable.
230 pub fn import(&mut self, path: impl AsRef<Path>) -> usize {
231 let path = canonical(path.as_ref());
232 match self.sources.iter().position(|s| *s == path) {
233 Some(idx) => idx,
234 None => {
235 self.sources.push(path);
236 self.sources.len() - 1
237 }
238 }
239 }
240
241 /// Append a whole-file clip of `source` to the end of *both* lanes, grouped
242 /// -- an import lands as one take. One history snapshot, so an import is one
243 /// undo step, and undoing it leaves the (harmless) source entry behind,
244 /// because indexes are forever. Refused for an unknown source index.
245 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
246 if source >= self.sources.len() {
247 return false;
248 }
249 self.snapshot();
250 let start = self.timeline_frames();
251 let clip = Clip {
252 start,
253 in_frame: 0,
254 out_frame: frame_count.max(1),
255 source,
256 link: Some(self.new_link()),
257 };
258 for lane in &mut self.lanes {
259 lane.push(clip);
260 }
261 true
262 }
263
264 /// The sources a clip actually names, with the clips reindexed onto them
265 /// -- what a save writes. Indexes are forever *inside* a session (see
266 /// [`Project::append_clip`]), so an undone import leaves an orphan source
267 /// entry behind; writing that orphan to a project file would let a file
268 /// nothing plays refuse a future load. New indexes are assigned in order of
269 /// first use -- video lane first, then audio -- so the same project always
270 /// emits the same bytes.
271 pub fn without_orphan_sources(&self) -> (Vec<PathBuf>, Vec<Clip>, Vec<Clip>) {
272 let mut moved = vec![None; self.sources.len()];
273 let mut sources = Vec::new();
274 let mut lanes = self.lanes.clone();
275 for c in lanes.iter_mut().flatten() {
276 let old = c.source;
277 c.source = match moved[old] {
278 Some(new) => new,
279 None => {
280 sources.push(self.sources[old].clone());
281 moved[old] = Some(sources.len() - 1);
282 sources.len() - 1
283 }
284 };
285 }
286 let [video, audio] = lanes;
287 (sources, video, audio)
288 }
289
290 /// Length of the timeline in frames: where the *last* lane runs out. A lane
291 /// that ends early is a trailing gap in that lane, not a shorter timeline.
292 pub fn timeline_frames(&self) -> u32 {
293 self.lanes
294 .iter()
295 .filter_map(|lane| lane.last().map(Clip::end))
296 .max()
297 .unwrap_or(0)
298 }
299
300 /// `(timeline_start, len)` per video clip, in order -- what a UI lane needs
301 /// to lay clips out. Gaps show up as the holes between consecutive entries.
302 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
303 self.lane_spans(Lane::Video)
304 }
305
306 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
307 self.lane(lane).iter().map(|c| (c.start, c.len())).collect()
308 }
309
310 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
311 /// and past the end -- [`Project::span_at`] is the version that tells those
312 /// two apart.
313 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
314 let clips = self.lane(lane);
315 let idx = at(clips, timeline_frame)?;
316 Some((
317 idx,
318 clips[idx].in_frame + (timeline_frame - clips[idx].start),
319 ))
320 }
321
322 /// [`map`](Project::map) on the video lane -- the mapping a decoder follows.
323 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
324 self.map(Lane::Video, timeline_frame)
325 }
326
327 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
328 /// it, or the gap running to the next clip (or to the end of the timeline,
329 /// which is where a lane shorter than its neighbour keeps showing black).
330 /// `None` at or past the end of the timeline, which is the only "nothing
331 /// left" there is.
332 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
333 let total = self.timeline_frames();
334 if timeline_frame >= total {
335 return None;
336 }
337 let clips = self.lane(lane);
338 Some(match at(clips, timeline_frame) {
339 Some(idx) => Span {
340 start: timeline_frame,
341 len: clips[idx].end() - timeline_frame,
342 from: Some((
343 clips[idx].source,
344 clips[idx].in_frame + (timeline_frame - clips[idx].start),
345 )),
346 },
347 None => Span {
348 start: timeline_frame,
349 // The next placement, or the end of the timeline: a gap is
350 // bounded by what comes after it, never by its own bookkeeping.
351 len: clips
352 .iter()
353 .find(|c| c.start > timeline_frame)
354 .map_or(total, |c| c.start)
355 - timeline_frame,
356 from: None,
357 },
358 })
359 }
360
361 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
362 /// gaps included -- the whole play list, which is what an export walks.
363 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
364 let mut out = Vec::new();
365 let mut t = timeline_frame;
366 while let Some(span) = self.span_at(lane, t) {
367 t = span.end();
368 out.push(span);
369 }
370 out
371 }
372
373 /// Split every lane at `timeline_frame`, so that frame becomes the first
374 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
375 /// (`false`, no change) when no lane has a clip to split there -- at a
376 /// placement's own start, in a gap, and past the end -- all of which would
377 /// produce an empty clip or nothing at all.
378 ///
379 /// The two lanes' halves share an id only where they are the *same* span:
380 /// the lanes are edited apart, so the clip being cut here may start (or
381 /// end) somewhere else in the other lane, and a group id whose two clips
382 /// disagree about their span is not one take (see [`links_are_consistent`],
383 /// which refuses to load one).
384 ///
385 /// Metadata only: no mapping changes, in any lane.
386 pub fn split(&mut self, timeline_frame: u32) -> bool {
387 let cut = Lane::ALL
388 .map(|l| splittable(self.lane(l), timeline_frame).map(|idx| self.lane(l)[idx]));
389 if cut.iter().all(Option::is_none) {
390 return false;
391 }
392 self.snapshot();
393 let same = |f: fn(&Clip) -> u32| match cut {
394 [Some(a), Some(b)] => f(&a) == f(&b),
395 _ => false,
396 };
397 let (left, right) = (self.new_link(), self.new_link());
398 // Each side is its own question: two clips may start together and end
399 // apart, and the halves that do line up stay one take.
400 let ids = [
401 (left, right),
402 (
403 if same(|c| c.start) {
404 left
405 } else {
406 self.new_link()
407 },
408 if same(Clip::end) {
409 right
410 } else {
411 self.new_link()
412 },
413 ),
414 ];
415 for (lane, (left, right)) in self.lanes.iter_mut().zip(ids) {
416 let Some(idx) = splittable(lane, timeline_frame) else {
417 continue;
418 };
419 let mut tail = lane[idx];
420 tail.in_frame += timeline_frame - tail.start;
421 tail.start = timeline_frame;
422 tail.link = Some(right);
423 lane[idx].out_frame = tail.in_frame;
424 lane[idx].link = Some(left);
425 lane.insert(idx + 1, tail);
426 }
427 true
428 }
429
430 /// The inverse of [`split`](Project::split): rejoin the placements that meet
431 /// at `timeline_frame` in every lane and put the result back in one group.
432 /// Only what a split could have produced is rejoined -- the two sides must
433 /// touch on the timeline *and* be consecutive frames of the same source --
434 /// so the clip list comes back exactly as it was and traversal with it.
435 /// `false` when no lane has such a pair. The rejoined clips share one id
436 /// only when they rejoin into the same span, for [`split`](Project::split)'s
437 /// reason.
438 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
439 // What each lane would end up covering, if it joins here at all.
440 let joined = Lane::ALL.map(|l| {
441 joinable(self.lane(l), timeline_frame)
442 .map(|idx| (self.lane(l)[idx].start, self.lane(l)[idx + 1].end()))
443 });
444 if joined.iter().all(Option::is_none) {
445 return false;
446 }
447 self.snapshot();
448 let link = self.new_link();
449 let ids = [
450 link,
451 match joined {
452 [Some(a), Some(b)] if a == b => link,
453 _ => self.new_link(),
454 },
455 ];
456 for (lane, link) in self.lanes.iter_mut().zip(ids) {
457 let Some(idx) = joinable(lane, timeline_frame) else {
458 continue;
459 };
460 lane[idx].out_frame = lane[idx + 1].out_frame;
461 lane[idx].link = Some(link);
462 lane.remove(idx + 1);
463 }
464 true
465 }
466
467 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
468 /// lands on and leaving every other clip exactly where it is -- the
469 /// per-lane paste. Anything already there is trimmed away (and split in two
470 /// if `clip` lands inside it), which is what keeps the lane sorted and
471 /// disjoint; nothing ripples, so a gap before the placement simply stays a
472 /// gap. Refused only for an empty `clip`.
473 ///
474 /// The placement belongs to no group: a clipboard clip carries the link id
475 /// of the take it was copied from, and placing it twice -- or placing a copy
476 /// back over the clip it came from -- would put that id on two clips of one
477 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
478 /// `None` rather than a fresh id because a one-lane placement has nothing on
479 /// the other lane to be grouped *with*; [`Project::regroup`] is how clips
480 /// become a group again.
481 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
482 if clip.out_frame <= clip.in_frame {
483 return false;
484 }
485 self.snapshot();
486 let clip = Clip {
487 start: timeline_frame,
488 link: None,
489 ..clip
490 };
491 let lane = &mut self.lanes[lane.index()];
492 clear(lane, clip.start, clip.end());
493 let idx = lane.partition_point(|c| c.start < clip.start);
494 lane.insert(idx, clip);
495 debug_assert!(sorted_disjoint(lane));
496 true
497 }
498
499 /// Insert `clip` into *both* lanes at `timeline_frame` as one new group,
500 /// pushing everything from there on later by its length -- the grouped,
501 /// rippling paste a clipboard does. Mid-clip the clip it lands in is split
502 /// around it; at or past the end of the timeline it is appended, because a
503 /// paste means "put it here", not "put it here and leave black in front".
504 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
505 ///
506 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
507 /// Changes the timeline->source mapping: the caller must reseek. Refused
508 /// only for an empty `clip`, which the never-empty invariant forbids but the
509 /// public fields still allow a caller to build.
510 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
511 if clip.out_frame <= clip.in_frame {
512 return false;
513 }
514 self.snapshot();
515 let at = timeline_frame.min(self.timeline_frames());
516 let clip = Clip {
517 start: at,
518 link: Some(self.new_link()),
519 ..clip
520 };
521 for lane in &mut self.lanes {
522 open_room(lane, at, clip.len());
523 let idx = lane.partition_point(|c| c.start < at);
524 lane.insert(idx, clip);
525 debug_assert!(sorted_disjoint(lane));
526 }
527 true
528 }
529
530 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
531 /// silence, and nothing else moves. Refused for an out-of-range index and
532 /// for the lift that would leave *both* lanes empty -- an empty timeline is
533 /// the front-end's state, not a project's (see the never-empty invariant).
534 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
535 let placed: usize = self.lanes.iter().map(Vec::len).sum();
536 if idx >= self.lane(lane).len() || placed == 1 {
537 return false;
538 }
539 self.snapshot();
540 self.lanes[lane.index()].remove(idx);
541 true
542 }
543
544 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
545 /// the hole: everything after slides back by `len`. The rippling delete --
546 /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an
547 /// empty range and when it would leave both lanes empty.
548 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
549 if len == 0 {
550 return false;
551 }
552 let survivors: usize = self
553 .lanes
554 .iter()
555 .map(|lane| {
556 lane.iter()
557 .filter(|c| c.start < at || c.end() > at + len)
558 .count()
559 })
560 .sum();
561 if survivors == 0 {
562 return false;
563 }
564 self.snapshot();
565 for lane in &mut self.lanes {
566 clear(lane, at, at + len);
567 for c in lane.iter_mut().filter(|c| c.start >= at) {
568 c.start -= len;
569 }
570 debug_assert!(sorted_disjoint(lane));
571 }
572 true
573 }
574
575 /// Remove the video clip at `idx` and everything under it, closing the gap
576 /// -- the whole-group delete a single-lane front-end means. `false` for a
577 /// bad index. Changes the mapping: the caller must reseek.
578 pub fn delete(&mut self, idx: usize) -> bool {
579 let Some(clip) = self.clips().get(idx).copied() else {
580 return false;
581 };
582 self.ripple_delete(clip.start, clip.len())
583 }
584
585 /// Restore both lanes from before the last successful edit. `false` when
586 /// there is nothing left to undo.
587 pub fn undo(&mut self) -> bool {
588 match self.history.pop() {
589 Some(prev) => {
590 self.lanes = prev;
591 true
592 }
593 None => false,
594 }
595 }
596
597 /// Half-open `(source, start, end)` segments in *source* seconds, from
598 /// `timeline_frame` to the end of the timeline -- the play list for the
599 /// audio worker, read off the **audio** lane. A `None` source is a gap: the
600 /// worker synthesises that many seconds of silence, which is what keeps the
601 /// audio master clock counting across a hole instead of stalling on it.
602 /// The first entry is partial when the position is mid-clip. Empty when the
603 /// position is past the end or `fps` is not usable.
604 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
605 if !(fps.is_finite() && fps > 0.0) {
606 return Vec::new();
607 }
608 self.spans_from(Lane::Audio, timeline_frame)
609 .iter()
610 .map(|span| match span.from {
611 // A clip's window is in *source* seconds: where in the file it
612 // reads from, which a delete before it never shifts.
613 Some((source, in_frame)) => (
614 Some(source),
615 f64::from(in_frame) / fps,
616 f64::from(in_frame + span.len) / fps,
617 ),
618 // A gap has no file, so all it can say is how long it is.
619 None => (None, 0.0, f64::from(span.len) / fps),
620 })
621 .collect()
622 }
623
624 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
625 /// it has decided it will succeed -- a refusal must not cost an undo step.
626 fn snapshot(&mut self) {
627 self.history.push(self.lanes.clone());
628 }
629
630 fn new_link(&mut self) -> u32 {
631 let id = self.next_link;
632 self.next_link = self.next_link.saturating_add(1);
633 id
634 }
635}
636
637/// Index of the clip covering `frame`, or `None` for a gap or past the end.
638/// Binary search: the sorted-disjoint invariant is what makes it legal.
639fn at(clips: &[Clip], frame: u32) -> Option<usize> {
640 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
641 (frame < clips[idx].end()).then_some(idx)
642}
643
644/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
645/// there would cut in two. A placement's own first frame is not inside it.
646fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
647 let idx = at(clips, frame)?;
648 (frame > clips[idx].start).then_some(idx)
649}
650
651/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
652/// rejoin: they must touch there, and be consecutive frames of one source.
653fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
654 let idx = clips.iter().position(|c| c.end() == frame)?;
655 let next = clips.get(idx + 1)?;
656 (next.start == frame
657 && next.source == clips[idx].source
658 && next.in_frame == clips[idx].out_frame)
659 .then_some(idx)
660}
661
662/// The lane invariant: sorted by `start`, no two placements overlapping, no
663/// empty placement. Checked at every constructor and asserted after every
664/// mutation -- the offset model is only tractable while it holds.
665fn sorted_disjoint(clips: &[Clip]) -> bool {
666 clips.iter().all(|c| c.out_frame > c.in_frame)
667 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
668}
669
670/// The grouping invariant, checked in release at [`Project::from_parts`]: a link
671/// id names **at most one** clip per lane, and when it names one in each, the two
672/// cover the same timeline span -- that is all "these move together" can mean.
673///
674/// A link the *other* lane does not carry is legal and is not an error: lifting
675/// one half of a group ([`Project::lift`]) leaves exactly that, and a save of
676/// that timeline has to load again.
677fn links_are_consistent(lanes: &[Vec<Clip>; 2]) -> crate::Result<()> {
678 let find = |lane: &Vec<Clip>, id: u32| lane.iter().find(|c| c.link == Some(id)).copied();
679 for (lane, name) in lanes.iter().zip(["video", "audio"]) {
680 for (i, c) in lane.iter().enumerate() {
681 let Some(id) = c.link else { continue };
682 if lane[..i].iter().any(|prev| prev.link == Some(id)) {
683 return Err(format!("link {id} names two clips in the {name} lane").into());
684 }
685 }
686 }
687 for a in lanes[0].iter().filter(|c| c.link.is_some()) {
688 let id = a.link.expect("filtered");
689 let Some(b) = find(&lanes[1], id) else {
690 continue;
691 };
692 if (a.start, a.end()) != (b.start, b.end()) {
693 return Err(format!(
694 "link {id} covers [{}, {}) in video and [{}, {}) in audio",
695 a.start,
696 a.end(),
697 b.start,
698 b.end()
699 )
700 .into());
701 }
702 }
703 Ok(())
704}
705
706/// Removes the timeline frames `[start, end)` from `clips`: placements inside
707/// it go, one straddling it is split in two, one overlapping an edge is
708/// trimmed. Source frames follow the trim, so what is left plays what it always
709/// played. Leaves the lane sorted and disjoint.
710///
711/// A piece the hole cut is no longer the take its group id names -- and both
712/// halves of a straddled placement carrying that id would be the same id twice
713/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
714fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
715 let mut out = Vec::with_capacity(clips.len() + 1);
716 for c in clips.drain(..) {
717 // Disjoint from the hole: untouched.
718 if c.end() <= start || c.start >= end {
719 out.push(c);
720 continue;
721 }
722 // The head that survives in front of the hole.
723 if c.start < start {
724 out.push(Clip {
725 out_frame: c.in_frame + (start - c.start),
726 link: None,
727 ..c
728 });
729 }
730 // ...and the tail behind it, which keeps reading where it would have.
731 if c.end() > end {
732 out.push(Clip {
733 start: end,
734 in_frame: c.in_frame + (end - c.start),
735 link: None,
736 ..c
737 });
738 }
739 }
740 *clips = out;
741}
742
743/// Slides everything from `at` on later by `len`, splitting a placement that
744/// straddles `at` so the two halves end up on either side of the hole. The
745/// insert half of a rippling paste. The two halves lose the group id for the
746/// reason [`clear`] gives.
747fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
748 if let Some(idx) = splittable(clips, at) {
749 let mut tail = clips[idx];
750 tail.in_frame += at - tail.start;
751 tail.start = at;
752 tail.link = None;
753 clips[idx].out_frame = tail.in_frame;
754 clips[idx].link = None;
755 clips.insert(idx + 1, tail);
756 }
757 for c in clips.iter_mut().filter(|c| c.start >= at) {
758 c.start += len;
759 }
760}
761
762/// Absolute, symlink-resolved when the file is reachable; the path as given
763/// when it is not -- an unreadable path still deserves an index, it simply
764/// dedups by spelling.
765fn canonical(path: &Path) -> PathBuf {
766 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
767}
768
769#[cfg(test)]
770mod tests {
771 use super::*;
772
773 const FPS: f64 = 30.0;
774 /// Never opened -- `Project` is pure data, so a path that does not exist is
775 /// simply a path that dedups by spelling.
776 const FILE: &str = "/nonexistent/a.mp4";
777 const FILE2: &str = "/nonexistent/b.mp4";
778
779 /// A contiguous placement, group id ignored: what most assertions compare.
780 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
781 Clip {
782 start,
783 in_frame,
784 out_frame,
785 source,
786 link: None,
787 }
788 }
789
790 /// Both lanes with their group ids blanked, for comparing shape.
791 fn shape(p: &Project) -> [Vec<Clip>; 2] {
792 Lane::ALL.map(|l| {
793 p.lane(l)
794 .iter()
795 .map(|c| Clip { link: None, ..*c })
796 .collect()
797 })
798 }
799
800 /// The *source frame* every timeline frame reads, per lane -- the traversal
801 /// a player performs. Deliberately not the clip index: a split changes which
802 /// clip a frame belongs to, and nothing else.
803 fn traversal(p: &Project) -> Vec<[Option<u32>; 2]> {
804 (0..p.timeline_frames() + 2)
805 .map(|f| Lane::ALL.map(|l| p.map(l, f).map(|(_, source)| source)))
806 .collect()
807 }
808
809 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
810 /// fixture. Built through `split` so the constructor path is exercised too.
811 fn three() -> Project {
812 let mut p = Project::single(FILE, 9);
813 assert!(p.split(3));
814 assert!(p.split(5));
815 assert_eq!(
816 shape(&p),
817 [
818 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
819 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
820 ]
821 );
822 p
823 }
824
825 #[test]
826 fn single_is_the_whole_file_on_both_lanes() {
827 let p = Project::single(FILE, 150);
828 assert_eq!(p.clips().len(), 1);
829 assert_eq!(p.lane(Lane::Audio).len(), 1);
830 assert_eq!(p.timeline_frames(), 150);
831 assert_eq!(p.clip_spans(), vec![(0, 150)]);
832 // grouped: video and audio carry the same link
833 assert_eq!(p.clips()[0].link, p.lane(Lane::Audio)[0].link);
834 assert!(p.clips()[0].link.is_some());
835 // degenerate mapping: timeline == source
836 assert_eq!(p.map_timeline(0), Some((0, 0)));
837 assert_eq!(p.map_timeline(149), Some((0, 149)));
838 assert_eq!(p.map_timeline(150), None);
839 // never-empty invariant survives a bogus frame count
840 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
841 }
842
843 #[test]
844 fn split_cuts_every_lane_and_regroups_it_back() {
845 let mut p = Project::single(FILE, 9);
846 let before = traversal(&p);
847 let before_shape = shape(&p);
848
849 assert!(p.split(4));
850 for l in Lane::ALL {
851 assert_eq!(p.lane(l).len(), 2, "{l:?} split");
852 }
853 // The two sides are two groups, one per side, matching across the lanes.
854 let (v, a) = (p.lane(Lane::Video), p.lane(Lane::Audio));
855 assert_eq!(v[0].link, a[0].link);
856 assert_eq!(v[1].link, a[1].link);
857 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
858 // A split changes no mapping, in either lane.
859 assert_eq!(traversal(&p), before, "a split moves nothing");
860
861 assert!(p.regroup(4), "the inverse rejoins them");
862 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
863 assert_eq!(traversal(&p), before);
864 assert_eq!(
865 p.lane(Lane::Video)[0].link,
866 p.lane(Lane::Audio)[0].link,
867 "and the rejoined clip is one group again"
868 );
869 }
870
871 #[test]
872 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
873 let mut p = three();
874 let before = shape(&p);
875 assert!(!p.split(0), "timeline 0 has nothing before it");
876 assert!(!p.split(3), "existing boundary");
877 assert!(!p.split(5), "existing boundary");
878 assert!(!p.split(9), "one past the last frame");
879 assert!(!p.split(1_000));
880 assert_eq!(shape(&p), before);
881 // one undo lands before the *second* split, so the refusals pushed nothing
882 assert!(p.undo());
883 assert_eq!(p.clips().len(), 2, "refused splits push no history");
884
885 // ...and a frame that is a gap in both lanes has nothing to split.
886 let mut p = three();
887 assert!(p.lift(Lane::Video, 1));
888 assert!(p.lift(Lane::Audio, 1));
889 assert!(!p.split(4), "a gap is not a clip");
890 }
891
892 #[test]
893 fn regroup_refuses_what_a_split_could_not_have_made() {
894 let mut p = three();
895 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
896 assert!(p.regroup(5));
897 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
898 // A boundary with a gap on one side, and one where the sources do not
899 // meet, are both refused.
900 let mut p = three();
901 assert!(p.lift(Lane::Video, 1));
902 assert!(p.lift(Lane::Audio, 1));
903 assert!(!p.regroup(3), "nothing starts at 3 any more");
904 let mut p = three();
905 for l in Lane::ALL {
906 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
907 }
908 assert!(!p.regroup(3), "source 100 does not follow source 3");
909 assert!(!p.regroup(0), "nothing ends at 0");
910 assert!(!p.regroup(1_000));
911 }
912
913 #[test]
914 fn map_and_spans_sweep_every_boundary() {
915 let p = three();
916 assert_eq!(p.timeline_frames(), 9);
917 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
918 // contiguous source here, so the clip index is what actually moves
919 let expect = [
920 (0, (0, 0)),
921 (1, (0, 1)),
922 (2, (0, 2)),
923 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
924 (4, (1, 4)),
925 (5, (2, 5)),
926 (6, (2, 6)),
927 (7, (2, 7)),
928 (8, (2, 8)),
929 ];
930 for (t, want) in expect {
931 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
932 }
933 assert_eq!(p.map_timeline(9), None);
934 // A span is the rest of the clip from where it was asked about.
935 assert_eq!(
936 p.span_at(Lane::Video, 6),
937 Some(Span {
938 start: 6,
939 len: 3,
940 from: Some((0, 6))
941 })
942 );
943 assert_eq!(p.span_at(Lane::Video, 9), None);
944 }
945
946 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
947 /// anything in `three()` so it is recognisable wherever it lands.
948 const PASTED: Clip = Clip {
949 start: 0,
950 in_frame: 100,
951 out_frame: 102,
952 source: 0,
953 link: None,
954 };
955
956 #[test]
957 fn paste_mid_clip_splits_around_it() {
958 let mut p = three();
959 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
960 assert_eq!(p.timeline_frames(), 11);
961 assert_eq!(
962 shape(&p)[0],
963 vec![
964 clip(0, 0, 3, 0),
965 clip(3, 3, 5, 0),
966 clip(5, 5, 6, 0),
967 clip(6, 100, 102, 0),
968 clip(8, 6, 9, 0),
969 ]
970 );
971 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
972 // The pasted frames are exactly where they were asked for, and the
973 // split-off remainder resumes after them.
974 assert_eq!(p.map_timeline(6), Some((3, 100)));
975 assert_eq!(p.map_timeline(7), Some((3, 101)));
976 assert_eq!(p.map_timeline(8), Some((4, 6)));
977 }
978
979 #[test]
980 fn paste_at_boundary_zero_and_end() {
981 let mut p = three();
982 assert!(p.paste(3, PASTED), "existing boundary: no split");
983 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
984 assert_eq!(p.map_timeline(3), Some((1, 100)));
985
986 let mut p = three();
987 assert!(p.paste(0, PASTED));
988 assert_eq!(p.map_timeline(0), Some((0, 100)));
989 assert_eq!(p.map_timeline(2), Some((1, 0)));
990
991 // At the end and past it both append -- a paste never leaves black in
992 // front of itself; `place` is the call that makes a gap.
993 let mut p = three();
994 assert!(p.paste(9, PASTED));
995 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
996 assert!(p.paste(1_000, PASTED));
997 assert_eq!(p.timeline_frames(), 13);
998
999 // An empty clip is the one thing refused, and it pushes no history.
1000 let mut p = three();
1001 assert!(!p.paste(4, clip(0, 7, 7, 0)));
1002 assert_eq!(p.clips().len(), 3);
1003 }
1004
1005 #[test]
1006 fn paste_undoes_in_one_step() {
1007 let mut p = three();
1008 let before = shape(&p);
1009 assert!(p.paste(6, PASTED));
1010 assert!(p.undo());
1011 assert_eq!(shape(&p), before, "a paste is one undo step");
1012 }
1013
1014 #[test]
1015 fn a_copy_outlives_the_clip_it_came_from() {
1016 let mut p = three();
1017 let copied = p.clips()[1]; // [3,5)
1018 assert!(p.delete(1));
1019 // Just a frame range: the source is still on disk either way.
1020 assert!(p.paste(0, copied));
1021 assert_eq!(p.map_timeline(0), Some((0, 3)));
1022 assert_eq!(p.timeline_frames(), 9);
1023 }
1024
1025 #[test]
1026 fn delete_closes_the_gap_on_both_lanes() {
1027 let mut p = three();
1028 assert!(p.delete(1));
1029 assert_eq!(p.timeline_frames(), 7);
1030 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
1031 assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 4)]);
1032 // timeline 3 used to be source 3; the gap closed so it is source 5 now
1033 assert_eq!(p.map_timeline(3), Some((1, 5)));
1034 assert_eq!(p.map_timeline(6), Some((1, 8)));
1035 assert_eq!(p.map_timeline(7), None);
1036 }
1037
1038 #[test]
1039 fn delete_first_last_and_only() {
1040 let mut p = three();
1041 assert!(p.delete(0));
1042 assert_eq!(p.map_timeline(0), Some((0, 3)));
1043 assert_eq!(p.timeline_frames(), 6);
1044
1045 let mut p = three();
1046 assert!(p.delete(2));
1047 assert_eq!(p.timeline_frames(), 5);
1048 assert_eq!(p.map_timeline(4), Some((1, 4)));
1049
1050 assert!(!p.delete(2), "index past the end");
1051 assert!(p.delete(1));
1052 assert!(!p.delete(0), "the last remaining clip stays");
1053 assert_eq!(p.clips().len(), 1);
1054 }
1055
1056 /// The offset model's point: one lane loses a clip, the other does not move.
1057 #[test]
1058 fn a_lift_leaves_a_gap_and_moves_nothing() {
1059 let mut p = three();
1060 let video_before = shape(&p)[0].clone();
1061 assert!(p.lift(Lane::Audio, 1));
1062 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
1063 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
1064 assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (5, 4)]);
1065 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
1066 assert_eq!(p.map(Lane::Audio, 4), None);
1067 assert_eq!(
1068 p.span_at(Lane::Audio, 3),
1069 Some(Span {
1070 start: 3,
1071 len: 2,
1072 from: None
1073 })
1074 );
1075 assert_eq!(p.map(Lane::Video, 4), Some((1, 4)), "video plays on");
1076 assert!(p.undo());
1077 assert_eq!(p.lane_spans(Lane::Audio), vec![(0, 3), (3, 2), (5, 4)]);
1078 }
1079
1080 #[test]
1081 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
1082 let mut p = three();
1083 assert!(p.lift(Lane::Audio, 2));
1084 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
1085 assert_eq!(
1086 p.span_at(Lane::Audio, 5),
1087 Some(Span {
1088 start: 5,
1089 len: 4,
1090 from: None
1091 }),
1092 "the audio lane holds silence to the end of the picture"
1093 );
1094 assert_eq!(p.span_at(Lane::Audio, 9), None);
1095 // Every lane covers the timeline exactly, gaps included.
1096 for l in Lane::ALL {
1097 let spans = p.spans_from(l, 0);
1098 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{l:?}");
1099 assert_eq!(spans[0].start, 0);
1100 }
1101 }
1102
1103 #[test]
1104 fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
1105 let mut p = Project::single(FILE, 9);
1106 assert!(p.lift(Lane::Audio, 0), "a silent timeline is fine");
1107 assert!(!p.lift(Lane::Video, 0), "an empty one is not");
1108 assert!(!p.lift(Lane::Audio, 0), "index past the end");
1109 assert_eq!(p.timeline_frames(), 9);
1110 }
1111
1112 #[test]
1113 fn place_overwrites_only_its_own_lane() {
1114 let mut p = three();
1115 let audio_before = shape(&p)[1].clone();
1116 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
1117 // is trimmed, nothing shifts.
1118 assert!(p.place(Lane::Video, 4, clip(0, 100, 102, 0)));
1119 assert_eq!(
1120 shape(&p)[0],
1121 vec![
1122 clip(0, 0, 3, 0),
1123 clip(3, 3, 4, 0),
1124 clip(4, 100, 102, 0),
1125 clip(6, 6, 9, 0),
1126 ]
1127 );
1128 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
1129 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
1130
1131 // Placed inside one clip, it splits it in two.
1132 let mut p = Project::single(FILE, 9);
1133 assert!(p.place(Lane::Video, 4, clip(0, 100, 101, 0)));
1134 assert_eq!(
1135 shape(&p)[0],
1136 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
1137 );
1138 // ...and placed past the end it makes a gap, which is the whole point.
1139 assert!(p.place(Lane::Video, 20, clip(0, 100, 102, 0)));
1140 assert_eq!(p.timeline_frames(), 22);
1141 assert_eq!(
1142 p.span_at(Lane::Video, 9),
1143 Some(Span {
1144 start: 9,
1145 len: 11,
1146 from: None
1147 })
1148 );
1149 assert!(!p.place(Lane::Video, 0, clip(0, 7, 7, 0)), "empty clip");
1150 }
1151
1152 #[test]
1153 fn ripple_delete_spans_partial_clips() {
1154 let mut p = three();
1155 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
1156 assert!(p.ripple_delete(2, 4));
1157 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
1158 assert_eq!(shape(&p)[1], shape(&p)[0]);
1159 assert_eq!(p.timeline_frames(), 5);
1160 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
1161 assert!(!p.ripple_delete(0, 100), "and one that empties every lane");
1162 assert!(p.undo());
1163 assert_eq!(shape(&p), shape(&three()));
1164 }
1165
1166 #[test]
1167 fn undo_restores_exactly() {
1168 let mut p = three();
1169 let after_splits = shape(&p);
1170 assert!(p.delete(1));
1171 assert!(p.undo());
1172 assert_eq!(shape(&p), after_splits);
1173
1174 // walk all the way back through both splits, then run dry
1175 assert!(p.undo());
1176 assert_eq!(p.clips().len(), 2);
1177 assert!(p.undo());
1178 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
1179 assert!(!p.undo(), "empty history");
1180 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
1181 }
1182
1183 /// Undo/redo by hand across a split must never merge two takes into one
1184 /// group by reusing an id.
1185 #[test]
1186 fn group_ids_are_never_reused() {
1187 let mut p = Project::single(FILE, 9);
1188 assert!(p.split(3));
1189 let first = p.clips()[1].link;
1190 assert!(p.undo());
1191 assert!(p.split(5));
1192 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
1193 }
1194
1195 #[test]
1196 fn segments_from_reads_the_audio_lane() {
1197 let p = three();
1198 // mid-clip: partial first segment, whole clips after it
1199 assert_eq!(
1200 p.segments_from(4, FPS),
1201 vec![
1202 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
1203 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
1204 ]
1205 );
1206 // on a boundary: nothing partial
1207 assert_eq!(
1208 p.segments_from(3, FPS),
1209 vec![
1210 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
1211 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
1212 ]
1213 );
1214 // from the top: one entry per clip
1215 assert_eq!(p.segments_from(0, FPS).len(), 3);
1216 // last clip only
1217 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
1218 // past the end / unusable fps
1219 assert!(p.segments_from(9, FPS).is_empty());
1220 assert!(p.segments_from(0, 0.0).is_empty());
1221 assert!(p.segments_from(0, f64::NAN).is_empty());
1222 }
1223
1224 #[test]
1225 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
1226 let mut p = three();
1227 assert!(p.lift(Lane::Audio, 1)); // silence over timeline [3, 5)
1228 assert_eq!(
1229 p.segments_from(0, FPS),
1230 vec![
1231 (Some(0), 0.0, 3.0 / 30.0),
1232 (None, 0.0, 2.0 / 30.0),
1233 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
1234 ]
1235 );
1236 // The list still covers exactly the timeline: that is what stops the
1237 // master clock stalling at the hole.
1238 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
1239 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
1240 // Starting inside the gap trims the silence, not the clip after it.
1241 assert_eq!(
1242 p.segments_from(4, FPS),
1243 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
1244 );
1245 // ...and a lane that is nothing but gap is a run of silence.
1246 assert!(p.lift(Lane::Audio, 0));
1247 assert!(p.lift(Lane::Audio, 0));
1248 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
1249 }
1250
1251 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
1252 /// of source 0 then [0,4) of source 1.
1253 fn two_sources() -> Project {
1254 let mut p = three();
1255 let s = p.import(FILE2);
1256 assert_eq!(s, 1);
1257 assert!(p.append_clip(s, 4));
1258 p
1259 }
1260
1261 #[test]
1262 fn import_dedups_and_appends() {
1263 let mut p = Project::single(FILE, 9);
1264 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
1265 assert_eq!(p.import(FILE), 0, "reimporting the open file reuses 0");
1266 assert_eq!(p.import(FILE2), 1);
1267 assert_eq!(p.import(FILE2), 1, "second import of the same path");
1268 assert_eq!(p.sources().len(), 2);
1269 assert!(!p.append_clip(2, 5), "unknown source index");
1270 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
1271
1272 // Two spellings of one real file are one source: this is the case the
1273 // raw-path comparison above would get wrong.
1274 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
1275 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
1276 let mut p = Project::single(here, 9);
1277 assert_eq!(p.import(detour), 0);
1278 assert_eq!(p.sources().len(), 1);
1279 }
1280
1281 #[test]
1282 fn append_clip_is_one_undo_step() {
1283 let mut p = two_sources();
1284 assert_eq!(p.timeline_frames(), 13);
1285 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
1286 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
1287 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
1288 assert!(p.undo());
1289 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
1290 assert_eq!(
1291 p.sources().len(),
1292 2,
1293 "the orphan source entry stays -- indexes are forever"
1294 );
1295 // ...and it is still usable, so a redo-by-hand costs no reimport.
1296 assert!(p.append_clip(1, 0));
1297 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
1298 }
1299
1300 #[test]
1301 fn edits_carry_the_source_along() {
1302 let mut p = two_sources();
1303 // A split inside the second source splits into two source-1 clips.
1304 assert!(p.split(11));
1305 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
1306 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
1307
1308 // A source-1 clip pasted into source-0 territory keeps its file, and so
1309 // does the source-0 half that got split off around it.
1310 let copied = p.clips()[4];
1311 assert!(p.paste(1, copied));
1312 assert_eq!(p.clips()[1].source, 1);
1313 assert_eq!(p.clips()[1].in_frame, 2);
1314 assert_eq!(p.clips()[2].source, 0);
1315 assert!(p.undo());
1316 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
1317 }
1318
1319 #[test]
1320 fn segments_from_names_the_source() {
1321 let p = two_sources();
1322 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
1323 assert_eq!(
1324 p.segments_from(4, FPS),
1325 vec![
1326 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
1327 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
1328 (Some(1), 0.0, 4.0 / 30.0),
1329 ]
1330 );
1331 // Mid-clip in source 1: only that source is left.
1332 assert_eq!(
1333 p.segments_from(10, FPS),
1334 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
1335 );
1336 assert!(p.segments_from(13, FPS).is_empty());
1337 // Segments still cover exactly the timeline across the join.
1338 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
1339 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
1340 }
1341
1342 #[test]
1343 fn segments_follow_deletes_and_fps() {
1344 let mut p = three();
1345 assert!(p.delete(0));
1346 // source seconds, not timeline: deleting the head does not shift them
1347 let segs = p.segments_from(0, 25.0);
1348 assert_eq!(
1349 segs,
1350 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
1351 );
1352 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
1353 assert!(
1354 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
1355 "segments must cover exactly the timeline: {played}"
1356 );
1357 }
1358
1359 #[test]
1360 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
1361 // Import a second file, undo it: source 1 is now an orphan.
1362 let mut p = two_sources();
1363 assert!(p.undo());
1364 let (sources, video, audio) = p.without_orphan_sources();
1365 assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone");
1366 assert_eq!(video, three().clips(), "the clips are untouched");
1367 assert_eq!(audio, three().lane(Lane::Audio));
1368
1369 // Three sources where only the middle one is orphaned: the survivors
1370 // renumber, and the clips follow.
1371 let mut p = Project::single(FILE, 9);
1372 assert_eq!(p.import(FILE2), 1);
1373 assert_eq!(p.import("/nonexistent/c.mp4"), 2);
1374 assert!(p.append_clip(2, 4));
1375 let (sources, video, audio) = p.without_orphan_sources();
1376 assert_eq!(
1377 sources,
1378 vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")]
1379 );
1380 assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);
1381 // ...and what comes out is loadable, with the same timeline.
1382 let reloaded = Project::from_parts(sources, video, audio).expect("from_parts");
1383 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
1384 assert_eq!(reloaded.sources().len(), 2);
1385 }
1386
1387 #[test]
1388 fn from_parts_has_no_history_and_checks_the_invariants() {
1389 let (sources, video, audio) = three().without_orphan_sources();
1390 let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())
1391 .expect("valid parts");
1392 assert_eq!(p.clips(), three().clips());
1393 assert!(!p.undo(), "a loaded project has nothing to undo");
1394 assert!(p.split(4), "...and is editable from there");
1395 assert!(p.undo());
1396
1397 // A lane may be empty; both may not.
1398 assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_ok());
1399 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());
1400 let bad: [Vec<Clip>; 5] = [
1401 vec![clip(0, 0, 3, 1)], // source that is not there
1402 vec![clip(0, 3, 3, 0)], // empty clip
1403 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
1404 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
1405 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
1406 ];
1407 for clips in bad {
1408 assert!(
1409 Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_err(),
1410 "{clips:?}"
1411 );
1412 assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_err());
1413 }
1414 // Group ids survive a load, and the next split gets a fresh one.
1415 let mut p = Project::from_parts(sources, video, audio).expect("valid parts");
1416 assert!(p.split(4));
1417 assert!(p.clips().iter().all(|c| c.link.is_some()));
1418 }
1419
1420 /// The grouping rules, at the untrusted door and after every edit that can
1421 /// touch a link. A link id is at most one clip per lane and, when both lanes
1422 /// carry it, one span -- and no sequence of edits may produce otherwise,
1423 /// because what an edit produces is what a save writes and a load reads.
1424 #[test]
1425 fn a_link_id_is_never_two_clips_of_one_lane() {
1426 let sources = vec![PathBuf::from(FILE)];
1427 let linked = |start, in_frame, out_frame, link| Clip {
1428 start,
1429 in_frame,
1430 out_frame,
1431 source: 0,
1432 link: Some(link),
1433 };
1434
1435 // The door: named errors, one per cause.
1436 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1437 Project::from_parts(sources.clone(), video, audio)
1438 .expect_err("refused")
1439 .to_string()
1440 };
1441 assert!(
1442 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
1443 .contains("link 7 names two clips in the video lane"),
1444 "a duplicate id inside one lane is refused by name"
1445 );
1446 assert!(
1447 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
1448 .contains("link 2 covers [0, 5) in video and [0, 3) in audio"),
1449 "a pair that does not cover one span is refused by name"
1450 );
1451 // A one-sided link is *not* an error: it is what a lift leaves behind.
1452 let mut p = Project::single(FILE, 9);
1453 assert!(p.lift(Lane::Audio, 0));
1454 let (sources, video, audio) = p.clone().without_orphan_sources();
1455 assert!(
1456 Project::from_parts(sources, video, audio).is_ok(),
1457 "a lifted lane's project has to load again"
1458 );
1459
1460 // The edits: nothing below may break either rule.
1461 let consistent = |p: &Project, what: &str| {
1462 let lanes = Lane::ALL.map(|l| p.lane(l).to_vec());
1463 assert!(links_are_consistent(&lanes).is_ok(), "{what}: {lanes:?}");
1464 };
1465 let mut p = three();
1466 let copied = p.clips()[0];
1467 assert!(
1468 copied.link.is_some(),
1469 "the clipboard clip carries its group"
1470 );
1471 assert!(p.lift(Lane::Video, 0));
1472 assert!(p.place(Lane::Video, 0, copied));
1473 assert!(p.place(Lane::Video, 20, copied), "and again, further out");
1474 assert_eq!(
1475 p.clips().iter().filter(|c| c.link == copied.link).count(),
1476 0,
1477 "a placement belongs to no group, so it cannot duplicate one"
1478 );
1479 consistent(&p, "lift + place twice");
1480 assert!(
1481 p.place(Lane::Audio, 4, copied),
1482 "over a linked clip's middle"
1483 );
1484 consistent(&p, "place through a grouped clip");
1485 assert!(p.paste(6, copied), "a rippling paste through another");
1486 consistent(&p, "paste");
1487 assert!(p.split(2));
1488 consistent(&p, "split");
1489 assert!(p.ripple_delete(1, 3));
1490 consistent(&p, "ripple_delete");
1491 assert!(p.undo());
1492 consistent(&p, "undo");
1493 }
1494
1495 /// What an edit produces is what a save writes, so *every* state the public
1496 /// API can reach has to load again. The two the verifier panel found where
1497 /// it did not: a split and a regroup handed one group id to two clips that
1498 /// were not the same span, because the lanes had been edited apart.
1499 #[test]
1500 fn every_reachable_state_reloads() {
1501 let mut p = Project::single(FILE, 150);
1502 assert!(p.place(Lane::Audio, 3, clip(0, 0, 50, 0)));
1503 assert!(p.split(10), "the lanes are cut apart at 10");
1504 reloads(&p, "place on one lane, then split");
1505
1506 let mut p = Project::single(FILE, 150);
1507 assert!(p.split(30));
1508 assert!(p.lift(Lane::Video, 0), "the picture goes, the sound stays");
1509 assert!(p.regroup(30), "only the audio lane can rejoin");
1510 assert!(p.split(60));
1511 reloads(&p, "lift, regroup one lane, split");
1512 }
1513
1514 /// The same claim, swept: random op sequences off the public surface, the
1515 /// project reloaded after every one of them. A failure prints its seed, and
1516 /// the seed replays the whole sequence.
1517 #[test]
1518 fn random_edit_sequences_reload() {
1519 for seed in 0..200u64 {
1520 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
1521 let mut next = move |n: u32| {
1522 // xorshift64*: no dependency, and the seed replays it exactly.
1523 rng ^= rng << 13;
1524 rng ^= rng >> 7;
1525 rng ^= rng << 17;
1526 (rng >> 33) as u32 % n
1527 };
1528 let mut p = Project::single(FILE, 40);
1529 for step in 0..24 {
1530 let frame = next(44);
1531 // A clipboard copy carries the group id of the take it came from
1532 // -- the input that made a placement duplicate an id.
1533 let copied = *p
1534 .lane(if next(2) == 0 {
1535 Lane::Video
1536 } else {
1537 Lane::Audio
1538 })
1539 .get(next(4) as usize)
1540 .unwrap_or(&clip(0, 0, 5, 0));
1541 let lane = if next(2) == 0 {
1542 Lane::Video
1543 } else {
1544 Lane::Audio
1545 };
1546 let idx = next(4) as usize;
1547 let _ = match next(9) {
1548 0 => p.split(frame),
1549 1 => p.regroup(frame),
1550 2 => p.lift(lane, idx),
1551 3 => p.place(lane, frame, copied),
1552 4 => p.paste(frame, copied),
1553 5 => p.ripple_delete(frame, next(9)),
1554 6 => p.delete(idx),
1555 7 => p.undo(),
1556 _ => p.append_clip(0, 1 + next(9)),
1557 };
1558 reloads(&p, &format!("seed {seed}, step {step}"));
1559 }
1560 }
1561 }
1562
1563 /// The save/load round trip a project must survive: the parts a save writes,
1564 /// handed back to the constructor a load goes through.
1565 fn reloads(p: &Project, what: &str) {
1566 let (sources, video, audio) = p.clone().without_orphan_sources();
1567 if let Err(e) = Project::from_parts(sources, video, audio) {
1568 panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);
1569 }
1570 }
1571}