forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbbacfbTahinli3 months ago81 commits

project.rs2131 lines, 84.7 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- playback and export take `V1`, the audio
19//! worker takes `A1`, until a compositing slice teaches them the rest.
20//!
21//! The price is one invariant this module enforces at every mutation and every
22//! constructor: within a lane, clips are **sorted by `start` and never overlap**
23//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
24//! walk over that order.
25//!
26//! Two frame spaces meet here and are never mixed: *source* frames index the
27//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
28//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
29//!
30//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
31//! same take and move together. An id is *not* a pairing of two lanes -- it
32//! names at most one clip per lane and every clip carrying it covers the same
33//! timeline span, on however many lanes ([`links_are_consistent`]).
34//! [`Project::split`] cuts every lane at a timeline frame and hands each side
35//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
36//! is its inverse and rejoins them.
37//!
38//! Editing is metadata only. [`Project::split`] changes no timeline->source
39//! mapping, so a running decoder stays correct across it; everything else does
40//! and the caller must reseek. Every successful edit snapshots every lane, so
41//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
42//!
43//! A clip names its file by *index* into [`Project::sources`], which is
44//! append-only: an index handed out once stays valid forever, so a clip on the
45//! clipboard or inside an undo snapshot can never dangle. An index -- not an
46//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
47//! plain assignment.
48
49use std::path::{Path, PathBuf};
50
51/// A half-open `[in_frame, out_frame)` range of frames of source
52/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
53/// Never empty.
54#[derive(Clone, Copy, PartialEq, Eq, Debug)]
55pub struct Clip {
56 /// Timeline frame the clip's first frame is shown at. Meaningless on a
57 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
58 /// with where the caller asked for.
59 pub start: u32,
60 pub in_frame: u32,
61 pub out_frame: u32,
62 /// Index into [`Project::sources`].
63 pub source: usize,
64 /// Group id: clips sharing one were split from the same take. `None` for a
65 /// clip that belongs to no group.
66 pub link: Option<u32>,
67}
68
69impl Clip {
70 /// Frame count; `>= 1` by the never-empty invariant.
71 pub fn len(&self) -> u32 {
72 self.out_frame - self.in_frame
73 }
74
75 /// One past the last timeline frame it covers.
76 pub fn end(&self) -> u32 {
77 self.start + self.len()
78 }
79}
80
81/// A file the timeline plays from, and *which* of its audio streams it plays:
82/// a file carrying one track per language is several sources, one per stream,
83/// sharing a path. Two entries differing only in the stream are two sources --
84/// they are what a clip names, and a clip plays exactly one stream.
85///
86/// The path is always canonical ([`Source::new`]), so the same file reached by
87/// two paths is one source.
88#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct Source {
90 pub path: PathBuf,
91 /// Position among the file's audio tracks in file order, the numbering
92 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
93 /// single track, and for a silent one.
94 pub audio_stream: usize,
95}
96
97impl Source {
98 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
99 Self {
100 path: canonical(path.as_ref()),
101 audio_stream,
102 }
103 }
104}
105
106/// What a lane carries, which is what a *gap* in it means: black frames on a
107/// video lane, silence on an audio one.
108#[derive(Clone, Copy, PartialEq, Eq, Debug)]
109pub enum LaneKind {
110 Video,
111 Audio,
112}
113
114/// Which lane an operation acts on: a kind plus a 0-based position among the
115/// lanes of that kind, so [`Lane::V1`] is the first video lane and
116/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
117///
118/// A handle, not the lane itself. It stays meaningful while lanes are added,
119/// and one naming a lane that is not there reads as an empty lane and refuses
120/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
121/// bounds check of its own.
122#[derive(Clone, Copy, PartialEq, Eq, Debug)]
123pub struct Lane {
124 pub kind: LaneKind,
125 pub ord: usize,
126}
127
128impl Lane {
129 /// The first video lane: what a decoder plays and what an export renders.
130 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
131 /// The first audio lane: what the audio worker plays.
132 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
133
134 pub const fn new(kind: LaneKind, ord: usize) -> Self {
135 Self { kind, ord }
136 }
137
138 /// `V1`, `A2`: how a lane is written in a header column and named in an
139 /// error about it.
140 pub fn label(self) -> String {
141 let kind = match self.kind {
142 LaneKind::Video => 'V',
143 LaneKind::Audio => 'A',
144 };
145 format!("{kind}{}", self.ord + 1)
146 }
147}
148
149/// One lane: what it is and what it holds. A struct rather than a bare
150/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
151/// compositing mode, a name -- and it belongs next to the clips it applies to.
152#[derive(Clone, Debug)]
153struct LaneData {
154 kind: LaneKind,
155 /// Sorted by `start` and disjoint ([`sorted_disjoint`]).
156 clips: Vec<Clip>,
157}
158
159impl LaneData {
160 /// The two lanes a project starts with and the only two a `.edith` file
161 /// holds: `V1` then `A1`, in display order. One place, because every door
162 /// that builds a project from the outside builds exactly this pair.
163 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
164 vec![
165 LaneData {
166 kind: LaneKind::Video,
167 clips: video,
168 },
169 LaneData {
170 kind: LaneKind::Audio,
171 clips: audio,
172 },
173 ]
174 }
175}
176
177/// What a lane holds over one stretch of the timeline: either a placed clip or
178/// a gap. Returned already trimmed to the position it was asked about, so a
179/// caller can hand `len` straight to a decoder (or to a black-frame generator).
180#[derive(Clone, Copy, PartialEq, Eq, Debug)]
181pub struct Span {
182 /// Timeline frame the span starts at.
183 pub start: u32,
184 /// Frames it covers; `>= 1`.
185 pub len: u32,
186 /// `(source index, first source frame)`, or `None` for a gap -- which the
187 /// engine renders as black frames and as silence.
188 pub from: Option<(usize, u32)>,
189}
190
191impl Span {
192 /// One past the last timeline frame it covers.
193 pub fn end(&self) -> u32 {
194 self.start + self.len
195 }
196}
197
198/// The edit list plus its undo history.
199#[derive(Clone, Debug)]
200pub struct Project {
201 /// Append-only: never popped, never reordered. See the module docs.
202 sources: Vec<Source>,
203 /// In display order, which is the order [`Lane::ord`] counts in: the nth
204 /// lane of a kind here is that kind's `ord` n. Never empty.
205 lanes: Vec<LaneData>,
206 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
207 /// whole lane list, so adding a lane undoes as well.
208 history: Vec<Vec<LaneData>>,
209 /// Never rolled back by an undo: an id retired by an undone split must not
210 /// come back and group two clips that were never together.
211 next_link: u32,
212}
213
214impl Project {
215 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
216 /// grouped -- the state of a freshly opened video, where the timeline is the
217 /// source. `frame_count` of 0 would break the never-empty invariant, so it
218 /// is clamped to one frame.
219 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
220 let clip = Clip {
221 start: 0,
222 in_frame: 0,
223 out_frame: frame_count.max(1),
224 source: 0,
225 link: Some(0),
226 };
227 Self {
228 // A file is opened on its first audio stream: nothing has picked
229 // one yet, and every file with audio at all has that one.
230 sources: vec![Source::new(path, 0)],
231 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
232 history: Vec::new(),
233 next_link: 1,
234 }
235 }
236
237 /// A project rebuilt from a saved edit list -- the load half of
238 /// [`crate::edith`], which is a two-lane format, so this door takes `V1` and
239 /// `A1` and nothing else (see [`Project::without_orphan_sources`], which
240 /// refuses to *write* more). History is *not* saved, so [`Project::undo`] is
241 /// `false` until the first edit of the new session. This is the one door
242 /// untrusted parts come in through, so every invariant every other
243 /// constructor keeps is checked here, by name and in release: both lanes
244 /// empty, an empty clip, a clip naming a source that is not there, a clip
245 /// whose end overflows, a lane that is unsorted or self-overlapping, and
246 /// the grouping rules of [`Clip::link`] below.
247 pub fn from_parts(
248 sources: Vec<Source>,
249 video: Vec<Clip>,
250 audio: Vec<Clip>,
251 ) -> crate::Result<Self> {
252 if video.is_empty() && audio.is_empty() {
253 return Err("both lanes are empty: that is not a project".into());
254 }
255 let lanes = LaneData::two_lanes(video, audio);
256 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
257 let name = lane.label();
258 for c in &data.clips {
259 if c.out_frame <= c.in_frame {
260 return Err(format!(
261 "{name} clip at {} plays the empty range [{}, {})",
262 c.start, c.in_frame, c.out_frame
263 )
264 .into());
265 }
266 if c.source >= sources.len() {
267 return Err(format!(
268 "{name} clip at {} names source {} of {}",
269 c.start,
270 c.source,
271 sources.len()
272 )
273 .into());
274 }
275 if c.start.checked_add(c.len()).is_none() {
276 return Err(format!(
277 "{name} clip at {} runs past the last frame there is",
278 c.start
279 )
280 .into());
281 }
282 }
283 if !sorted_disjoint(&data.clips) {
284 return Err(format!("the {name} lane is out of order or overlaps itself").into());
285 }
286 }
287 links_are_consistent(&lanes)?;
288 let next_link = lanes
289 .iter()
290 .flat_map(|l| &l.clips)
291 .filter_map(|c| c.link)
292 .max()
293 // Saturating so a crafted file cannot make the counter wrap: at the
294 // ceiling ids stop being fresh, which loses grouping, not memory.
295 .map_or(0, |m| m.saturating_add(1));
296 Ok(Self {
297 sources: sources
298 .iter()
299 .map(|s| Source::new(&s.path, s.audio_stream))
300 .collect(),
301 lanes,
302 history: Vec::new(),
303 next_link,
304 })
305 }
306
307 /// The first video lane -- what an export renders and what a single-lane
308 /// caller still means by "the clips".
309 pub fn clips(&self) -> &[Clip] {
310 self.lane(Lane::V1)
311 }
312
313 /// The clips of `lane`, or nothing at all for a lane that is not there.
314 pub fn lane(&self, lane: Lane) -> &[Clip] {
315 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
316 }
317
318 /// Every lane's handle, in display order -- what a walk over "all lanes"
319 /// iterates, and what a front-end lays out top to bottom.
320 pub fn lanes(&self) -> Vec<Lane> {
321 handles(&self.lanes)
322 }
323
324 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
325 /// for every `ord` below it, and none at or above it.
326 pub fn lane_count(&self, kind: LaneKind) -> usize {
327 self.lanes.iter().filter(|l| l.kind == kind).count()
328 }
329
330 /// Appends an empty lane of `kind` and hands back its handle. One undo
331 /// step, because the lane list is state a front-end shows: an added lane
332 /// that could not be taken back would be the one edit with no way out.
333 /// Nothing plays differently until something is placed on it.
334 ///
335 /// The new lane being empty is fine even though [`Project::from_parts`]
336 /// refuses an all-empty project: the lanes that were there still hold the
337 /// timeline, and "no lane holds anything" is what that door refuses.
338 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
339 self.snapshot();
340 self.lanes.push(LaneData {
341 kind,
342 clips: Vec::new(),
343 });
344 Lane::new(kind, self.lane_count(kind) - 1)
345 }
346
347 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
348 /// not there. The one place a handle becomes a position.
349 fn index(&self, lane: Lane) -> Option<usize> {
350 self.lanes
351 .iter()
352 .enumerate()
353 .filter(|(_, l)| l.kind == lane.kind)
354 .map(|(i, _)| i)
355 .nth(lane.ord)
356 }
357
358 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
359 let i = self.index(lane)?;
360 Some(&mut self.lanes[i].clips)
361 }
362
363 /// The files the clips index into, in import order; index 0 is the file the
364 /// project was opened with.
365 pub fn sources(&self) -> &[Source] {
366 &self.sources
367 }
368
369 /// The same list in the `(path, stream)` shape the audio engine indexes
370 /// into -- [`crate::AudioSession::open_multi_streams`] and
371 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
372 /// was placed with is the stream that plays *and* the stream that exports.
373 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
374 self.sources
375 .iter()
376 .map(|s| (s.path.clone(), s.audio_stream))
377 .collect()
378 }
379
380 /// Index for `path` played on `audio_stream`, appending it if it is new.
381 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
382 /// by two paths imports once and two streams of one file are two sources.
383 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
384 /// no history: a source entry alone changes nothing playable.
385 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
386 let source = Source::new(path, audio_stream);
387 match self.sources.iter().position(|s| *s == source) {
388 Some(idx) => idx,
389 None => {
390 self.sources.push(source);
391 self.sources.len() - 1
392 }
393 }
394 }
395
396 /// Append a whole-file clip of `source` to the end of *every* lane, grouped
397 /// -- an import lands as one take. One history snapshot, so an import is one
398 /// undo step, and undoing it leaves the (harmless) source entry behind,
399 /// because indexes are forever. Refused for an unknown source index.
400 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
401 if source >= self.sources.len() {
402 return false;
403 }
404 self.snapshot();
405 let start = self.timeline_frames();
406 let clip = Clip {
407 start,
408 in_frame: 0,
409 out_frame: frame_count.max(1),
410 source,
411 link: Some(self.new_link()),
412 };
413 for data in &mut self.lanes {
414 data.clips.push(clip);
415 }
416 true
417 }
418
419 /// The sources a clip actually names, with the clips reindexed onto them
420 /// -- what a save writes. Indexes are forever *inside* a session (see
421 /// [`Project::append_clip`]), so an undone import leaves an orphan source
422 /// entry behind; writing that orphan to a project file would let a file
423 /// nothing plays refuse a future load. New indexes are assigned in order of
424 /// first use -- video lane first, then audio -- so the same project always
425 /// emits the same bytes.
426 ///
427 /// Refused, by name, for a timeline with more than one lane of a kind: the
428 /// `.edith` format has one line keyword per kind, so writing a third lane
429 /// would silently drop it. The model runs ahead of the format here on
430 /// purpose -- the bump is its own slice -- and a refused save is the one
431 /// answer that loses nothing.
432 pub fn without_orphan_sources(&self) -> crate::Result<(Vec<Source>, Vec<Clip>, Vec<Clip>)> {
433 for kind in [LaneKind::Video, LaneKind::Audio] {
434 let n = self.lane_count(kind);
435 if n > 1 {
436 let name = match kind {
437 LaneKind::Video => "video",
438 LaneKind::Audio => "audio",
439 };
440 return Err(format!(
441 "this timeline has {n} {name} lanes; a project file holds one of each -- \
442 saving more than two lanes needs a newer format"
443 )
444 .into());
445 }
446 }
447 let mut moved = vec![None; self.sources.len()];
448 let mut sources = Vec::new();
449 let mut lanes = self.lanes.clone();
450 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
451 let old = c.source;
452 c.source = match moved[old] {
453 Some(new) => new,
454 None => {
455 sources.push(self.sources[old].clone());
456 moved[old] = Some(sources.len() - 1);
457 sources.len() - 1
458 }
459 };
460 }
461 let (mut video, mut audio) = (Vec::new(), Vec::new());
462 for data in lanes {
463 match data.kind {
464 LaneKind::Video => video = data.clips,
465 LaneKind::Audio => audio = data.clips,
466 }
467 }
468 Ok((sources, video, audio))
469 }
470
471 /// Length of the timeline in frames: where the *last* lane runs out. A lane
472 /// that ends early is a trailing gap in that lane, not a shorter timeline.
473 pub fn timeline_frames(&self) -> u32 {
474 self.lanes
475 .iter()
476 .filter_map(|l| l.clips.last().map(Clip::end))
477 .max()
478 .unwrap_or(0)
479 }
480
481 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
482 /// to lay clips out. Gaps show up as the holes between consecutive entries.
483 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
484 self.lane_spans(Lane::V1)
485 }
486
487 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
488 self.lane(lane).iter().map(|c| (c.start, c.len())).collect()
489 }
490
491 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
492 /// and past the end -- [`Project::span_at`] is the version that tells those
493 /// two apart.
494 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
495 let clips = self.lane(lane);
496 let idx = at(clips, timeline_frame)?;
497 Some((
498 idx,
499 clips[idx].in_frame + (timeline_frame - clips[idx].start),
500 ))
501 }
502
503 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
504 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
505 self.map(Lane::V1, timeline_frame)
506 }
507
508 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
509 /// it, or the gap running to the next clip (or to the end of the timeline,
510 /// which is where a lane shorter than its neighbour keeps showing black).
511 /// `None` at or past the end of the timeline, which is the only "nothing
512 /// left" there is.
513 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
514 let total = self.timeline_frames();
515 if timeline_frame >= total {
516 return None;
517 }
518 let clips = self.lane(lane);
519 Some(match at(clips, timeline_frame) {
520 Some(idx) => Span {
521 start: timeline_frame,
522 len: clips[idx].end() - timeline_frame,
523 from: Some((
524 clips[idx].source,
525 clips[idx].in_frame + (timeline_frame - clips[idx].start),
526 )),
527 },
528 None => Span {
529 start: timeline_frame,
530 // The next placement, or the end of the timeline: a gap is
531 // bounded by what comes after it, never by its own bookkeeping.
532 len: clips
533 .iter()
534 .find(|c| c.start > timeline_frame)
535 .map_or(total, |c| c.start)
536 - timeline_frame,
537 from: None,
538 },
539 })
540 }
541
542 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
543 /// gaps included -- the whole play list, which is what an export walks.
544 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
545 let mut out = Vec::new();
546 let mut t = timeline_frame;
547 while let Some(span) = self.span_at(lane, t) {
548 t = span.end();
549 out.push(span);
550 }
551 out
552 }
553
554 /// Split every lane at `timeline_frame`, so that frame becomes the first
555 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
556 /// (`false`, no change) when no lane has a clip to split there -- at a
557 /// placement's own start, in a gap, and past the end -- all of which would
558 /// produce an empty clip or nothing at all.
559 ///
560 /// Lanes' halves share an id only where they are the *same* span: the lanes
561 /// are edited apart, so the clip being cut here may start (or end)
562 /// somewhere else on another lane, and a group id whose clips disagree
563 /// about their span is not one take (see [`links_are_consistent`], which
564 /// refuses to load one).
565 ///
566 /// Metadata only: no mapping changes, in any lane.
567 pub fn split(&mut self, timeline_frame: u32) -> bool {
568 let cut: Vec<Option<Clip>> = self
569 .lanes
570 .iter()
571 .map(|l| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
572 .collect();
573 if cut.iter().all(Option::is_none) {
574 return false;
575 }
576 self.snapshot();
577 // Each side is its own question: two clips may start together and end
578 // apart, and every lane whose halves do line up stays one take.
579 let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
580 let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();
581 let left = self.group_ids(&starts);
582 let right = self.group_ids(&ends);
583 for ((data, left), right) in self.lanes.iter_mut().zip(left).zip(right) {
584 let Some(idx) = splittable(&data.clips, timeline_frame) else {
585 continue;
586 };
587 let mut tail = data.clips[idx];
588 tail.in_frame += timeline_frame - tail.start;
589 tail.start = timeline_frame;
590 tail.link = right;
591 data.clips[idx].out_frame = tail.in_frame;
592 data.clips[idx].link = left;
593 data.clips.insert(idx + 1, tail);
594 }
595 true
596 }
597
598 /// The inverse of [`split`](Project::split): rejoin the placements that meet
599 /// at `timeline_frame` in every lane and put the result back in one group.
600 /// Only what a split could have produced is rejoined -- the two sides must
601 /// touch on the timeline *and* be consecutive frames of the same source --
602 /// so the clip list comes back exactly as it was and traversal with it.
603 /// `false` when no lane has such a pair. The rejoined clips share one id
604 /// only when they rejoin into the same span, for [`split`](Project::split)'s
605 /// reason.
606 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
607 // What each lane would end up covering, if it joins here at all.
608 let joined: Vec<Option<(u32, u32)>> = self
609 .lanes
610 .iter()
611 .map(|l| {
612 joinable(&l.clips, timeline_frame)
613 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
614 })
615 .collect();
616 if joined.iter().all(Option::is_none) {
617 return false;
618 }
619 self.snapshot();
620 let ids = self.group_ids(&joined);
621 for (data, link) in self.lanes.iter_mut().zip(ids) {
622 let Some(idx) = joinable(&data.clips, timeline_frame) else {
623 continue;
624 };
625 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
626 data.clips[idx].link = link;
627 data.clips.remove(idx + 1);
628 }
629 true
630 }
631
632 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
633 /// lands on and leaving every other clip exactly where it is -- the
634 /// per-lane paste. Anything already there is trimmed away (and split in two
635 /// if `clip` lands inside it), which is what keeps the lane sorted and
636 /// disjoint; nothing ripples, so a gap before the placement simply stays a
637 /// gap. Refused only for an empty `clip`.
638 ///
639 /// The placement belongs to no group: a clipboard clip carries the link id
640 /// of the take it was copied from, and placing it twice -- or placing a copy
641 /// back over the clip it came from -- would put that id on two clips of one
642 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
643 /// `None` rather than a fresh id because a one-lane placement has nothing on
644 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
645 /// become a group again.
646 ///
647 /// Refused for an empty `clip` and for a lane that is not there.
648 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
649 if clip.out_frame <= clip.in_frame || self.index(lane).is_none() {
650 return false;
651 }
652 self.snapshot();
653 let clip = Clip {
654 start: timeline_frame,
655 link: None,
656 ..clip
657 };
658 let clips = self.lane_mut(lane).expect("checked above");
659 clear(clips, clip.start, clip.end());
660 let idx = clips.partition_point(|c| c.start < clip.start);
661 clips.insert(idx, clip);
662 debug_assert!(sorted_disjoint(clips));
663 true
664 }
665
666 /// Insert `clip` into *every* lane at `timeline_frame` as one new group,
667 /// pushing everything from there on later by its length -- the grouped,
668 /// rippling paste a clipboard does. Mid-clip the clip it lands in is split
669 /// around it; at or past the end of the timeline it is appended, because a
670 /// paste means "put it here", not "put it here and leave black in front".
671 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
672 ///
673 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
674 /// Changes the timeline->source mapping: the caller must reseek. Refused
675 /// only for an empty `clip`, which the never-empty invariant forbids but the
676 /// public fields still allow a caller to build.
677 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
678 if clip.out_frame <= clip.in_frame {
679 return false;
680 }
681 self.snapshot();
682 let at = timeline_frame.min(self.timeline_frames());
683 let clip = Clip {
684 start: at,
685 link: Some(self.new_link()),
686 ..clip
687 };
688 for data in &mut self.lanes {
689 open_room(&mut data.clips, at, clip.len());
690 let idx = data.clips.partition_point(|c| c.start < at);
691 data.clips.insert(idx, clip);
692 debug_assert!(sorted_disjoint(&data.clips));
693 }
694 true
695 }
696
697 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
698 /// silence, and nothing else moves. Refused for an out-of-range index (which
699 /// a lane that is not there always is) and for the lift that would leave
700 /// *every* lane empty -- an empty timeline is the front-end's state, not a
701 /// project's (see the never-empty invariant).
702 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
703 let placed: usize = self.lanes.iter().map(|l| l.clips.len()).sum();
704 if idx >= self.lane(lane).len() || placed == 1 {
705 return false;
706 }
707 self.snapshot();
708 self.lane_mut(lane).expect("checked above").remove(idx);
709 true
710 }
711
712 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
713 /// the hole: everything after slides back by `len`. The rippling delete --
714 /// [`lift`](Project::lift) is the one that leaves a gap. Refused for an
715 /// empty range and when it would leave every lane empty.
716 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
717 if len == 0 {
718 return false;
719 }
720 let survivors: usize = self
721 .lanes
722 .iter()
723 .map(|l| {
724 l.clips
725 .iter()
726 .filter(|c| c.start < at || c.end() > at + len)
727 .count()
728 })
729 .sum();
730 if survivors == 0 {
731 return false;
732 }
733 self.snapshot();
734 for data in &mut self.lanes {
735 clear(&mut data.clips, at, at + len);
736 for c in data.clips.iter_mut().filter(|c| c.start >= at) {
737 c.start -= len;
738 }
739 debug_assert!(sorted_disjoint(&data.clips));
740 }
741 true
742 }
743
744 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
745 /// -- the whole-group delete a single-lane front-end means. `false` for a
746 /// bad index. Changes the mapping: the caller must reseek.
747 pub fn delete(&mut self, idx: usize) -> bool {
748 let Some(clip) = self.clips().get(idx).copied() else {
749 return false;
750 };
751 self.ripple_delete(clip.start, clip.len())
752 }
753
754 /// Restore every lane from before the last successful edit -- the clips and
755 /// the lane list both. `false` when there is nothing left to undo.
756 pub fn undo(&mut self) -> bool {
757 match self.history.pop() {
758 Some(prev) => {
759 self.lanes = prev;
760 true
761 }
762 None => false,
763 }
764 }
765
766 /// Half-open `(source, start, end)` segments in *source* seconds, from
767 /// `timeline_frame` to the end of the timeline -- the play list for the
768 /// audio worker, read off **`A1`**. A `None` source is a gap: the
769 /// worker synthesises that many seconds of silence, which is what keeps the
770 /// audio master clock counting across a hole instead of stalling on it.
771 /// The first entry is partial when the position is mid-clip. Empty when the
772 /// position is past the end or `fps` is not usable.
773 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
774 if !(fps.is_finite() && fps > 0.0) {
775 return Vec::new();
776 }
777 self.spans_from(Lane::A1, timeline_frame)
778 .iter()
779 .map(|span| match span.from {
780 // A clip's window is in *source* seconds: where in the file it
781 // reads from, which a delete before it never shifts.
782 Some((source, in_frame)) => (
783 Some(source),
784 f64::from(in_frame) / fps,
785 f64::from(in_frame + span.len) / fps,
786 ),
787 // A gap has no file, so all it can say is how long it is.
788 None => (None, 0.0, f64::from(span.len) / fps),
789 })
790 .collect()
791 }
792
793 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
794 /// it has decided it will succeed -- a refusal must not cost an undo step.
795 fn snapshot(&mut self) {
796 self.history.push(self.lanes.clone());
797 }
798
799 fn new_link(&mut self) -> u32 {
800 let id = self.next_link;
801 self.next_link = self.next_link.saturating_add(1);
802 id
803 }
804
805 /// One fresh group id per *distinct* key, in lane order, and `None` where a
806 /// lane has no key -- how [`split`](Project::split) and
807 /// [`regroup`](Project::regroup) hand out ids across however many lanes.
808 /// Lanes sharing a key end up sharing an id, which is exactly the rule
809 /// [`links_are_consistent`] enforces: one id, one span.
810 fn group_ids<K: PartialEq>(&mut self, keys: &[Option<K>]) -> Vec<Option<u32>> {
811 // Linear, over a handful of lanes: a hash of a lane list would cost
812 // more than it saves and would not be deterministic for free.
813 let mut seen: Vec<(&K, u32)> = Vec::new();
814 let mut out = Vec::with_capacity(keys.len());
815 for key in keys {
816 out.push(
817 key.as_ref()
818 .map(|k| match seen.iter().find(|(other, _)| *other == k) {
819 Some(&(_, id)) => id,
820 None => {
821 let id = self.new_link();
822 seen.push((k, id));
823 id
824 }
825 }),
826 );
827 }
828 out
829 }
830}
831
832/// The handle of every lane, in storage order -- the one definition of what
833/// [`Lane::ord`] counts.
834fn handles(lanes: &[LaneData]) -> Vec<Lane> {
835 let (mut video, mut audio) = (0, 0);
836 lanes
837 .iter()
838 .map(|l| match l.kind {
839 LaneKind::Video => {
840 video += 1;
841 Lane::new(LaneKind::Video, video - 1)
842 }
843 LaneKind::Audio => {
844 audio += 1;
845 Lane::new(LaneKind::Audio, audio - 1)
846 }
847 })
848 .collect()
849}
850
851/// Index of the clip covering `frame`, or `None` for a gap or past the end.
852/// Binary search: the sorted-disjoint invariant is what makes it legal.
853fn at(clips: &[Clip], frame: u32) -> Option<usize> {
854 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
855 (frame < clips[idx].end()).then_some(idx)
856}
857
858/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
859/// there would cut in two. A placement's own first frame is not inside it.
860fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
861 let idx = at(clips, frame)?;
862 (frame > clips[idx].start).then_some(idx)
863}
864
865/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
866/// rejoin: they must touch there, and be consecutive frames of one source.
867fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
868 let idx = clips.iter().position(|c| c.end() == frame)?;
869 let next = clips.get(idx + 1)?;
870 (next.start == frame
871 && next.source == clips[idx].source
872 && next.in_frame == clips[idx].out_frame)
873 .then_some(idx)
874}
875
876/// The lane invariant: sorted by `start`, no two placements overlapping, no
877/// empty placement. Checked at every constructor and asserted after every
878/// mutation -- the offset model is only tractable while it holds.
879fn sorted_disjoint(clips: &[Clip]) -> bool {
880 clips.iter().all(|c| c.out_frame > c.in_frame)
881 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
882}
883
884/// The grouping invariant, checked in release at [`Project::from_parts`] and
885/// asserted by the tests after every edit: a link id names **at most one** clip
886/// per lane, and every clip carrying it covers the same timeline span -- that is
887/// all "these move together" can mean.
888///
889/// Deliberately *not* a pairing of two lanes: with N lanes a take may run on
890/// `V1`, `V2` and `A1` at once, and the rule that makes an id meaningful is span
891/// identity, not which lane (or which `ord`) the partner sits on. Two lanes are
892/// the case where it reads as "the picture and its sound".
893///
894/// A link no other lane carries is legal and is not an error: lifting one half
895/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
896/// timeline has to load again.
897fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
898 let handles = handles(lanes);
899 for (data, lane) in lanes.iter().zip(&handles) {
900 for (i, c) in data.clips.iter().enumerate() {
901 let Some(id) = c.link else { continue };
902 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
903 return Err(
904 format!("link {id} names two clips in the {} lane", lane.label()).into(),
905 );
906 }
907 }
908 }
909 // First lane to carry an id fixes the span every other lane must agree on.
910 let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();
911 for (data, &lane) in lanes.iter().zip(&handles) {
912 for c in &data.clips {
913 let Some(id) = c.link else { continue };
914 match seen.iter().find(|(other, ..)| *other == id) {
915 Some(&(_, first, start, end)) => {
916 if (start, end) != (c.start, c.end()) {
917 return Err(format!(
918 "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",
919 first.label(),
920 c.start,
921 c.end(),
922 lane.label()
923 )
924 .into());
925 }
926 }
927 None => seen.push((id, lane, c.start, c.end())),
928 }
929 }
930 }
931 Ok(())
932}
933
934/// Removes the timeline frames `[start, end)` from `clips`: placements inside
935/// it go, one straddling it is split in two, one overlapping an edge is
936/// trimmed. Source frames follow the trim, so what is left plays what it always
937/// played. Leaves the lane sorted and disjoint.
938///
939/// A piece the hole cut is no longer the take its group id names -- and both
940/// halves of a straddled placement carrying that id would be the same id twice
941/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
942fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
943 let mut out = Vec::with_capacity(clips.len() + 1);
944 for c in clips.drain(..) {
945 // Disjoint from the hole: untouched.
946 if c.end() <= start || c.start >= end {
947 out.push(c);
948 continue;
949 }
950 // The head that survives in front of the hole.
951 if c.start < start {
952 out.push(Clip {
953 out_frame: c.in_frame + (start - c.start),
954 link: None,
955 ..c
956 });
957 }
958 // ...and the tail behind it, which keeps reading where it would have.
959 if c.end() > end {
960 out.push(Clip {
961 start: end,
962 in_frame: c.in_frame + (end - c.start),
963 link: None,
964 ..c
965 });
966 }
967 }
968 *clips = out;
969}
970
971/// Slides everything from `at` on later by `len`, splitting a placement that
972/// straddles `at` so the two halves end up on either side of the hole. The
973/// insert half of a rippling paste. The two halves lose the group id for the
974/// reason [`clear`] gives.
975fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
976 if let Some(idx) = splittable(clips, at) {
977 let mut tail = clips[idx];
978 tail.in_frame += at - tail.start;
979 tail.start = at;
980 tail.link = None;
981 clips[idx].out_frame = tail.in_frame;
982 clips[idx].link = None;
983 clips.insert(idx + 1, tail);
984 }
985 for c in clips.iter_mut().filter(|c| c.start >= at) {
986 c.start += len;
987 }
988}
989
990/// Absolute, symlink-resolved when the file is reachable; the path as given
991/// when it is not -- an unreadable path still deserves an index, it simply
992/// dedups by spelling.
993fn canonical(path: &Path) -> PathBuf {
994 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
995}
996
997#[cfg(test)]
998mod tests {
999 use super::*;
1000
1001 const FPS: f64 = 30.0;
1002 /// Never opened -- `Project` is pure data, so a path that does not exist is
1003 /// simply a path that dedups by spelling.
1004 const FILE: &str = "/nonexistent/a.mp4";
1005 const FILE2: &str = "/nonexistent/b.mp4";
1006
1007 /// A contiguous placement, group id ignored: what most assertions compare.
1008 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
1009 Clip {
1010 start,
1011 in_frame,
1012 out_frame,
1013 source,
1014 link: None,
1015 }
1016 }
1017
1018 /// Every lane with its group ids blanked, for comparing shape.
1019 fn shape(p: &Project) -> Vec<Vec<Clip>> {
1020 p.lanes()
1021 .into_iter()
1022 .map(|l| {
1023 p.lane(l)
1024 .iter()
1025 .map(|c| Clip { link: None, ..*c })
1026 .collect()
1027 })
1028 .collect()
1029 }
1030
1031 /// The *source frame* every timeline frame reads, per lane -- the traversal
1032 /// a player performs. Deliberately not the clip index: a split changes which
1033 /// clip a frame belongs to, and nothing else.
1034 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
1035 (0..p.timeline_frames() + 2)
1036 .map(|f| {
1037 p.lanes()
1038 .into_iter()
1039 .map(|l| p.map(l, f).map(|(_, source)| source))
1040 .collect()
1041 })
1042 .collect()
1043 }
1044
1045 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
1046 /// fixture. Built through `split` so the constructor path is exercised too.
1047 fn three() -> Project {
1048 let mut p = Project::single(FILE, 9);
1049 assert!(p.split(3));
1050 assert!(p.split(5));
1051 assert_eq!(
1052 shape(&p),
1053 [
1054 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
1055 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
1056 ]
1057 );
1058 p
1059 }
1060
1061 #[test]
1062 fn single_is_the_whole_file_on_both_lanes() {
1063 let p = Project::single(FILE, 150);
1064 assert_eq!(p.clips().len(), 1);
1065 assert_eq!(p.lane(Lane::A1).len(), 1);
1066 assert_eq!(p.timeline_frames(), 150);
1067 assert_eq!(p.clip_spans(), vec![(0, 150)]);
1068 // grouped: video and audio carry the same link
1069 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
1070 assert!(p.clips()[0].link.is_some());
1071 // degenerate mapping: timeline == source
1072 assert_eq!(p.map_timeline(0), Some((0, 0)));
1073 assert_eq!(p.map_timeline(149), Some((0, 149)));
1074 assert_eq!(p.map_timeline(150), None);
1075 // never-empty invariant survives a bogus frame count
1076 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
1077 }
1078
1079 #[test]
1080 fn split_cuts_every_lane_and_regroups_it_back() {
1081 let mut p = Project::single(FILE, 9);
1082 let before = traversal(&p);
1083 let before_shape = shape(&p);
1084
1085 assert!(p.split(4));
1086 for l in p.lanes() {
1087 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
1088 }
1089 // The two sides are two groups, one per side, matching across the lanes.
1090 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
1091 assert_eq!(v[0].link, a[0].link);
1092 assert_eq!(v[1].link, a[1].link);
1093 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
1094 // A split changes no mapping, in either lane.
1095 assert_eq!(traversal(&p), before, "a split moves nothing");
1096
1097 assert!(p.regroup(4), "the inverse rejoins them");
1098 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
1099 assert_eq!(traversal(&p), before);
1100 assert_eq!(
1101 p.lane(Lane::V1)[0].link,
1102 p.lane(Lane::A1)[0].link,
1103 "and the rejoined clip is one group again"
1104 );
1105 }
1106
1107 #[test]
1108 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
1109 let mut p = three();
1110 let before = shape(&p);
1111 assert!(!p.split(0), "timeline 0 has nothing before it");
1112 assert!(!p.split(3), "existing boundary");
1113 assert!(!p.split(5), "existing boundary");
1114 assert!(!p.split(9), "one past the last frame");
1115 assert!(!p.split(1_000));
1116 assert_eq!(shape(&p), before);
1117 // one undo lands before the *second* split, so the refusals pushed nothing
1118 assert!(p.undo());
1119 assert_eq!(p.clips().len(), 2, "refused splits push no history");
1120
1121 // ...and a frame that is a gap in both lanes has nothing to split.
1122 let mut p = three();
1123 assert!(p.lift(Lane::V1, 1));
1124 assert!(p.lift(Lane::A1, 1));
1125 assert!(!p.split(4), "a gap is not a clip");
1126 }
1127
1128 #[test]
1129 fn regroup_refuses_what_a_split_could_not_have_made() {
1130 let mut p = three();
1131 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
1132 assert!(p.regroup(5));
1133 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
1134 // A boundary with a gap on one side, and one where the sources do not
1135 // meet, are both refused.
1136 let mut p = three();
1137 assert!(p.lift(Lane::V1, 1));
1138 assert!(p.lift(Lane::A1, 1));
1139 assert!(!p.regroup(3), "nothing starts at 3 any more");
1140 let mut p = three();
1141 for l in p.lanes() {
1142 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
1143 }
1144 assert!(!p.regroup(3), "source 100 does not follow source 3");
1145 assert!(!p.regroup(0), "nothing ends at 0");
1146 assert!(!p.regroup(1_000));
1147 }
1148
1149 #[test]
1150 fn map_and_spans_sweep_every_boundary() {
1151 let p = three();
1152 assert_eq!(p.timeline_frames(), 9);
1153 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
1154 // contiguous source here, so the clip index is what actually moves
1155 let expect = [
1156 (0, (0, 0)),
1157 (1, (0, 1)),
1158 (2, (0, 2)),
1159 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
1160 (4, (1, 4)),
1161 (5, (2, 5)),
1162 (6, (2, 6)),
1163 (7, (2, 7)),
1164 (8, (2, 8)),
1165 ];
1166 for (t, want) in expect {
1167 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
1168 }
1169 assert_eq!(p.map_timeline(9), None);
1170 // A span is the rest of the clip from where it was asked about.
1171 assert_eq!(
1172 p.span_at(Lane::V1, 6),
1173 Some(Span {
1174 start: 6,
1175 len: 3,
1176 from: Some((0, 6))
1177 })
1178 );
1179 assert_eq!(p.span_at(Lane::V1, 9), None);
1180 }
1181
1182 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
1183 /// anything in `three()` so it is recognisable wherever it lands.
1184 const PASTED: Clip = Clip {
1185 start: 0,
1186 in_frame: 100,
1187 out_frame: 102,
1188 source: 0,
1189 link: None,
1190 };
1191
1192 #[test]
1193 fn paste_mid_clip_splits_around_it() {
1194 let mut p = three();
1195 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
1196 assert_eq!(p.timeline_frames(), 11);
1197 assert_eq!(
1198 shape(&p)[0],
1199 vec![
1200 clip(0, 0, 3, 0),
1201 clip(3, 3, 5, 0),
1202 clip(5, 5, 6, 0),
1203 clip(6, 100, 102, 0),
1204 clip(8, 6, 9, 0),
1205 ]
1206 );
1207 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
1208 // The pasted frames are exactly where they were asked for, and the
1209 // split-off remainder resumes after them.
1210 assert_eq!(p.map_timeline(6), Some((3, 100)));
1211 assert_eq!(p.map_timeline(7), Some((3, 101)));
1212 assert_eq!(p.map_timeline(8), Some((4, 6)));
1213 }
1214
1215 #[test]
1216 fn paste_at_boundary_zero_and_end() {
1217 let mut p = three();
1218 assert!(p.paste(3, PASTED), "existing boundary: no split");
1219 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
1220 assert_eq!(p.map_timeline(3), Some((1, 100)));
1221
1222 let mut p = three();
1223 assert!(p.paste(0, PASTED));
1224 assert_eq!(p.map_timeline(0), Some((0, 100)));
1225 assert_eq!(p.map_timeline(2), Some((1, 0)));
1226
1227 // At the end and past it both append -- a paste never leaves black in
1228 // front of itself; `place` is the call that makes a gap.
1229 let mut p = three();
1230 assert!(p.paste(9, PASTED));
1231 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
1232 assert!(p.paste(1_000, PASTED));
1233 assert_eq!(p.timeline_frames(), 13);
1234
1235 // An empty clip is the one thing refused, and it pushes no history.
1236 let mut p = three();
1237 assert!(!p.paste(4, clip(0, 7, 7, 0)));
1238 assert_eq!(p.clips().len(), 3);
1239 }
1240
1241 #[test]
1242 fn paste_undoes_in_one_step() {
1243 let mut p = three();
1244 let before = shape(&p);
1245 assert!(p.paste(6, PASTED));
1246 assert!(p.undo());
1247 assert_eq!(shape(&p), before, "a paste is one undo step");
1248 }
1249
1250 #[test]
1251 fn a_copy_outlives_the_clip_it_came_from() {
1252 let mut p = three();
1253 let copied = p.clips()[1]; // [3,5)
1254 assert!(p.delete(1));
1255 // Just a frame range: the source is still on disk either way.
1256 assert!(p.paste(0, copied));
1257 assert_eq!(p.map_timeline(0), Some((0, 3)));
1258 assert_eq!(p.timeline_frames(), 9);
1259 }
1260
1261 #[test]
1262 fn delete_closes_the_gap_on_both_lanes() {
1263 let mut p = three();
1264 assert!(p.delete(1));
1265 assert_eq!(p.timeline_frames(), 7);
1266 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
1267 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
1268 // timeline 3 used to be source 3; the gap closed so it is source 5 now
1269 assert_eq!(p.map_timeline(3), Some((1, 5)));
1270 assert_eq!(p.map_timeline(6), Some((1, 8)));
1271 assert_eq!(p.map_timeline(7), None);
1272 }
1273
1274 #[test]
1275 fn delete_first_last_and_only() {
1276 let mut p = three();
1277 assert!(p.delete(0));
1278 assert_eq!(p.map_timeline(0), Some((0, 3)));
1279 assert_eq!(p.timeline_frames(), 6);
1280
1281 let mut p = three();
1282 assert!(p.delete(2));
1283 assert_eq!(p.timeline_frames(), 5);
1284 assert_eq!(p.map_timeline(4), Some((1, 4)));
1285
1286 assert!(!p.delete(2), "index past the end");
1287 assert!(p.delete(1));
1288 assert!(!p.delete(0), "the last remaining clip stays");
1289 assert_eq!(p.clips().len(), 1);
1290 }
1291
1292 /// The offset model's point: one lane loses a clip, the other does not move.
1293 #[test]
1294 fn a_lift_leaves_a_gap_and_moves_nothing() {
1295 let mut p = three();
1296 let video_before = shape(&p)[0].clone();
1297 assert!(p.lift(Lane::A1, 1));
1298 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
1299 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
1300 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
1301 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
1302 assert_eq!(p.map(Lane::A1, 4), None);
1303 assert_eq!(
1304 p.span_at(Lane::A1, 3),
1305 Some(Span {
1306 start: 3,
1307 len: 2,
1308 from: None
1309 })
1310 );
1311 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
1312 assert!(p.undo());
1313 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
1314 }
1315
1316 #[test]
1317 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
1318 let mut p = three();
1319 assert!(p.lift(Lane::A1, 2));
1320 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
1321 assert_eq!(
1322 p.span_at(Lane::A1, 5),
1323 Some(Span {
1324 start: 5,
1325 len: 4,
1326 from: None
1327 }),
1328 "the audio lane holds silence to the end of the picture"
1329 );
1330 assert_eq!(p.span_at(Lane::A1, 9), None);
1331 // Every lane covers the timeline exactly, gaps included.
1332 for l in p.lanes() {
1333 let spans = p.spans_from(l, 0);
1334 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
1335 assert_eq!(spans[0].start, 0);
1336 }
1337 }
1338
1339 #[test]
1340 fn the_last_clip_of_the_last_lane_cannot_be_lifted() {
1341 let mut p = Project::single(FILE, 9);
1342 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
1343 assert!(!p.lift(Lane::V1, 0), "an empty one is not");
1344 assert!(!p.lift(Lane::A1, 0), "index past the end");
1345 assert_eq!(p.timeline_frames(), 9);
1346 }
1347
1348 #[test]
1349 fn place_overwrites_only_its_own_lane() {
1350 let mut p = three();
1351 let audio_before = shape(&p)[1].clone();
1352 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
1353 // is trimmed, nothing shifts.
1354 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
1355 assert_eq!(
1356 shape(&p)[0],
1357 vec![
1358 clip(0, 0, 3, 0),
1359 clip(3, 3, 4, 0),
1360 clip(4, 100, 102, 0),
1361 clip(6, 6, 9, 0),
1362 ]
1363 );
1364 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
1365 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
1366
1367 // Placed inside one clip, it splits it in two.
1368 let mut p = Project::single(FILE, 9);
1369 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
1370 assert_eq!(
1371 shape(&p)[0],
1372 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
1373 );
1374 // ...and placed past the end it makes a gap, which is the whole point.
1375 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
1376 assert_eq!(p.timeline_frames(), 22);
1377 assert_eq!(
1378 p.span_at(Lane::V1, 9),
1379 Some(Span {
1380 start: 9,
1381 len: 11,
1382 from: None
1383 })
1384 );
1385 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
1386 }
1387
1388 #[test]
1389 fn ripple_delete_spans_partial_clips() {
1390 let mut p = three();
1391 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
1392 assert!(p.ripple_delete(2, 4));
1393 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
1394 assert_eq!(shape(&p)[1], shape(&p)[0]);
1395 assert_eq!(p.timeline_frames(), 5);
1396 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
1397 assert!(!p.ripple_delete(0, 100), "and one that empties every lane");
1398 assert!(p.undo());
1399 assert_eq!(shape(&p), shape(&three()));
1400 }
1401
1402 #[test]
1403 fn undo_restores_exactly() {
1404 let mut p = three();
1405 let after_splits = shape(&p);
1406 assert!(p.delete(1));
1407 assert!(p.undo());
1408 assert_eq!(shape(&p), after_splits);
1409
1410 // walk all the way back through both splits, then run dry
1411 assert!(p.undo());
1412 assert_eq!(p.clips().len(), 2);
1413 assert!(p.undo());
1414 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
1415 assert!(!p.undo(), "empty history");
1416 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
1417 }
1418
1419 /// Undo/redo by hand across a split must never merge two takes into one
1420 /// group by reusing an id.
1421 #[test]
1422 fn group_ids_are_never_reused() {
1423 let mut p = Project::single(FILE, 9);
1424 assert!(p.split(3));
1425 let first = p.clips()[1].link;
1426 assert!(p.undo());
1427 assert!(p.split(5));
1428 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
1429 }
1430
1431 #[test]
1432 fn segments_from_reads_the_audio_lane() {
1433 let p = three();
1434 // mid-clip: partial first segment, whole clips after it
1435 assert_eq!(
1436 p.segments_from(4, FPS),
1437 vec![
1438 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
1439 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
1440 ]
1441 );
1442 // on a boundary: nothing partial
1443 assert_eq!(
1444 p.segments_from(3, FPS),
1445 vec![
1446 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
1447 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
1448 ]
1449 );
1450 // from the top: one entry per clip
1451 assert_eq!(p.segments_from(0, FPS).len(), 3);
1452 // last clip only
1453 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
1454 // past the end / unusable fps
1455 assert!(p.segments_from(9, FPS).is_empty());
1456 assert!(p.segments_from(0, 0.0).is_empty());
1457 assert!(p.segments_from(0, f64::NAN).is_empty());
1458 }
1459
1460 #[test]
1461 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
1462 let mut p = three();
1463 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
1464 assert_eq!(
1465 p.segments_from(0, FPS),
1466 vec![
1467 (Some(0), 0.0, 3.0 / 30.0),
1468 (None, 0.0, 2.0 / 30.0),
1469 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
1470 ]
1471 );
1472 // The list still covers exactly the timeline: that is what stops the
1473 // master clock stalling at the hole.
1474 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
1475 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
1476 // Starting inside the gap trims the silence, not the clip after it.
1477 assert_eq!(
1478 p.segments_from(4, FPS),
1479 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
1480 );
1481 // ...and a lane that is nothing but gap is a run of silence.
1482 assert!(p.lift(Lane::A1, 0));
1483 assert!(p.lift(Lane::A1, 0));
1484 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
1485 }
1486
1487 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
1488 /// of source 0 then [0,4) of source 1.
1489 fn two_sources() -> Project {
1490 let mut p = three();
1491 let s = p.import(FILE2, 0);
1492 assert_eq!(s, 1);
1493 assert!(p.append_clip(s, 4));
1494 p
1495 }
1496
1497 #[test]
1498 fn import_dedups_and_appends() {
1499 let mut p = Project::single(FILE, 9);
1500 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
1501 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
1502 assert_eq!(p.import(FILE2, 0), 1);
1503 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
1504 // ...but the same file on another audio stream is another source: it is
1505 // what a clip names, and a clip plays exactly one stream.
1506 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
1507 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
1508 assert_eq!(p.sources()[2].audio_stream, 1);
1509 assert!(p.append_clip(2, 4), "a stream entry is placeable");
1510 assert!(p.undo());
1511 assert_eq!(p.sources().len(), 3);
1512 assert!(!p.append_clip(3, 5), "unknown source index");
1513 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
1514
1515 // Two spellings of one real file are one source: this is the case the
1516 // raw-path comparison above would get wrong.
1517 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
1518 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
1519 let mut p = Project::single(here, 9);
1520 assert_eq!(p.import(detour, 0), 0);
1521 assert_eq!(p.sources().len(), 1);
1522 }
1523
1524 #[test]
1525 fn append_clip_is_one_undo_step() {
1526 let mut p = two_sources();
1527 assert_eq!(p.timeline_frames(), 13);
1528 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
1529 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
1530 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
1531 assert!(p.undo());
1532 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
1533 assert_eq!(
1534 p.sources().len(),
1535 2,
1536 "the orphan source entry stays -- indexes are forever"
1537 );
1538 // ...and it is still usable, so a redo-by-hand costs no reimport.
1539 assert!(p.append_clip(1, 0));
1540 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
1541 }
1542
1543 #[test]
1544 fn edits_carry_the_source_along() {
1545 let mut p = two_sources();
1546 // A split inside the second source splits into two source-1 clips.
1547 assert!(p.split(11));
1548 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
1549 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
1550
1551 // A source-1 clip pasted into source-0 territory keeps its file, and so
1552 // does the source-0 half that got split off around it.
1553 let copied = p.clips()[4];
1554 assert!(p.paste(1, copied));
1555 assert_eq!(p.clips()[1].source, 1);
1556 assert_eq!(p.clips()[1].in_frame, 2);
1557 assert_eq!(p.clips()[2].source, 0);
1558 assert!(p.undo());
1559 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
1560 }
1561
1562 #[test]
1563 fn segments_from_names_the_source() {
1564 let p = two_sources();
1565 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
1566 assert_eq!(
1567 p.segments_from(4, FPS),
1568 vec![
1569 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
1570 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
1571 (Some(1), 0.0, 4.0 / 30.0),
1572 ]
1573 );
1574 // Mid-clip in source 1: only that source is left.
1575 assert_eq!(
1576 p.segments_from(10, FPS),
1577 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
1578 );
1579 assert!(p.segments_from(13, FPS).is_empty());
1580 // Segments still cover exactly the timeline across the join.
1581 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
1582 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
1583 }
1584
1585 #[test]
1586 fn segments_follow_deletes_and_fps() {
1587 let mut p = three();
1588 assert!(p.delete(0));
1589 // source seconds, not timeline: deleting the head does not shift them
1590 let segs = p.segments_from(0, 25.0);
1591 assert_eq!(
1592 segs,
1593 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
1594 );
1595 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
1596 assert!(
1597 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
1598 "segments must cover exactly the timeline: {played}"
1599 );
1600 }
1601
1602 #[test]
1603 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
1604 // Import a second file, undo it: source 1 is now an orphan.
1605 let mut p = two_sources();
1606 assert!(p.undo());
1607 let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");
1608 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
1609 assert_eq!(video, three().clips(), "the clips are untouched");
1610 assert_eq!(audio, three().lane(Lane::A1));
1611
1612 // Three sources where only the middle one is orphaned: the survivors
1613 // renumber, and the clips follow.
1614 let mut p = Project::single(FILE, 9);
1615 assert_eq!(p.import(FILE2, 0), 1);
1616 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
1617 assert!(p.append_clip(2, 4));
1618 let (sources, video, audio) = p.without_orphan_sources().expect("two lanes");
1619 assert_eq!(
1620 sources,
1621 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
1622 );
1623 assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);
1624 // ...and what comes out is loadable, with the same timeline.
1625 let reloaded = Project::from_parts(sources, video, audio).expect("from_parts");
1626 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
1627 assert_eq!(reloaded.sources().len(), 2);
1628 }
1629
1630 #[test]
1631 fn from_parts_has_no_history_and_checks_the_invariants() {
1632 let (sources, video, audio) = three().without_orphan_sources().expect("two lanes");
1633 let mut p = Project::from_parts(sources.clone(), video.clone(), audio.clone())
1634 .expect("valid parts");
1635 assert_eq!(p.clips(), three().clips());
1636 assert!(!p.undo(), "a loaded project has nothing to undo");
1637 assert!(p.split(4), "...and is editable from there");
1638 assert!(p.undo());
1639
1640 // A lane may be empty; both may not.
1641 assert!(Project::from_parts(sources.clone(), video.clone(), Vec::new()).is_ok());
1642 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());
1643 let bad: [Vec<Clip>; 5] = [
1644 vec![clip(0, 0, 3, 1)], // source that is not there
1645 vec![clip(0, 3, 3, 0)], // empty clip
1646 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
1647 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
1648 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
1649 ];
1650 for clips in bad {
1651 assert!(
1652 Project::from_parts(sources.clone(), clips.clone(), Vec::new()).is_err(),
1653 "{clips:?}"
1654 );
1655 assert!(Project::from_parts(sources.clone(), video.clone(), clips).is_err());
1656 }
1657 // Group ids survive a load, and the next split gets a fresh one.
1658 let mut p = Project::from_parts(sources, video, audio).expect("valid parts");
1659 assert!(p.split(4));
1660 assert!(p.clips().iter().all(|c| c.link.is_some()));
1661 }
1662
1663 /// The grouping rules, at the untrusted door and after every edit that can
1664 /// touch a link. A link id is at most one clip per lane and, wherever it is
1665 /// carried, one span -- and no sequence of edits may produce otherwise,
1666 /// because what an edit produces is what a save writes and a load reads.
1667 ///
1668 /// Amended for the lane model: the two errors name their lane `V1`/`A1`
1669 /// rather than "video"/"audio", because with N lanes "the video lane" is no
1670 /// longer a lane. Same causes, same door, same claim.
1671 #[test]
1672 fn a_link_id_is_never_two_clips_of_one_lane() {
1673 let sources = vec![Source::new(FILE, 0)];
1674 let linked = |start, in_frame, out_frame, link| Clip {
1675 start,
1676 in_frame,
1677 out_frame,
1678 source: 0,
1679 link: Some(link),
1680 };
1681
1682 // The door: named errors, one per cause.
1683 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1684 Project::from_parts(sources.clone(), video, audio)
1685 .expect_err("refused")
1686 .to_string()
1687 };
1688 assert!(
1689 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
1690 .contains("link 7 names two clips in the V1 lane"),
1691 "a duplicate id inside one lane is refused by name"
1692 );
1693 assert!(
1694 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
1695 .contains("link 2 covers [0, 5) in V1 and [0, 3) in A1"),
1696 "a pair that does not cover one span is refused by name"
1697 );
1698 // A one-sided link is *not* an error: it is what a lift leaves behind.
1699 let mut p = Project::single(FILE, 9);
1700 assert!(p.lift(Lane::A1, 0));
1701 let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");
1702 assert!(
1703 Project::from_parts(sources, video, audio).is_ok(),
1704 "a lifted lane's project has to load again"
1705 );
1706
1707 // The edits: nothing below may break either rule.
1708 let consistent = |p: &Project, what: &str| {
1709 assert!(
1710 links_are_consistent(&p.lanes).is_ok(),
1711 "{what}: {:?}",
1712 p.lanes
1713 );
1714 };
1715 let mut p = three();
1716 let copied = p.clips()[0];
1717 assert!(
1718 copied.link.is_some(),
1719 "the clipboard clip carries its group"
1720 );
1721 assert!(p.lift(Lane::V1, 0));
1722 assert!(p.place(Lane::V1, 0, copied));
1723 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
1724 assert_eq!(
1725 p.clips().iter().filter(|c| c.link == copied.link).count(),
1726 0,
1727 "a placement belongs to no group, so it cannot duplicate one"
1728 );
1729 consistent(&p, "lift + place twice");
1730 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
1731 consistent(&p, "place through a grouped clip");
1732 assert!(p.paste(6, copied), "a rippling paste through another");
1733 consistent(&p, "paste");
1734 assert!(p.split(2));
1735 consistent(&p, "split");
1736 assert!(p.ripple_delete(1, 3));
1737 consistent(&p, "ripple_delete");
1738 assert!(p.undo());
1739 consistent(&p, "undo");
1740 }
1741
1742 /// What an edit produces is what a save writes, so *every* state the public
1743 /// API can reach has to load again. The two the verifier panel found where
1744 /// it did not: a split and a regroup handed one group id to two clips that
1745 /// were not the same span, because the lanes had been edited apart.
1746 #[test]
1747 fn every_reachable_state_reloads() {
1748 let mut p = Project::single(FILE, 150);
1749 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
1750 assert!(p.split(10), "the lanes are cut apart at 10");
1751 reloads(&p, "place on one lane, then split");
1752
1753 let mut p = Project::single(FILE, 150);
1754 assert!(p.split(30));
1755 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
1756 assert!(p.regroup(30), "only the audio lane can rejoin");
1757 assert!(p.split(60));
1758 reloads(&p, "lift, regroup one lane, split");
1759
1760 // Two audio streams of one file, both placed: two source entries with
1761 // one path between them, which is the state a stream picked out of the
1762 // library reaches -- and the state a save has to write and read back.
1763 let mut p = Project::single(FILE, 150);
1764 let second = p.import(FILE, 1);
1765 assert_eq!(second, 1, "the same file on another stream is a new source");
1766 assert!(p.append_clip(second, 150));
1767 assert!(p.split(200));
1768 reloads(
1769 &p,
1770 "a second audio stream of the same file, placed and split",
1771 );
1772 let (sources, ..) = p.without_orphan_sources().expect("two lanes");
1773 assert_eq!(
1774 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
1775 [0, 1],
1776 "both entries survive the orphan prune: both are played"
1777 );
1778 }
1779
1780 /// The same claim, swept: random op sequences off the public surface, the
1781 /// project reloaded after every one of them. A failure prints its seed, and
1782 /// the seed replays the whole sequence.
1783 #[test]
1784 fn random_edit_sequences_reload() {
1785 for seed in 0..200u64 {
1786 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
1787 let mut next = move |n: u32| {
1788 // xorshift64*: no dependency, and the seed replays it exactly.
1789 rng ^= rng << 13;
1790 rng ^= rng >> 7;
1791 rng ^= rng << 17;
1792 (rng >> 33) as u32 % n
1793 };
1794 let mut p = Project::single(FILE, 40);
1795 for step in 0..24 {
1796 let frame = next(44);
1797 // A clipboard copy carries the group id of the take it came from
1798 // -- the input that made a placement duplicate an id.
1799 let copied = *p
1800 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
1801 .get(next(4) as usize)
1802 .unwrap_or(&clip(0, 0, 5, 0));
1803 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
1804 let idx = next(4) as usize;
1805 let _ = match next(9) {
1806 0 => p.split(frame),
1807 1 => p.regroup(frame),
1808 2 => p.lift(lane, idx),
1809 3 => p.place(lane, frame, copied),
1810 4 => p.paste(frame, copied),
1811 5 => p.ripple_delete(frame, next(9)),
1812 6 => p.delete(idx),
1813 7 => p.undo(),
1814 _ => p.append_clip(0, 1 + next(9)),
1815 };
1816 reloads(&p, &format!("seed {seed}, step {step}"));
1817 }
1818 }
1819 }
1820
1821 /// The save/load round trip a project must survive: the parts a save writes,
1822 /// handed back to the constructor a load goes through.
1823 fn reloads(p: &Project, what: &str) {
1824 let (sources, video, audio) = p.clone().without_orphan_sources().expect("two lanes");
1825 if let Err(e) = Project::from_parts(sources, video, audio) {
1826 panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes);
1827 }
1828 }
1829
1830 /// What [`reloads`] proves for a timeline the file format cannot hold yet:
1831 /// the two invariants [`Project::from_parts`] checks that are about *lanes*
1832 /// -- each one sorted and disjoint, and one span per group id -- asserted
1833 /// directly, since a save of more than two lanes is refused on purpose.
1834 fn invariants_hold(p: &Project, what: &str) {
1835 for lane in p.lanes() {
1836 assert!(
1837 sorted_disjoint(p.lane(lane)),
1838 "{what}: {} is out of order or overlaps itself: {:?}",
1839 lane.label(),
1840 p.lane(lane)
1841 );
1842 }
1843 if let Err(e) = links_are_consistent(&p.lanes) {
1844 panic!("{what}: {e}\n{:?}", p.lanes);
1845 }
1846 }
1847
1848 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
1849 /// edited without any other lane hearing about it. A handle naming a lane
1850 /// that is not there reads as empty and refuses to mutate.
1851 #[test]
1852 fn a_third_lane_is_a_peer() {
1853 let mut p = three();
1854 assert_eq!(p.lane_count(LaneKind::Video), 1);
1855 assert_eq!(p.lane_count(LaneKind::Audio), 1);
1856 let v2 = p.add_lane(LaneKind::Video);
1857 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
1858 assert_eq!(v2.label(), "V2");
1859 assert_eq!(p.lane_count(LaneKind::Video), 2);
1860 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
1861 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
1862
1863 // A handle for a lane that is not there: empty, and no mutation takes.
1864 let v3 = Lane::new(LaneKind::Video, 2);
1865 assert!(p.lane(v3).is_empty());
1866 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
1867 assert!(!p.lift(v3, 0));
1868 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
1869
1870 // Placing on V2 moves nothing else, and the lane can outrun the rest.
1871 let before = shape(&p);
1872 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
1873 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
1874 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
1875 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
1876 assert_eq!(
1877 p.timeline_frames(),
1878 16,
1879 "the last lane to end sets the length"
1880 );
1881 assert_eq!(p.map(v2, 5), Some((0, 21)));
1882 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
1883 assert_eq!(
1884 p.span_at(v2, 0),
1885 Some(Span {
1886 start: 0,
1887 len: 4,
1888 from: None
1889 })
1890 );
1891 // Every lane still covers the whole timeline, gaps included.
1892 for l in p.lanes() {
1893 let spans = p.spans_from(l, 0);
1894 assert_eq!(
1895 spans.iter().map(|s| s.len).sum::<u32>(),
1896 16,
1897 "{}",
1898 l.label()
1899 );
1900 }
1901 // ...and playback still reads V1 and A1, whatever else is there.
1902 assert_eq!(p.clips(), p.lane(Lane::V1));
1903 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
1904 let segments = p.segments_from(0, FPS);
1905 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
1906 assert_eq!(
1907 segments[3],
1908 (None, 0.0, 7.0 / FPS),
1909 "A1 keeps the clock counting over the picture V2 added"
1910 );
1911 invariants_hold(&p, "place on V2");
1912
1913 // A lift is that lane's business too, and the lane list undoes.
1914 assert!(p.lift(v2, 0));
1915 assert!(p.lane(v2).is_empty());
1916 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
1917 assert!(p.undo());
1918 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
1919 assert!(p.undo());
1920 assert!(p.lane(v2).is_empty(), "the placement came off V2");
1921 assert!(p.undo(), "and one more step takes the lane itself back");
1922 assert_eq!(p.lane_count(LaneKind::Video), 1);
1923 assert_eq!(shape(&p), shape(&three()));
1924 }
1925
1926 /// The grouping rule across more than two lanes: a link id is one *span*,
1927 /// on however many lanes carry it -- not a video/audio pair and not a
1928 /// pairing by `ord`. So a split shares an id with every lane whose half
1929 /// lines up, and gives its own to every lane whose half does not.
1930 #[test]
1931 fn a_group_id_is_one_span_across_every_lane() {
1932 let mut p = Project::single(FILE, 9);
1933 let v2 = p.add_lane(LaneKind::Video);
1934 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "three lanes, one span");
1935 assert!(p.split(4));
1936 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
1937 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
1938 };
1939 let (left, right) = (side(&p, 0), side(&p, 1));
1940 assert!(
1941 left[0].is_some() && left.iter().all(|id| *id == left[0]),
1942 "one id for three left halves: {left:?}"
1943 );
1944 assert!(right.iter().all(|id| *id == right[0]), "{right:?}");
1945 assert_ne!(left[0], right[0], "the halves are no longer one take");
1946 invariants_hold(&p, "split across three lanes");
1947
1948 // V2 ends early: same start, so the left halves are one take; different
1949 // end, so the right halves cannot be.
1950 let mut p = Project::single(FILE, 9);
1951 let v2 = p.add_lane(LaneKind::Video);
1952 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
1953 assert!(p.split(3));
1954 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "same [0, 3)");
1955 assert_ne!(
1956 p.lane(Lane::V1)[1].link,
1957 p.lane(v2)[1].link,
1958 "[3,9) vs [3,6)"
1959 );
1960 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
1961 invariants_hold(&p, "split where one lane ends early");
1962
1963 // The inverse rejoins all three, and groups them the same way.
1964 assert!(p.regroup(3));
1965 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
1966 assert_ne!(
1967 p.lane(Lane::V1)[0].link,
1968 p.lane(v2)[0].link,
1969 "V2 rejoins into a span of its own"
1970 );
1971 invariants_hold(&p, "regroup across three lanes");
1972
1973 // ...and the rule is enforced, not merely produced: two video lanes
1974 // carrying one id over two spans is refused, by lane name.
1975 let linked = |out_frame, link| Clip {
1976 start: 0,
1977 in_frame: 0,
1978 out_frame,
1979 source: 0,
1980 link: Some(link),
1981 };
1982 let lanes = vec![
1983 LaneData {
1984 kind: LaneKind::Video,
1985 clips: vec![linked(3, 4)],
1986 },
1987 LaneData {
1988 kind: LaneKind::Video,
1989 clips: vec![linked(5, 4)],
1990 },
1991 ];
1992 assert_eq!(
1993 links_are_consistent(&lanes).unwrap_err().to_string(),
1994 "link 4 covers [0, 3) in V1 and [0, 5) in V2"
1995 );
1996 }
1997
1998 /// A group is a set of clips over one span, at most one per lane: a picture
1999 /// may be grouped with sound in *any* audio lane -- there is no paired ord,
2000 /// and the lanes in between may be empty -- and the two ways to break that
2001 /// name the lane they broke it on. Lanes built by hand, because the rule is
2002 /// checked at the untrusted door and no edit can produce these.
2003 #[test]
2004 fn a_group_may_span_any_lane() {
2005 let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips };
2006 let one = |start: u32, end: u32, link| Clip {
2007 start,
2008 in_frame: start,
2009 out_frame: end,
2010 source: 0,
2011 link: Some(link),
2012 };
2013 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
2014 let kinds = [
2015 LaneKind::Video,
2016 LaneKind::Audio,
2017 LaneKind::Video,
2018 LaneKind::Audio,
2019 ];
2020 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
2021 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
2022 };
2023 let take = || vec![one(0, 4, 7)];
2024 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
2025 // The same take on V1 + A2 only, the lanes between it empty: legal, the
2026 // way a lifted half is legal.
2027 let across = build([take(), Vec::new(), Vec::new(), take()]);
2028 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
2029 // Disagreeing about the span is not, and the message names both lanes.
2030 let apart = build([take(), Vec::new(), Vec::new(), vec![one(0, 6, 7)]]);
2031 assert_eq!(
2032 links_are_consistent(&apart).unwrap_err().to_string(),
2033 "link 7 covers [0, 4) in V1 and [0, 6) in A2"
2034 );
2035 // ...and one id twice in one lane is still that lane's error, by name.
2036 let twice = build([
2037 Vec::new(),
2038 Vec::new(),
2039 vec![one(0, 4, 7), one(4, 8, 7)],
2040 Vec::new(),
2041 ]);
2042 assert_eq!(
2043 links_are_consistent(&twice).unwrap_err().to_string(),
2044 "link 7 names two clips in the V2 lane"
2045 );
2046 }
2047
2048 /// The model runs ahead of the file format on purpose, so a save of what the
2049 /// format cannot hold is refused by name rather than silently dropping a
2050 /// lane -- and a two-lane project still writes exactly the parts it always
2051 /// did.
2052 #[test]
2053 fn a_save_refuses_more_lanes_than_the_format_holds() {
2054 let mut p = three();
2055 let before = p.without_orphan_sources().expect("two lanes save");
2056 let v2 = p.add_lane(LaneKind::Video);
2057 let err = p.without_orphan_sources().expect_err("refused").to_string();
2058 assert!(
2059 err.contains("2 video lanes") && err.contains("newer format"),
2060 "{err}"
2061 );
2062 // Even empty: what cannot be written must not be quietly left behind.
2063 assert!(p.lane(v2).is_empty());
2064 assert!(p.undo(), "and the lane undoes");
2065 assert_eq!(
2066 p.without_orphan_sources().expect("saveable again"),
2067 before,
2068 "byte for byte the same parts a two-lane save always wrote"
2069 );
2070
2071 let mut p = three();
2072 p.add_lane(LaneKind::Audio);
2073 assert!(
2074 p.without_orphan_sources()
2075 .unwrap_err()
2076 .to_string()
2077 .contains("2 audio lanes")
2078 );
2079 }
2080
2081 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
2082 /// three lanes and may grow more: every lane's own order and the one
2083 /// span-per-id rule, after every op. Amended rather than merged into that
2084 /// test because a >2-lane project cannot round-trip through the v2 file
2085 /// format -- [`invariants_hold`] checks what a reload would have checked.
2086 #[test]
2087 fn random_edit_sequences_keep_many_lanes_consistent() {
2088 for seed in 0..200u64 {
2089 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
2090 let mut next = move |n: u32| {
2091 rng ^= rng << 13;
2092 rng ^= rng >> 7;
2093 rng ^= rng << 17;
2094 (rng >> 33) as u32 % n
2095 };
2096 let mut p = Project::single(FILE, 40);
2097 let v2 = p.add_lane(LaneKind::Video);
2098 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
2099 let lanes = [Lane::V1, Lane::A1, v2];
2100 for step in 0..24 {
2101 let frame = next(44);
2102 let copied = *p
2103 .lane(lanes[next(3) as usize])
2104 .get(next(4) as usize)
2105 .unwrap_or(&clip(0, 0, 5, 0));
2106 let lane = lanes[next(3) as usize];
2107 let idx = next(4) as usize;
2108 let _ = match next(10) {
2109 0 => p.split(frame),
2110 1 => p.regroup(frame),
2111 2 => p.lift(lane, idx),
2112 3 => p.place(lane, frame, copied),
2113 4 => p.paste(frame, copied),
2114 5 => p.ripple_delete(frame, next(9)),
2115 6 => p.delete(idx),
2116 7 => p.undo(),
2117 8 => {
2118 p.add_lane(if next(2) == 0 {
2119 LaneKind::Video
2120 } else {
2121 LaneKind::Audio
2122 });
2123 true
2124 }
2125 _ => p.append_clip(0, 1 + next(9)),
2126 };
2127 invariants_hold(&p, &format!("seed {seed}, step {step}"));
2128 }
2129 }
2130 }
2131}