forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

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