forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

project.rs3745 lines, 153.9 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 -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! A clip names its file by *index* into [`Project::sources`], which is
46//! append-only: an index handed out once stays valid forever, so a clip on the
47//! clipboard or inside an undo snapshot can never dangle. An index -- not an
48//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
49//! plain assignment.
50//!
51//! A clip names its equalizer the same way, by index into a second append-only
52//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
53//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
54//! halves the same settings, a copy carries them, and an undo restores whatever
55//! index the clip had. Only a *save* prunes the table
56//! ([`Project::without_orphan_sources`]), for the reason an undone import
57//! leaves its source entry behind: an index handed out is an index forever.
58//!
59//! Its colour grade is a third such table ([`Clip::color`],
60//! [`Project::set_color`]) and behaves in every way like the equalizer one --
61//! shared by equal settings, inherited by both halves of a split, pruned only at
62//! a save. An index rather than the four floats themselves for the same reason:
63//! twenty clips graded alike name one entry, and the file writes it once.
64
65use std::path::{Path, PathBuf};
66
67use crate::color::ColorParams;
68use crate::eq::EqParams;
69use crate::scale::FitPolicy;
70
71/// A half-open `[in_frame, out_frame)` range of frames of source
72/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
73/// Never empty.
74#[derive(Clone, Copy, PartialEq, Eq, Debug)]
75pub struct Clip {
76 /// Timeline frame the clip's first frame is shown at. Meaningless on a
77 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
78 /// with where the caller asked for.
79 pub start: u32,
80 pub in_frame: u32,
81 pub out_frame: u32,
82 /// Index into [`Project::sources`].
83 pub source: usize,
84 /// Group id: clips sharing one were split from the same take. `None` for a
85 /// clip that belongs to no group.
86 pub link: Option<u32>,
87 /// Index into the project's equalizer table
88 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
89 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
90 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
91 /// plain assignment. The table is append-only within a session, so an index
92 /// on a clipboard clip or inside an undo snapshot can never dangle.
93 pub eq: Option<u16>,
94 /// Index into the project's colour table
95 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
96 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
97 /// promises: `Copy`, append-only within a session, never dangling.
98 pub color: Option<u16>,
99 /// How this clip's picture meets a project canvas of another shape
100 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
101 /// two above: it is one byte with no parameters, so there is nothing for a
102 /// table to share, and a clip that is the project's own size never consults
103 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
104 /// where the aspect does not agree.
105 pub fit: FitPolicy,
106}
107
108impl Clip {
109 /// Frame count; `>= 1` by the never-empty invariant.
110 pub fn len(&self) -> u32 {
111 self.out_frame - self.in_frame
112 }
113
114 /// One past the last timeline frame it covers.
115 pub fn end(&self) -> u32 {
116 self.start + self.len()
117 }
118}
119
120/// A file the timeline plays from, and *which* of its audio streams it plays:
121/// a file carrying one track per language is several sources, one per stream,
122/// sharing a path. Two entries differing only in the stream are two sources --
123/// they are what a clip names, and a clip plays exactly one stream.
124///
125/// The path is always canonical ([`Source::new`]), so the same file reached by
126/// two paths is one source.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct Source {
129 pub path: PathBuf,
130 /// Position among the file's audio tracks in file order, the numbering
131 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
132 /// single track, and for a silent one.
133 pub audio_stream: usize,
134}
135
136impl Source {
137 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
138 Self {
139 path: canonical(path.as_ref()),
140 audio_stream,
141 }
142 }
143}
144
145/// What a lane carries, which is what a *gap* in it means: black frames on a
146/// video lane, silence on an audio one.
147#[derive(Clone, Copy, PartialEq, Eq, Debug)]
148pub enum LaneKind {
149 Video,
150 Audio,
151}
152
153/// Which lane an operation acts on: a kind plus a 0-based position among the
154/// lanes of that kind, so [`Lane::V1`] is the first video lane and
155/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
156///
157/// A handle, not the lane itself. It stays meaningful while lanes are added,
158/// and one naming a lane that is not there reads as an empty lane and refuses
159/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
160/// bounds check of its own.
161#[derive(Clone, Copy, PartialEq, Eq, Debug)]
162pub struct Lane {
163 pub kind: LaneKind,
164 pub ord: usize,
165}
166
167impl Lane {
168 /// The first video lane: what a decoder plays and what an export renders.
169 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
170 /// The first audio lane: what the audio worker plays.
171 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
172
173 pub const fn new(kind: LaneKind, ord: usize) -> Self {
174 Self { kind, ord }
175 }
176
177 /// `V1`, `A2`: how a lane is written in a header column and named in an
178 /// error about it.
179 pub fn label(self) -> String {
180 let kind = match self.kind {
181 LaneKind::Video => 'V',
182 LaneKind::Audio => 'A',
183 };
184 format!("{kind}{}", self.ord + 1)
185 }
186}
187
188/// One lane: what it is and what it holds. A struct rather than a bare
189/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
190/// compositing mode, a name -- and it belongs next to the clips it applies to.
191#[derive(Clone, Debug)]
192struct LaneData {
193 kind: LaneKind,
194 /// Sorted by `start` and disjoint ([`sorted_disjoint`]).
195 clips: Vec<Clip>,
196}
197
198impl LaneData {
199 /// The two lanes a project starts with: `V1` then `A1`, in display order.
200 /// One place, because a freshly opened file is exactly this pair.
201 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
202 vec![
203 LaneData {
204 kind: LaneKind::Video,
205 clips: video,
206 },
207 LaneData {
208 kind: LaneKind::Audio,
209 clips: audio,
210 },
211 ]
212 }
213}
214
215/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
216#[derive(Clone, Copy, PartialEq, Eq, Debug)]
217pub enum Edge {
218 /// Its first timeline frame; moving it changes where in the source the clip
219 /// starts reading, so the picture behind the edge slides with it.
220 Start,
221 /// One past its last timeline frame; moving it only says how much of the
222 /// source to keep.
223 End,
224}
225
226/// What a lane holds over one stretch of the timeline: either a placed clip or
227/// a gap. Returned already trimmed to the position it was asked about, so a
228/// caller can hand `len` straight to a decoder (or to a black-frame generator).
229#[derive(Clone, Copy, PartialEq, Eq, Debug)]
230pub struct Span {
231 /// Timeline frame the span starts at.
232 pub start: u32,
233 /// Frames it covers; `>= 1`.
234 pub len: u32,
235 /// `(source index, first source frame)`, or `None` for a gap -- which the
236 /// engine renders as black frames and as silence.
237 pub from: Option<(usize, u32)>,
238}
239
240impl Span {
241 /// One past the last timeline frame it covers.
242 pub fn end(&self) -> u32 {
243 self.start + self.len
244 }
245}
246
247/// What a save writes and a load takes back: the sources, every lane in
248/// display order with its kind, and the equalizer and colour tables their clips
249/// index into -- [`Project::without_orphan_sources`] out,
250/// [`Project::from_parts`] in.
251pub type Parts = (
252 Vec<Source>,
253 Vec<(LaneKind, Vec<Clip>)>,
254 Vec<EqParams>,
255 Vec<ColorParams>,
256);
257
258/// The edit list plus its undo history.
259#[derive(Clone, Debug)]
260pub struct Project {
261 /// Append-only: never popped, never reordered. See the module docs.
262 sources: Vec<Source>,
263 /// In display order, which is the order [`Lane::ord`] counts in: the nth
264 /// lane of a kind here is that kind's `ord` n. Never empty.
265 lanes: Vec<LaneData>,
266 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
267 eq: Vec<EqParams>,
268 /// The same, for [`Clip::color`].
269 color: Vec<ColorParams>,
270 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
271 /// whole lane list, so adding a lane undoes as well.
272 history: Vec<Vec<LaneData>>,
273 /// Never rolled back by an undo: an id retired by an undone split must not
274 /// come back and group two clips that were never together.
275 next_link: u32,
276}
277
278impl Project {
279 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
280 /// grouped -- the state of a freshly opened video, where the timeline is the
281 /// source. `frame_count` of 0 would break the never-empty invariant, so it
282 /// is clamped to one frame.
283 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
284 let clip = Clip {
285 start: 0,
286 in_frame: 0,
287 out_frame: frame_count.max(1),
288 source: 0,
289 link: Some(0),
290 eq: None,
291 color: None,
292 fit: FitPolicy::default(),
293 };
294 Self {
295 // A file is opened on its first audio stream: nothing has picked
296 // one yet, and every file with audio at all has that one.
297 sources: vec![Source::new(path, 0)],
298 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
299 eq: Vec::new(),
300 color: Vec::new(),
301 history: Vec::new(),
302 next_link: 1,
303 }
304 }
305
306 /// A project rebuilt from a saved edit list -- the load half of
307 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
308 /// an `ord` is a lane's position among the lanes of that kind, exactly as
309 /// [`Project::lanes`] hands them back. History is *not* saved, so
310 /// [`Project::undo`] is `false` until the first edit of the new session.
311 /// This is the one door untrusted parts come in through, so every invariant
312 /// every other constructor keeps is checked here, by name and in release:
313 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
314 /// or a colour) that is not there, a clip whose end overflows, a lane that is
315 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
316 /// below.
317 ///
318 /// A project whose lanes are all *empty* is not among them: an emptied
319 /// timeline is a project like any other -- it plays black and silent, it
320 /// saves, and it loads back. What a project cannot be is laneless, because
321 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
322 /// handle indexes into.
323 pub fn from_parts(
324 sources: Vec<Source>,
325 lanes: Vec<(LaneKind, Vec<Clip>)>,
326 eq: Vec<EqParams>,
327 color: Vec<ColorParams>,
328 ) -> crate::Result<Self> {
329 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
330 return Err(format!("eq {bad} holds a band that is not a finite number").into());
331 }
332 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
333 return Err(format!("color {bad} holds a value that is not a finite number").into());
334 }
335 if lanes.is_empty() {
336 return Err("no lanes at all: that is not a project".into());
337 }
338 let lanes: Vec<LaneData> = lanes
339 .into_iter()
340 .map(|(kind, clips)| LaneData { kind, clips })
341 .collect();
342 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
343 let name = lane.label();
344 for c in &data.clips {
345 if c.out_frame <= c.in_frame {
346 return Err(format!(
347 "{name} clip at {} plays the empty range [{}, {})",
348 c.start, c.in_frame, c.out_frame
349 )
350 .into());
351 }
352 if c.source >= sources.len() {
353 return Err(format!(
354 "{name} clip at {} names source {} of {}",
355 c.start,
356 c.source,
357 sources.len()
358 )
359 .into());
360 }
361 if c.start.checked_add(c.len()).is_none() {
362 return Err(format!(
363 "{name} clip at {} runs past the last frame there is",
364 c.start
365 )
366 .into());
367 }
368 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
369 return Err(format!(
370 "{name} clip at {} names eq {} of {}",
371 c.start,
372 c.eq.unwrap_or_default(),
373 eq.len()
374 )
375 .into());
376 }
377 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
378 return Err(format!(
379 "{name} clip at {} names color {} of {}",
380 c.start,
381 c.color.unwrap_or_default(),
382 color.len()
383 )
384 .into());
385 }
386 }
387 if !sorted_disjoint(&data.clips) {
388 return Err(format!("the {name} lane is out of order or overlaps itself").into());
389 }
390 }
391 links_are_consistent(&lanes)?;
392 let next_link = lanes
393 .iter()
394 .flat_map(|l| &l.clips)
395 .filter_map(|c| c.link)
396 .max()
397 // Saturating so a crafted file cannot make the counter wrap: at the
398 // ceiling ids stop being fresh, which loses grouping, not memory.
399 .map_or(0, |m| m.saturating_add(1));
400 Ok(Self {
401 sources: sources
402 .iter()
403 .map(|s| Source::new(&s.path, s.audio_stream))
404 .collect(),
405 lanes,
406 eq,
407 color,
408 history: Vec::new(),
409 next_link,
410 })
411 }
412
413 /// The first video lane -- what an export renders and what a single-lane
414 /// caller still means by "the clips".
415 pub fn clips(&self) -> &[Clip] {
416 self.lane(Lane::V1)
417 }
418
419 /// The clips of `lane`, or nothing at all for a lane that is not there.
420 pub fn lane(&self, lane: Lane) -> &[Clip] {
421 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
422 }
423
424 /// Every lane's handle, in display order -- what a walk over "all lanes"
425 /// iterates, and what a front-end lays out top to bottom.
426 pub fn lanes(&self) -> Vec<Lane> {
427 handles(&self.lanes)
428 }
429
430 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
431 /// for every `ord` below it, and none at or above it.
432 pub fn lane_count(&self, kind: LaneKind) -> usize {
433 self.lanes.iter().filter(|l| l.kind == kind).count()
434 }
435
436 /// Appends an empty lane of `kind` and hands back its handle. One undo
437 /// step, because the lane list is state a front-end shows: an added lane
438 /// that could not be taken back would be the one edit with no way out.
439 /// Nothing plays differently until something is placed on it.
440 ///
441 /// An empty lane is a lane like any other -- so is a whole project of them
442 /// ([`Project::from_parts`]); nothing plays until something is placed.
443 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
444 self.snapshot();
445 self.lanes.push(LaneData {
446 kind,
447 clips: Vec::new(),
448 });
449 Lane::new(kind, self.lane_count(kind) - 1)
450 }
451
452 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
453 /// not there. The one place a handle becomes a position.
454 fn index(&self, lane: Lane) -> Option<usize> {
455 self.lanes
456 .iter()
457 .enumerate()
458 .filter(|(_, l)| l.kind == lane.kind)
459 .map(|(i, _)| i)
460 .nth(lane.ord)
461 }
462
463 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
464 let i = self.index(lane)?;
465 Some(&mut self.lanes[i].clips)
466 }
467
468 /// The files the clips index into, in import order; index 0 is the file the
469 /// project was opened with.
470 pub fn sources(&self) -> &[Source] {
471 &self.sources
472 }
473
474 /// The same list in the `(path, stream)` shape the audio engine indexes
475 /// into -- [`crate::AudioSession::open_multi_streams`] and
476 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
477 /// was placed with is the stream that plays *and* the stream that exports.
478 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
479 self.sources
480 .iter()
481 .map(|s| (s.path.clone(), s.audio_stream))
482 .collect()
483 }
484
485 /// Index for `path` played on `audio_stream`, appending it if it is new.
486 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
487 /// by two paths imports once and two streams of one file are two sources.
488 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
489 /// no history: a source entry alone changes nothing playable.
490 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
491 let source = Source::new(path, audio_stream);
492 match self.sources.iter().position(|s| *s == source) {
493 Some(idx) => idx,
494 None => {
495 self.sources.push(source);
496 self.sources.len() - 1
497 }
498 }
499 }
500
501 /// Append a whole-file clip of `source` to the end of *every* lane, grouped
502 /// -- an import lands as one take. One history snapshot, so an import is one
503 /// undo step, and undoing it leaves the (harmless) source entry behind,
504 /// because indexes are forever. Refused for an unknown source index.
505 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
506 if source >= self.sources.len() {
507 return false;
508 }
509 self.snapshot();
510 let start = self.timeline_frames();
511 let clip = Clip {
512 start,
513 in_frame: 0,
514 out_frame: frame_count.max(1),
515 source,
516 link: Some(self.new_link()),
517 eq: None,
518 color: None,
519 fit: FitPolicy::default(),
520 };
521 for data in &mut self.lanes {
522 data.clips.push(clip);
523 }
524 true
525 }
526
527 /// The sources a clip actually names, with the clips reindexed onto them
528 /// -- what a save writes. Indexes are forever *inside* a session (see
529 /// [`Project::append_clip`]), so an undone import leaves an orphan source
530 /// entry behind; writing that orphan to a project file would let a file
531 /// nothing plays refuse a future load. New indexes are assigned in order of
532 /// first use -- lane by lane, in display order -- so the same project always
533 /// emits the same bytes.
534 ///
535 /// Every lane comes out, in display order and with its kind: that is what a
536 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
537 /// takes back.
538 ///
539 /// The equalizer and colour tables are pruned the same way and for the same
540 /// reason: an undone [`set_eq`](Project::set_eq) or
541 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
542 /// and this is the one moment they can go -- the indexes that survive it are
543 /// only the ones a clip names.
544 ///
545 /// One exception, and it is the emptied timeline's: a project no clip plays
546 /// from still keeps source 0. It is the file a session is scaffolded from --
547 /// its frame rate is the timeline's and is written nowhere else -- so a save
548 /// that pruned it would write a project that cannot be loaded back at all.
549 pub fn without_orphan_sources(&self) -> Parts {
550 let mut moved = vec![None; self.sources.len()];
551 let mut sources = Vec::new();
552 let mut moved_eq = vec![None; self.eq.len()];
553 let mut eq = Vec::new();
554 let mut moved_color = vec![None; self.color.len()];
555 let mut color = Vec::new();
556 let mut lanes = self.lanes.clone();
557 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
558 let old = c.source;
559 c.source = match moved[old] {
560 Some(new) => new,
561 None => {
562 sources.push(self.sources[old].clone());
563 moved[old] = Some(sources.len() - 1);
564 sources.len() - 1
565 }
566 };
567 if let Some(old) = c.eq.map(usize::from) {
568 c.eq = Some(match moved_eq[old] {
569 Some(new) => new,
570 None => {
571 eq.push(self.eq[old].clone());
572 let new = (eq.len() - 1) as u16;
573 moved_eq[old] = Some(new);
574 new
575 }
576 });
577 }
578 if let Some(old) = c.color.map(usize::from) {
579 c.color = Some(match moved_color[old] {
580 Some(new) => new,
581 None => {
582 color.push(self.color[old]);
583 let new = (color.len() - 1) as u16;
584 moved_color[old] = Some(new);
585 new
586 }
587 });
588 }
589 }
590 if sources.is_empty() {
591 sources.extend(self.sources.first().cloned());
592 }
593 (
594 sources,
595 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
596 eq,
597 color,
598 )
599 }
600
601 /// What the clip at `idx` of `lane` plays through, or `None` for one that
602 /// plays flat (and for an index that is not there) -- what a feeder and an
603 /// export ask before they build an [`crate::eq::EqState`].
604 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
605 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
606 }
607
608 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
609 /// take them off. One undo step, like every other edit. `false` -- and no
610 /// history -- for an index that is not there and for params holding a value
611 /// that is not finite, which is the one thing the file format could not
612 /// write and read back.
613 ///
614 /// Settings equal to ones already in the table share their entry, so a
615 /// project that puts the same curve on twenty clips writes it once.
616 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
617 if idx >= self.lane(lane).len() {
618 return false;
619 }
620 let slot = match params {
621 None => None,
622 Some(params) => {
623 if !finite(&params) {
624 return false;
625 }
626 Some(match self.eq.iter().position(|p| *p == params) {
627 Some(at) => at as u16,
628 // ponytail: the table is append-only within a session (see
629 // the module docs) and `Clip::eq` is a u16, so the 65535th
630 // *distinct* setting of one session is refused rather than
631 // silently aliased. Upgrade path if a UI ever drags a slider
632 // that far: widen `Clip::eq` to u32 (Clip has the room) or
633 // snapshot the table into the history and compact it here.
634 None if self.eq.len() >= usize::from(u16::MAX) => return false,
635 None => {
636 self.eq.push(params);
637 (self.eq.len() - 1) as u16
638 }
639 })
640 }
641 };
642 self.snapshot();
643 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
644 true
645 }
646
647 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
648 /// ungraded (and for an index that is not there) -- what the renderer and
649 /// the export ask before they call [`crate::color::apply_yuv`].
650 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
651 self.color
652 .get(usize::from(self.lane(lane).get(idx)?.color?))
653 }
654
655 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
656 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
657 /// (and no history) for an index that is not there or a value that is not
658 /// finite, and equal settings share a table entry.
659 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
660 self.write_color(lane, idx, params, true)
661 }
662
663 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
664 /// one pointer drag, whose first write (a plain `set_color`) already took the
665 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
666 /// not one per pixel -- and undoing it lands where the hand picked it up.
667 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
668 self.write_color(lane, idx, params, false)
669 }
670
671 fn write_color(
672 &mut self,
673 lane: Lane,
674 idx: usize,
675 params: Option<ColorParams>,
676 snapshot: bool,
677 ) -> bool {
678 if idx >= self.lane(lane).len() {
679 return false;
680 }
681 let slot = match params {
682 None => None,
683 Some(params) => {
684 if !color_finite(&params) {
685 return false;
686 }
687 Some(match self.color.iter().position(|p| *p == params) {
688 Some(at) => at as u16,
689 // ponytail: the 65535th *distinct* grade of one session is
690 // refused rather than silently aliased, exactly as `set_eq`
691 // refuses the 65535th curve; same upgrade path.
692 None if self.color.len() >= usize::from(u16::MAX) => return false,
693 None => {
694 self.color.push(params);
695 (self.color.len() - 1) as u16
696 }
697 })
698 }
699 };
700 if snapshot {
701 self.snapshot();
702 }
703 self.lane_mut(lane).expect("checked above")[idx].color = slot;
704 true
705 }
706
707 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
708 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
709 /// every clip starts at anyway.
710 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
711 self.lane(lane)
712 .get(idx)
713 .map_or(FitPolicy::default(), |c| c.fit)
714 }
715
716 /// Sets it. One undo step like every other edit, and `false` (with no
717 /// history) for an index that is not there. Unlike an eq or a grade there is
718 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
719 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
720 if idx >= self.lane(lane).len() {
721 return false;
722 }
723 self.snapshot();
724 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
725 true
726 }
727
728 /// Length of the timeline in frames: where the *last* lane runs out. A lane
729 /// that ends early is a trailing gap in that lane, not a shorter timeline.
730 pub fn timeline_frames(&self) -> u32 {
731 self.lanes
732 .iter()
733 .filter_map(|l| l.clips.last().map(Clip::end))
734 .max()
735 .unwrap_or(0)
736 }
737
738 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
739 /// to lay clips out. Gaps show up as the holes between consecutive entries.
740 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
741 self.lane_spans(Lane::V1)
742 }
743
744 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
745 self.lane(lane).iter().map(|c| (c.start, c.len())).collect()
746 }
747
748 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
749 /// and past the end -- [`Project::span_at`] is the version that tells those
750 /// two apart.
751 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
752 let clips = self.lane(lane);
753 let idx = at(clips, timeline_frame)?;
754 Some((
755 idx,
756 clips[idx].in_frame + (timeline_frame - clips[idx].start),
757 ))
758 }
759
760 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
761 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
762 self.map(Lane::V1, timeline_frame)
763 }
764
765 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
766 /// it, or the gap running to the next clip (or to the end of the timeline,
767 /// which is where a lane shorter than its neighbour keeps showing black).
768 /// `None` at or past the end of the timeline, which is the only "nothing
769 /// left" there is.
770 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
771 let total = self.timeline_frames();
772 if timeline_frame >= total {
773 return None;
774 }
775 let clips = self.lane(lane);
776 Some(match at(clips, timeline_frame) {
777 Some(idx) => Span {
778 start: timeline_frame,
779 len: clips[idx].end() - timeline_frame,
780 from: Some((
781 clips[idx].source,
782 clips[idx].in_frame + (timeline_frame - clips[idx].start),
783 )),
784 },
785 None => Span {
786 start: timeline_frame,
787 // The next placement, or the end of the timeline: a gap is
788 // bounded by what comes after it, never by its own bookkeeping.
789 len: clips
790 .iter()
791 .find(|c| c.start > timeline_frame)
792 .map_or(total, |c| c.start)
793 - timeline_frame,
794 from: None,
795 },
796 })
797 }
798
799 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
800 /// gaps included -- the whole play list, which is what an export walks.
801 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
802 let mut out = Vec::new();
803 let mut t = timeline_frame;
804 while let Some(span) = self.span_at(lane, t) {
805 t = span.end();
806 out.push(span);
807 }
808 out
809 }
810
811 /// What the *composite* shows from `timeline_frame` on -- the answer
812 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
813 /// video lane by one rule: **the topmost lane with a clip there wins**, and
814 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
815 /// (the usual overlay convention). A frame no video lane covers is a gap,
816 /// which is black however many lanes are above or below it.
817 ///
818 /// No blending, so exactly one lane is visible at a time and the composite
819 /// is itself a span list -- which is why one decoder plays it, the same one
820 /// a single-lane timeline uses, rather than N running at once.
821 ///
822 /// The span is cut short wherever a *higher* lane's clip starts, because
823 /// from that frame on a different lane wins; that is what makes walking
824 /// [`composite_spans_from`](Project::composite_spans_from) correct.
825 ///
826 /// ponytail: alpha, opacity or any blend mode makes this untrue -- two
827 /// lanes would then be visible in one frame and the caller needs a decoder
828 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
829 /// (this same walk, per lane) feeding N decoders.
830 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
831 let total = self.timeline_frames();
832 if timeline_frame >= total {
833 return None;
834 }
835 let video = self.video_lanes();
836 // The last covering lane is the winner; only the lanes above it can
837 // interrupt what it shows.
838 let winner = video
839 .iter()
840 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
841 let (from, until) = match winner {
842 Some(i) => {
843 let clips = self.lane(video[i]);
844 let idx = at(clips, timeline_frame).expect("just found above");
845 (
846 Some((
847 clips[idx].source,
848 clips[idx].in_frame + (timeline_frame - clips[idx].start),
849 )),
850 clips[idx].end(),
851 )
852 }
853 // Nothing covers it: black until something above the floor starts.
854 None => (None, total),
855 };
856 let takeover = video[winner.map_or(0, |i| i + 1)..]
857 .iter()
858 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
859 .map(|c| c.start)
860 .min();
861 Some(Span {
862 start: timeline_frame,
863 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
864 from,
865 })
866 }
867
868 /// The video lanes in display order, topmost last -- the order the composite
869 /// rule counts in.
870 fn video_lanes(&self) -> Vec<Lane> {
871 self.lanes()
872 .into_iter()
873 .filter(|l| l.kind == LaneKind::Video)
874 .collect()
875 }
876
877 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
878 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
879 /// index on that lane. `None` over a gap and past the end. What a front-end
880 /// asks to act on "the clip on screen" without re-deriving the rule.
881 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
882 let video = self.video_lanes();
883 let winner = video
884 .iter()
885 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
886 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
887 }
888
889 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
890 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
891 /// answers "the clip on screen"; this answers it per lane, which is what
892 /// walking the lanes for something to select needs.
893 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
894 at(self.lane(lane), timeline_frame)
895 }
896
897 /// How the composite is graded at `timeline_frame`, so the picture playback
898 /// converts and the one an export encodes are graded from one answer.
899 /// `None` over a gap (black is black) and for a clip nobody has graded,
900 /// which is the byte-identical path everywhere.
901 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
902 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
903 self.color_of(lane, idx)
904 }
905
906 /// How the composite meets the project canvas at `timeline_frame`, so the
907 /// picture playback composes and the one an export encodes are placed from
908 /// one answer. `Fit` over a gap, where black is already the canvas.
909 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
910 self.composite_clip_at(timeline_frame)
911 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
912 }
913
914 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
915 /// viewer sees from `timeline_frame` to the end, in order. What an export
916 /// encodes and what playback walks at a clip boundary.
917 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
918 let mut out = Vec::new();
919 let mut t = timeline_frame;
920 while let Some(span) = self.composite_span_at(t) {
921 t = span.end();
922 out.push(span);
923 }
924 out
925 }
926
927 /// Split every lane at `timeline_frame`, so that frame becomes the first
928 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
929 /// (`false`, no change) when no lane has a clip to split there -- at a
930 /// placement's own start, in a gap, and past the end -- all of which would
931 /// produce an empty clip or nothing at all.
932 ///
933 /// Lanes' halves share an id only where they are the *same* span: the lanes
934 /// are edited apart, so the clip being cut here may start (or end)
935 /// somewhere else on another lane, and a group id whose clips disagree
936 /// about their span is not one take (see [`links_are_consistent`], which
937 /// refuses to load one).
938 ///
939 /// Metadata only: no mapping changes, in any lane.
940 pub fn split(&mut self, timeline_frame: u32) -> bool {
941 let cut: Vec<Option<Clip>> = self
942 .lanes
943 .iter()
944 .map(|l| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
945 .collect();
946 if cut.iter().all(Option::is_none) {
947 return false;
948 }
949 self.snapshot();
950 // Each side is its own question: two clips may start together and end
951 // apart, and every lane whose halves do line up stays one take.
952 let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
953 let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();
954 let left = self.group_ids(&starts);
955 let right = self.group_ids(&ends);
956 for ((data, left), right) in self.lanes.iter_mut().zip(left).zip(right) {
957 let Some(idx) = splittable(&data.clips, timeline_frame) else {
958 continue;
959 };
960 let mut tail = data.clips[idx];
961 tail.in_frame += timeline_frame - tail.start;
962 tail.start = timeline_frame;
963 tail.link = right;
964 data.clips[idx].out_frame = tail.in_frame;
965 data.clips[idx].link = left;
966 data.clips.insert(idx + 1, tail);
967 }
968 true
969 }
970
971 /// The inverse of [`split`](Project::split): rejoin the placements that meet
972 /// at `timeline_frame` in every lane and put the result back in one group.
973 /// Only what a split could have produced is rejoined -- the two sides must
974 /// touch on the timeline *and* be consecutive frames of the same source --
975 /// so the clip list comes back exactly as it was and traversal with it.
976 /// `false` when no lane has such a pair. The rejoined clips share one id
977 /// only when they rejoin into the same span, for [`split`](Project::split)'s
978 /// reason.
979 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
980 // What each lane would end up covering, if it joins here at all.
981 let joined: Vec<Option<(u32, u32)>> = self
982 .lanes
983 .iter()
984 .map(|l| {
985 joinable(&l.clips, timeline_frame)
986 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
987 })
988 .collect();
989 if joined.iter().all(Option::is_none) {
990 return false;
991 }
992 self.snapshot();
993 let ids = self.group_ids(&joined);
994 for (data, link) in self.lanes.iter_mut().zip(ids) {
995 let Some(idx) = joinable(&data.clips, timeline_frame) else {
996 continue;
997 };
998 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
999 data.clips[idx].link = link;
1000 data.clips.remove(idx + 1);
1001 }
1002 true
1003 }
1004
1005 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
1006 /// lands on and leaving every other clip exactly where it is -- the
1007 /// per-lane paste. Anything already there is trimmed away (and split in two
1008 /// if `clip` lands inside it), which is what keeps the lane sorted and
1009 /// disjoint; nothing ripples, so a gap before the placement simply stays a
1010 /// gap. Refused only for an empty `clip`.
1011 ///
1012 /// The placement belongs to no group: a clipboard clip carries the link id
1013 /// of the take it was copied from, and placing it twice -- or placing a copy
1014 /// back over the clip it came from -- would put that id on two clips of one
1015 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
1016 /// `None` rather than a fresh id because a one-lane placement has nothing on
1017 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
1018 /// become a group again.
1019 ///
1020 /// Refused for an empty `clip` and for a lane that is not there.
1021 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
1022 if clip.out_frame <= clip.in_frame || self.index(lane).is_none() {
1023 return false;
1024 }
1025 self.snapshot();
1026 let clip = Clip {
1027 start: timeline_frame,
1028 link: None,
1029 ..clip
1030 };
1031 let clips = self.lane_mut(lane).expect("checked above");
1032 clear(clips, clip.start, clip.end());
1033 let idx = clips.partition_point(|c| c.start < clip.start);
1034 clips.insert(idx, clip);
1035 debug_assert!(sorted_disjoint(clips));
1036 true
1037 }
1038
1039 /// Move the clip at `idx` of `from` onto `to`, keeping the timeline frames
1040 /// it covers: the drag that rearranges takes across tracks. One snapshot, so
1041 /// one [`Project::undo`] puts it back where it was.
1042 ///
1043 /// Its group id travels with it, and that is not a desync: a link means
1044 /// "these cover one span on however many lanes" and names no lane at all
1045 /// (see [`links_are_consistent`]), so a picture moved from `V1` to `V2` is
1046 /// still the same take as the sound under it. The span never changes here --
1047 /// only which lane draws it.
1048 ///
1049 /// Refused, changing nothing, for a lane that is not there, an index that is
1050 /// not there, a move onto the lane it is already on, a move across *kinds*
1051 /// (a picture cannot play on an audio lane, and the save it wrote would not
1052 /// open again), and a landing that would touch another clip -- a move that
1053 /// overwrote what it landed on would destroy a take the pointer never named,
1054 /// which is what [`place`](Project::place) may do and a drag may not.
1055 pub fn move_to_lane(&mut self, from: Lane, idx: usize, to: Lane) -> bool {
1056 if from.kind != to.kind || from == to || self.index(to).is_none() {
1057 return false;
1058 }
1059 let Some(clip) = self.lane(from).get(idx).copied() else {
1060 return false;
1061 };
1062 if self
1063 .lane(to)
1064 .iter()
1065 .any(|c| c.start < clip.end() && clip.start < c.end())
1066 {
1067 return false;
1068 }
1069 self.snapshot();
1070 self.lane_mut(from).expect("checked above").remove(idx);
1071 let clips = self.lane_mut(to).expect("checked above");
1072 let at = clips.partition_point(|c| c.start < clip.start);
1073 clips.insert(at, clip);
1074 debug_assert!(sorted_disjoint(clips));
1075 true
1076 }
1077
1078 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1079 /// the drag on a clip's end that makes it play more or less of its source.
1080 /// The rest of the lane stays exactly where it is (nothing ripples), so what
1081 /// a shortened clip leaves behind is a gap and what a lengthened one takes
1082 /// is room that was already empty. One snapshot, so a whole drag is one
1083 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1084 /// sample. Changes the timeline->source mapping: the caller must reseek.
1085 ///
1086 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1087 /// exactly what they played before, which is what makes this a trim and not
1088 /// a slip.
1089 ///
1090 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1091 /// legal means "as far as it goes", and stopping the box there is the
1092 /// affordance. The walls are: one frame of clip always survives, an edge
1093 /// never crosses the neighbouring clip on its own lane, an in-point never
1094 /// walks back past the source's first frame, and an out-point never runs
1095 /// past `source_frames[clip.source]` -- the caller's table of how long each
1096 /// source actually is ([`Project`] does not know, and a clip ending past its
1097 /// file's last frame is a save that will not open again; see
1098 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1099 /// there may not grow at all.
1100 ///
1101 /// Linked clips trim *together*, to one clamped edge: a link is one span on
1102 /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1103 /// from its sound would be a group no save could load. The room is therefore
1104 /// what every member of the group has -- the tightest wall wins.
1105 ///
1106 /// `false`, changing nothing and costing no undo step, for an index that is
1107 /// not there and for an edge that is already where it was asked to go.
1108 pub fn trim(
1109 &mut self,
1110 lane: Lane,
1111 idx: usize,
1112 edge: Edge,
1113 to: u32,
1114 source_frames: &[u32],
1115 ) -> bool {
1116 let (Some((lo, hi)), Some(clip)) = (
1117 self.trim_room(lane, idx, edge, source_frames),
1118 self.lane(lane).get(idx).copied(),
1119 ) else {
1120 return false;
1121 };
1122 let to = to.clamp(lo, hi);
1123 let at = match edge {
1124 Edge::Start => clip.start,
1125 Edge::End => clip.end(),
1126 };
1127 if to == at {
1128 return false;
1129 }
1130 self.snapshot();
1131 for (l, i) in self.group_of(lane, idx).expect("checked above") {
1132 let c = &mut self.lanes[l].clips[i];
1133 match edge {
1134 Edge::Start => {
1135 // Non-negative by `lo`, which is what keeps the in-point on
1136 // the source.
1137 c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1138 c.start = to;
1139 }
1140 Edge::End => c.out_frame = c.in_frame + (to - c.start),
1141 }
1142 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1143 }
1144 true
1145 }
1146
1147 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1148 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1149 /// What a front-end drawing the box *during* a drag asks, so the live width
1150 /// is the width the release will commit and an edge stops under the pointer
1151 /// rather than snapping back. `None` for an index that is not there.
1152 pub fn trim_room(
1153 &self,
1154 lane: Lane,
1155 idx: usize,
1156 edge: Edge,
1157 source_frames: &[u32],
1158 ) -> Option<(u32, u32)> {
1159 let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1160 for (l, i) in self.group_of(lane, idx)? {
1161 let clips = &self.lanes[l].clips;
1162 let c = clips[i];
1163 let (member_lo, member_hi) = match edge {
1164 Edge::Start => (
1165 // Back to the source's own first frame, and never over the
1166 // clip in front of it. Saturating because a clip may hold
1167 // *more* head than the timeline has room for -- a ripple
1168 // delete slides a clip back to frame 0 with its in-point
1169 // wherever the cut left it -- and frame 0 is the other wall.
1170 c.start
1171 .saturating_sub(c.in_frame)
1172 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1173 c.end() - 1,
1174 ),
1175 Edge::End => (
1176 c.start + 1,
1177 // Out to whatever is left of the source, and never over the
1178 // clip behind it.
1179 c.start
1180 .saturating_add(
1181 source_frames
1182 .get(c.source)
1183 .copied()
1184 .unwrap_or(c.out_frame)
1185 .saturating_sub(c.in_frame),
1186 )
1187 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1188 ),
1189 };
1190 lo = lo.max(member_lo);
1191 hi = hi.min(member_hi);
1192 }
1193 // `hi.max(lo)`: for a clip the invariants hold for, the range always
1194 // contains the edge's own place, and a caller's wrong `source_frames`
1195 // must not become an empty range (or a panicking `clamp`) here.
1196 Some((lo, hi.max(lo)))
1197 }
1198
1199 /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1200 /// whatever carries its link on the other lanes -- as `(lane storage index,
1201 /// clip index)` pairs. `None` for an index that is not there.
1202 fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1203 let clip = *self.lane(lane).get(idx)?;
1204 Some(match clip.link {
1205 Some(link) => self
1206 .lanes
1207 .iter()
1208 .enumerate()
1209 .filter_map(|(l, data)| {
1210 Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1211 })
1212 .collect(),
1213 None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1214 })
1215 }
1216
1217 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
1218 /// new group, pushing everything from there on later by its length in
1219 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
1220 /// the clip it lands in is split around it; at or past the end of the
1221 /// timeline it is appended, because a paste means "put it here", not "put it
1222 /// here and leave black in front".
1223 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
1224 ///
1225 /// `V1` and `A1` and no other lane, because a take is one picture and one
1226 /// sound: copying it onto every lane there is would play the same audio
1227 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
1228 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
1229 /// video lane it is a clip that decodes to nothing, and a save carrying one
1230 /// does not open again. The room is still opened everywhere, or the lanes it
1231 /// was not inserted into would slide out of step with the ones it was.
1232 ///
1233 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
1234 /// Changes the timeline->source mapping: the caller must reseek. Refused for
1235 /// an empty `clip` and for one naming a source that is not there (both of
1236 /// which the public fields let a caller build), and for a paste whose ripple
1237 /// would push a clip past the last frame there is -- nothing is changed by
1238 /// any of them.
1239 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
1240 let Some(source) = self.sources.get(clip.source) else {
1241 return false;
1242 };
1243 if clip.out_frame <= clip.in_frame {
1244 return false;
1245 }
1246 let audio_only = crate::is_audio(&source.path);
1247 let at = timeline_frame.min(self.timeline_frames());
1248 let len = clip.len();
1249 // Room for it: `open_room` adds `len` to every start from `at` on, and a
1250 // hand-written file may hold a clip that ends at the very last frame
1251 // (`edith::check` permits `start + len == u32::MAX`). Refused here
1252 // rather than wrapped there -- a wrapped start lands *behind* the clip
1253 // it belongs after, which is an overlap no save will read back.
1254 if at.checked_add(len).is_none()
1255 || self
1256 .lanes
1257 .iter()
1258 .flat_map(|l| &l.clips)
1259 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
1260 {
1261 return false;
1262 }
1263 self.snapshot();
1264 let clip = Clip {
1265 start: at,
1266 link: Some(self.new_link()),
1267 ..clip
1268 };
1269 // Only lanes that can play the source: a file with no picture belongs on
1270 // an audio lane and nowhere else, exactly as `place_stream_at` decides
1271 // it for an import. On a video lane it would decode to nothing, and the
1272 // save it wrote would not open again.
1273 let kinds: &[LaneKind] = if audio_only {
1274 &[LaneKind::Audio]
1275 } else {
1276 &[LaneKind::Video, LaneKind::Audio]
1277 };
1278 let takes: Vec<usize> = kinds
1279 .iter()
1280 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
1281 .collect();
1282 for (i, data) in self.lanes.iter_mut().enumerate() {
1283 open_room(&mut data.clips, at, clip.len());
1284 if takes.contains(&i) {
1285 let idx = data.clips.partition_point(|c| c.start < at);
1286 data.clips.insert(idx, clip);
1287 }
1288 debug_assert!(sorted_disjoint(&data.clips));
1289 }
1290 true
1291 }
1292
1293 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
1294 /// silence, and nothing else moves. Refused only for an out-of-range index
1295 /// (which a lane that is not there always is) -- lifting the last placement
1296 /// there is leaves an *empty* timeline, which is a state the project holds
1297 /// like any other and an undo brings back.
1298 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
1299 if idx >= self.lane(lane).len() {
1300 return false;
1301 }
1302 self.snapshot();
1303 self.lane_mut(lane).expect("checked above").remove(idx);
1304 true
1305 }
1306
1307 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
1308 /// the hole: everything after slides back by `len`. The rippling delete --
1309 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
1310 /// empty range; a delete that leaves nothing behind empties the timeline,
1311 /// which is a state like any other and one undo away.
1312 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
1313 if len == 0 {
1314 return false;
1315 }
1316 // Nothing reaches past `at`: there is nothing to cut and nothing to
1317 // slide back, and a delete that changes nothing must not cost an undo
1318 // step (see [`snapshot`](Project::snapshot)).
1319 if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) {
1320 return false;
1321 }
1322 self.snapshot();
1323 for data in &mut self.lanes {
1324 clear(&mut data.clips, at, at + len);
1325 for c in data.clips.iter_mut().filter(|c| c.start >= at) {
1326 c.start -= len;
1327 }
1328 debug_assert!(sorted_disjoint(&data.clips));
1329 }
1330 true
1331 }
1332
1333 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
1334 /// -- the whole-group delete a single-lane front-end means. `false` for a
1335 /// bad index. Changes the mapping: the caller must reseek.
1336 pub fn delete(&mut self, idx: usize) -> bool {
1337 self.delete_in(Lane::V1, idx)
1338 }
1339
1340 /// [`delete`](Project::delete) for the lane the clip was picked on: the
1341 /// clip's own span is cut out of *every* lane, so a take deletes whole from
1342 /// whichever half of it was clicked. `false` for a bad index, and for a lane
1343 /// that is not there.
1344 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
1345 let Some(clip) = self.lane(lane).get(idx).copied() else {
1346 return false;
1347 };
1348 self.ripple_delete(clip.start, clip.len())
1349 }
1350
1351 /// Restore every lane from before the last successful edit -- the clips and
1352 /// the lane list both. `false` when there is nothing left to undo.
1353 pub fn undo(&mut self) -> bool {
1354 match self.history.pop() {
1355 Some(prev) => {
1356 self.lanes = prev;
1357 true
1358 }
1359 None => false,
1360 }
1361 }
1362
1363 /// Half-open `(source, start, end)` segments in *source* seconds, from
1364 /// `timeline_frame` to the end of the timeline -- the play list for the
1365 /// audio worker, read off **`A1`**. A `None` source is a gap: the
1366 /// worker synthesises that many seconds of silence, which is what keeps the
1367 /// audio master clock counting across a hole instead of stalling on it.
1368 /// The first entry is partial when the position is mid-clip. Empty when the
1369 /// position is past the end or `fps` is not usable.
1370 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
1371 self.lane_segments_from(Lane::A1, timeline_frame, fps)
1372 }
1373
1374 /// [`segments_from`](Project::segments_from) for a named lane.
1375 pub fn lane_segments_from(
1376 &self,
1377 lane: Lane,
1378 timeline_frame: u32,
1379 fps: f64,
1380 ) -> Vec<(Option<usize>, f64, f64)> {
1381 if !(fps.is_finite() && fps > 0.0) {
1382 return Vec::new();
1383 }
1384 self.spans_from(lane, timeline_frame)
1385 .iter()
1386 .map(|span| match span.from {
1387 // A clip's window is in *source* seconds: where in the file it
1388 // reads from, which a delete before it never shifts.
1389 Some((source, in_frame)) => (
1390 Some(source),
1391 f64::from(in_frame) / fps,
1392 f64::from(in_frame + span.len) / fps,
1393 ),
1394 // A gap has no file, so all it can say is how long it is.
1395 None => (None, 0.0, f64::from(span.len) / fps),
1396 })
1397 .collect()
1398 }
1399
1400 /// One play list per audio lane that *holds* something, in display order --
1401 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
1402 /// what an export asks how many lanes it would have to mix.
1403 ///
1404 /// Never empty: a timeline whose audio lanes are all empty (or which has no
1405 /// audio lane at all) still yields one all-gap list, so it plays silence
1406 /// against a master clock exactly as it did before there were lanes to
1407 /// count. Lanes with nothing on them are left out rather than mixed in as
1408 /// silence: they would cost a decode thread each and add zero.
1409 pub fn audio_segments_from(
1410 &self,
1411 timeline_frame: u32,
1412 fps: f64,
1413 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
1414 self.audio_lanes()
1415 .into_iter()
1416 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
1417 .collect()
1418 }
1419
1420 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
1421 /// builds a play list for, in the same order. Public because everything
1422 /// asked per audio lane -- which clip a segment's equalizer belongs to,
1423 /// which lane an mp4 export would copy -- has to read the very list the
1424 /// sound comes off, or the two answers drift apart (which is exactly how an
1425 /// `A2`-only project once exported silently, ledger).
1426 pub fn audio_lanes(&self) -> Vec<Lane> {
1427 let lanes: Vec<Lane> = self
1428 .lanes()
1429 .into_iter()
1430 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
1431 .collect();
1432 match lanes.is_empty() {
1433 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
1434 // no sound still plays silence against the master clock.
1435 true => vec![Lane::A1],
1436 false => lanes,
1437 }
1438 }
1439
1440 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
1441 /// segments plays through: the same lanes in the same order, one entry per
1442 /// segment, `None` where the segment is a gap or its clip plays flat.
1443 ///
1444 /// A parallel list rather than a fourth element of the segment tuple: that
1445 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
1446 /// and an effect is not part of *which samples* a segment names. A short
1447 /// list therefore means "flat from here on" rather than a length mismatch --
1448 /// see [`crate::AudioSession::open_mixed_streams_eq`].
1449 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
1450 self.audio_lanes()
1451 .into_iter()
1452 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
1453 .collect()
1454 }
1455
1456 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
1457 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
1458 /// same walk, same `fps` refusal, so the two lists cannot come out different
1459 /// lengths.
1460 pub fn lane_eqs_from(
1461 &self,
1462 lane: Lane,
1463 timeline_frame: u32,
1464 fps: f64,
1465 ) -> Vec<Option<EqParams>> {
1466 if !(fps.is_finite() && fps > 0.0) {
1467 return Vec::new();
1468 }
1469 self.spans_from(lane, timeline_frame)
1470 .iter()
1471 // A span off a clip covers that clip's frames and no others, so its
1472 // own start names the clip -- the index a [`Span`] does not carry.
1473 .map(|span| {
1474 self.map(lane, span.start)
1475 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
1476 })
1477 .collect()
1478 }
1479
1480 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
1481 /// it has decided it will succeed -- a refusal must not cost an undo step.
1482 fn snapshot(&mut self) {
1483 self.history.push(self.lanes.clone());
1484 }
1485
1486 fn new_link(&mut self) -> u32 {
1487 let id = self.next_link;
1488 self.next_link = self.next_link.saturating_add(1);
1489 id
1490 }
1491
1492 /// One fresh group id per *distinct* key, in lane order, and `None` where a
1493 /// lane has no key -- how [`split`](Project::split) and
1494 /// [`regroup`](Project::regroup) hand out ids across however many lanes.
1495 /// Lanes sharing a key end up sharing an id, which is exactly the rule
1496 /// [`links_are_consistent`] enforces: one id, one span.
1497 fn group_ids<K: PartialEq>(&mut self, keys: &[Option<K>]) -> Vec<Option<u32>> {
1498 // Linear, over a handful of lanes: a hash of a lane list would cost
1499 // more than it saves and would not be deterministic for free.
1500 let mut seen: Vec<(&K, u32)> = Vec::new();
1501 let mut out = Vec::with_capacity(keys.len());
1502 for key in keys {
1503 out.push(
1504 key.as_ref()
1505 .map(|k| match seen.iter().find(|(other, _)| *other == k) {
1506 Some(&(_, id)) => id,
1507 None => {
1508 let id = self.new_link();
1509 seen.push((k, id));
1510 id
1511 }
1512 }),
1513 );
1514 }
1515 out
1516 }
1517}
1518
1519/// The handle of every lane, in storage order -- the one definition of what
1520/// [`Lane::ord`] counts.
1521fn handles(lanes: &[LaneData]) -> Vec<Lane> {
1522 let (mut video, mut audio) = (0, 0);
1523 lanes
1524 .iter()
1525 .map(|l| match l.kind {
1526 LaneKind::Video => {
1527 video += 1;
1528 Lane::new(LaneKind::Video, video - 1)
1529 }
1530 LaneKind::Audio => {
1531 audio += 1;
1532 Lane::new(LaneKind::Audio, audio - 1)
1533 }
1534 })
1535 .collect()
1536}
1537
1538/// Index of the clip covering `frame`, or `None` for a gap or past the end.
1539/// Binary search: the sorted-disjoint invariant is what makes it legal.
1540fn at(clips: &[Clip], frame: u32) -> Option<usize> {
1541 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
1542 (frame < clips[idx].end()).then_some(idx)
1543}
1544
1545/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
1546/// there would cut in two. A placement's own first frame is not inside it.
1547fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
1548 let idx = at(clips, frame)?;
1549 (frame > clips[idx].start).then_some(idx)
1550}
1551
1552/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
1553/// rejoin: they must touch there, and be consecutive frames of one source.
1554fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
1555 let idx = clips.iter().position(|c| c.end() == frame)?;
1556 let next = clips.get(idx + 1)?;
1557 (next.start == frame
1558 && next.source == clips[idx].source
1559 && next.in_frame == clips[idx].out_frame)
1560 .then_some(idx)
1561}
1562
1563/// The lane invariant: sorted by `start`, no two placements overlapping, no
1564/// empty placement. Checked at every constructor and asserted after every
1565/// mutation -- the offset model is only tractable while it holds.
1566/// The one thing an equalizer setting may not be: a value the text format
1567/// cannot write and read back as itself. Checked wherever params come in, so
1568/// what an edit produces is always what a save writes and a load reads.
1569fn finite(params: &EqParams) -> bool {
1570 params
1571 .bands
1572 .iter()
1573 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
1574}
1575
1576/// The same for a colour grade: [`crate::color`] itself falls back to identity
1577/// on a non-finite value, but a value that cannot be written and read back as
1578/// itself has no business reaching the model.
1579fn color_finite(p: &ColorParams) -> bool {
1580 p.brightness.is_finite()
1581 && p.contrast.is_finite()
1582 && p.saturation.is_finite()
1583 && p.tint.is_finite()
1584}
1585
1586fn sorted_disjoint(clips: &[Clip]) -> bool {
1587 clips.iter().all(|c| c.out_frame > c.in_frame)
1588 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
1589}
1590
1591/// The grouping invariant, checked in release at [`Project::from_parts`] and
1592/// asserted by the tests after every edit: a link id names **at most one** clip
1593/// per lane, and every clip carrying it covers the same timeline span -- that is
1594/// all "these move together" can mean.
1595///
1596/// Deliberately *not* a pairing of two lanes: with N lanes a take may run on
1597/// `V1`, `V2` and `A1` at once, and the rule that makes an id meaningful is span
1598/// identity, not which lane (or which `ord`) the partner sits on. Two lanes are
1599/// the case where it reads as "the picture and its sound".
1600///
1601/// A link no other lane carries is legal and is not an error: lifting one half
1602/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
1603/// timeline has to load again.
1604fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
1605 let handles = handles(lanes);
1606 for (data, lane) in lanes.iter().zip(&handles) {
1607 for (i, c) in data.clips.iter().enumerate() {
1608 let Some(id) = c.link else { continue };
1609 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
1610 return Err(
1611 format!("link {id} names two clips in the {} lane", lane.label()).into(),
1612 );
1613 }
1614 }
1615 }
1616 // First lane to carry an id fixes the span every other lane must agree on.
1617 let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();
1618 for (data, &lane) in lanes.iter().zip(&handles) {
1619 for c in &data.clips {
1620 let Some(id) = c.link else { continue };
1621 match seen.iter().find(|(other, ..)| *other == id) {
1622 Some(&(_, first, start, end)) => {
1623 if (start, end) != (c.start, c.end()) {
1624 return Err(format!(
1625 "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",
1626 first.label(),
1627 c.start,
1628 c.end(),
1629 lane.label()
1630 )
1631 .into());
1632 }
1633 }
1634 None => seen.push((id, lane, c.start, c.end())),
1635 }
1636 }
1637 }
1638 Ok(())
1639}
1640
1641/// Removes the timeline frames `[start, end)` from `clips`: placements inside
1642/// it go, one straddling it is split in two, one overlapping an edge is
1643/// trimmed. Source frames follow the trim, so what is left plays what it always
1644/// played. Leaves the lane sorted and disjoint.
1645///
1646/// A piece the hole cut is no longer the take its group id names -- and both
1647/// halves of a straddled placement carrying that id would be the same id twice
1648/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
1649fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
1650 let mut out = Vec::with_capacity(clips.len() + 1);
1651 for c in clips.drain(..) {
1652 // Disjoint from the hole: untouched.
1653 if c.end() <= start || c.start >= end {
1654 out.push(c);
1655 continue;
1656 }
1657 // The head that survives in front of the hole.
1658 if c.start < start {
1659 out.push(Clip {
1660 out_frame: c.in_frame + (start - c.start),
1661 link: None,
1662 ..c
1663 });
1664 }
1665 // ...and the tail behind it, which keeps reading where it would have.
1666 if c.end() > end {
1667 out.push(Clip {
1668 start: end,
1669 in_frame: c.in_frame + (end - c.start),
1670 link: None,
1671 ..c
1672 });
1673 }
1674 }
1675 *clips = out;
1676}
1677
1678/// Slides everything from `at` on later by `len`, splitting a placement that
1679/// straddles `at` so the two halves end up on either side of the hole. The
1680/// insert half of a rippling paste. The two halves lose the group id for the
1681/// reason [`clear`] gives.
1682fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
1683 if let Some(idx) = splittable(clips, at) {
1684 let mut tail = clips[idx];
1685 tail.in_frame += at - tail.start;
1686 tail.start = at;
1687 tail.link = None;
1688 clips[idx].out_frame = tail.in_frame;
1689 clips[idx].link = None;
1690 clips.insert(idx + 1, tail);
1691 }
1692 for c in clips.iter_mut().filter(|c| c.start >= at) {
1693 c.start += len;
1694 }
1695}
1696
1697/// Absolute, symlink-resolved when the file is reachable; the path as given
1698/// when it is not -- an unreadable path still deserves an index, it simply
1699/// dedups by spelling.
1700fn canonical(path: &Path) -> PathBuf {
1701 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1702}
1703
1704#[cfg(test)]
1705mod tests {
1706 use super::*;
1707
1708 const FPS: f64 = 30.0;
1709 /// Never opened -- `Project` is pure data, so a path that does not exist is
1710 /// simply a path that dedups by spelling.
1711 const FILE: &str = "/nonexistent/a.mp4";
1712 const FILE2: &str = "/nonexistent/b.mp4";
1713
1714 /// A contiguous placement, group id ignored: what most assertions compare.
1715 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
1716 Clip {
1717 start,
1718 in_frame,
1719 out_frame,
1720 source,
1721 link: None,
1722 eq: None,
1723 color: None,
1724 fit: FitPolicy::default(),
1725 }
1726 }
1727
1728 /// A recognisable equalizer setting: one peak band, `n` telling two of them
1729 /// apart -- which is what makes the table's dedup and its prune visible.
1730 fn band_at(n: u32) -> EqParams {
1731 EqParams {
1732 bands: vec![crate::eq::Band {
1733 freq_hz: 1000.0,
1734 gain_db: f64::from(n) as f32 * 1.5,
1735 q: 0.707,
1736 kind: crate::eq::BandKind::Peak,
1737 }],
1738 }
1739 }
1740
1741 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
1742 /// for the colour table.
1743 fn grade_at(n: u32) -> ColorParams {
1744 ColorParams {
1745 brightness: f64::from(n) as f32 * 0.05,
1746 ..Default::default()
1747 }
1748 }
1749
1750 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
1751 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
1752 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
1753 }
1754
1755 /// Every lane with its group ids blanked, for comparing shape.
1756 fn shape(p: &Project) -> Vec<Vec<Clip>> {
1757 p.lanes()
1758 .into_iter()
1759 .map(|l| {
1760 p.lane(l)
1761 .iter()
1762 .map(|c| Clip { link: None, ..*c })
1763 .collect()
1764 })
1765 .collect()
1766 }
1767
1768 /// The *source frame* every timeline frame reads, per lane -- the traversal
1769 /// a player performs. Deliberately not the clip index: a split changes which
1770 /// clip a frame belongs to, and nothing else.
1771 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
1772 (0..p.timeline_frames() + 2)
1773 .map(|f| {
1774 p.lanes()
1775 .into_iter()
1776 .map(|l| p.map(l, f).map(|(_, source)| source))
1777 .collect()
1778 })
1779 .collect()
1780 }
1781
1782 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
1783 /// fixture. Built through `split` so the constructor path is exercised too.
1784 fn three() -> Project {
1785 let mut p = Project::single(FILE, 9);
1786 assert!(p.split(3));
1787 assert!(p.split(5));
1788 assert_eq!(
1789 shape(&p),
1790 [
1791 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
1792 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
1793 ]
1794 );
1795 p
1796 }
1797
1798 #[test]
1799 fn single_is_the_whole_file_on_both_lanes() {
1800 let p = Project::single(FILE, 150);
1801 assert_eq!(p.clips().len(), 1);
1802 assert_eq!(p.lane(Lane::A1).len(), 1);
1803 assert_eq!(p.timeline_frames(), 150);
1804 assert_eq!(p.clip_spans(), vec![(0, 150)]);
1805 // grouped: video and audio carry the same link
1806 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
1807 assert!(p.clips()[0].link.is_some());
1808 // degenerate mapping: timeline == source
1809 assert_eq!(p.map_timeline(0), Some((0, 0)));
1810 assert_eq!(p.map_timeline(149), Some((0, 149)));
1811 assert_eq!(p.map_timeline(150), None);
1812 // never-empty invariant survives a bogus frame count
1813 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
1814 }
1815
1816 #[test]
1817 fn split_cuts_every_lane_and_regroups_it_back() {
1818 let mut p = Project::single(FILE, 9);
1819 let before = traversal(&p);
1820 let before_shape = shape(&p);
1821
1822 assert!(p.split(4));
1823 for l in p.lanes() {
1824 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
1825 }
1826 // The two sides are two groups, one per side, matching across the lanes.
1827 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
1828 assert_eq!(v[0].link, a[0].link);
1829 assert_eq!(v[1].link, a[1].link);
1830 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
1831 // A split changes no mapping, in either lane.
1832 assert_eq!(traversal(&p), before, "a split moves nothing");
1833
1834 assert!(p.regroup(4), "the inverse rejoins them");
1835 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
1836 assert_eq!(traversal(&p), before);
1837 assert_eq!(
1838 p.lane(Lane::V1)[0].link,
1839 p.lane(Lane::A1)[0].link,
1840 "and the rejoined clip is one group again"
1841 );
1842 }
1843
1844 #[test]
1845 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
1846 let mut p = three();
1847 let before = shape(&p);
1848 assert!(!p.split(0), "timeline 0 has nothing before it");
1849 assert!(!p.split(3), "existing boundary");
1850 assert!(!p.split(5), "existing boundary");
1851 assert!(!p.split(9), "one past the last frame");
1852 assert!(!p.split(1_000));
1853 assert_eq!(shape(&p), before);
1854 // one undo lands before the *second* split, so the refusals pushed nothing
1855 assert!(p.undo());
1856 assert_eq!(p.clips().len(), 2, "refused splits push no history");
1857
1858 // ...and a frame that is a gap in both lanes has nothing to split.
1859 let mut p = three();
1860 assert!(p.lift(Lane::V1, 1));
1861 assert!(p.lift(Lane::A1, 1));
1862 assert!(!p.split(4), "a gap is not a clip");
1863 }
1864
1865 #[test]
1866 fn regroup_refuses_what_a_split_could_not_have_made() {
1867 let mut p = three();
1868 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
1869 assert!(p.regroup(5));
1870 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
1871 // A boundary with a gap on one side, and one where the sources do not
1872 // meet, are both refused.
1873 let mut p = three();
1874 assert!(p.lift(Lane::V1, 1));
1875 assert!(p.lift(Lane::A1, 1));
1876 assert!(!p.regroup(3), "nothing starts at 3 any more");
1877 let mut p = three();
1878 for l in p.lanes() {
1879 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
1880 }
1881 assert!(!p.regroup(3), "source 100 does not follow source 3");
1882 assert!(!p.regroup(0), "nothing ends at 0");
1883 assert!(!p.regroup(1_000));
1884 }
1885
1886 #[test]
1887 fn map_and_spans_sweep_every_boundary() {
1888 let p = three();
1889 assert_eq!(p.timeline_frames(), 9);
1890 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
1891 // contiguous source here, so the clip index is what actually moves
1892 let expect = [
1893 (0, (0, 0)),
1894 (1, (0, 1)),
1895 (2, (0, 2)),
1896 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
1897 (4, (1, 4)),
1898 (5, (2, 5)),
1899 (6, (2, 6)),
1900 (7, (2, 7)),
1901 (8, (2, 8)),
1902 ];
1903 for (t, want) in expect {
1904 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
1905 }
1906 assert_eq!(p.map_timeline(9), None);
1907 // A span is the rest of the clip from where it was asked about.
1908 assert_eq!(
1909 p.span_at(Lane::V1, 6),
1910 Some(Span {
1911 start: 6,
1912 len: 3,
1913 from: Some((0, 6))
1914 })
1915 );
1916 assert_eq!(p.span_at(Lane::V1, 9), None);
1917 }
1918
1919 /// The fit policy is one byte *in* the clip rather than an index into a
1920 /// table like the eq and the grade: there is nothing for a table to share.
1921 /// It costs the clip nothing at all -- the fields before it (a `usize`
1922 /// source and two `Option<u16>`s) already left the struct padded to 40
1923 /// bytes, and the byte landed in that padding. This is the assert that says
1924 /// so: a clip that grew a word grew every undo snapshot and every clipboard
1925 /// copy with it.
1926 #[test]
1927 fn a_fit_policy_costs_the_clip_no_word() {
1928 assert_eq!(
1929 std::mem::size_of::<Clip>(),
1930 40,
1931 "Clip changed size: {} bytes",
1932 std::mem::size_of::<Clip>()
1933 );
1934 }
1935
1936 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
1937 /// anything in `three()` so it is recognisable wherever it lands.
1938 const PASTED: Clip = Clip {
1939 start: 0,
1940 in_frame: 100,
1941 out_frame: 102,
1942 source: 0,
1943 link: None,
1944 eq: None,
1945 color: None,
1946 fit: FitPolicy::Fit,
1947 };
1948
1949 #[test]
1950 fn paste_mid_clip_splits_around_it() {
1951 let mut p = three();
1952 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
1953 assert_eq!(p.timeline_frames(), 11);
1954 assert_eq!(
1955 shape(&p)[0],
1956 vec![
1957 clip(0, 0, 3, 0),
1958 clip(3, 3, 5, 0),
1959 clip(5, 5, 6, 0),
1960 clip(6, 100, 102, 0),
1961 clip(8, 6, 9, 0),
1962 ]
1963 );
1964 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
1965 // The pasted frames are exactly where they were asked for, and the
1966 // split-off remainder resumes after them.
1967 assert_eq!(p.map_timeline(6), Some((3, 100)));
1968 assert_eq!(p.map_timeline(7), Some((3, 101)));
1969 assert_eq!(p.map_timeline(8), Some((4, 6)));
1970 }
1971
1972 #[test]
1973 fn paste_at_boundary_zero_and_end() {
1974 let mut p = three();
1975 assert!(p.paste(3, PASTED), "existing boundary: no split");
1976 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
1977 assert_eq!(p.map_timeline(3), Some((1, 100)));
1978
1979 let mut p = three();
1980 assert!(p.paste(0, PASTED));
1981 assert_eq!(p.map_timeline(0), Some((0, 100)));
1982 assert_eq!(p.map_timeline(2), Some((1, 0)));
1983
1984 // At the end and past it both append -- a paste never leaves black in
1985 // front of itself; `place` is the call that makes a gap.
1986 let mut p = three();
1987 assert!(p.paste(9, PASTED));
1988 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
1989 assert!(p.paste(1_000, PASTED));
1990 assert_eq!(p.timeline_frames(), 13);
1991
1992 // An empty clip is the one thing refused, and it pushes no history.
1993 let mut p = three();
1994 assert!(!p.paste(4, clip(0, 7, 7, 0)));
1995 assert_eq!(p.clips().len(), 3);
1996 }
1997
1998 /// The data-loss paste: a clip of a source with no picture used to land on
1999 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
2000 /// carried it was refused on the way back in ("a box with a larger size").
2001 #[test]
2002 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
2003 let mut p = three();
2004 let wav = p.import("/nonexistent/song.wav", 0);
2005 let copied = Clip {
2006 source: wav,
2007 ..PASTED
2008 };
2009 assert!(p.paste(3, copied));
2010 // The room is opened on every lane, or the two would slide apart...
2011 assert_eq!(p.timeline_frames(), 11);
2012 assert_eq!(
2013 shape(&p)[0],
2014 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
2015 "the video lane got room and nothing else"
2016 );
2017 // ...but the clip itself only reaches the lane that can play it.
2018 assert_eq!(
2019 shape(&p)[1],
2020 vec![
2021 clip(0, 0, 3, 0),
2022 clip(3, 100, 102, wav),
2023 clip(5, 3, 5, 0),
2024 clip(7, 5, 9, 0)
2025 ]
2026 );
2027 // A source with a picture is unchanged: still the grouped pair.
2028 let mut p = three();
2029 assert!(p.paste(3, PASTED));
2030 assert_eq!(shape(&p)[0], shape(&p)[1]);
2031 }
2032
2033 /// A hand-written file may hold a clip that ends at the very last frame
2034 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
2035 /// to wrap its start round to the front of the lane: an overlap in debug, a
2036 /// project no reload would accept in release.
2037 #[test]
2038 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
2039 let far = clip(u32::MAX - 90, 0, 90, 0);
2040 let parts = |c: Clip| {
2041 Project::from_parts(
2042 vec![Source::new(FILE, 0)],
2043 two(vec![c], vec![c]),
2044 Vec::new(),
2045 Vec::new(),
2046 )
2047 .expect("valid parts")
2048 };
2049 let mut p = parts(far);
2050 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
2051 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
2052 assert!(!p.undo(), "...and pushes no history either");
2053 assert!(
2054 !p.paste(u32::MAX, PASTED),
2055 "appending has nowhere to go either: the timeline ends at the last frame"
2056 );
2057 // With room for exactly those frames the same paste is taken.
2058 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
2059 assert!(p.paste(0, PASTED));
2060 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
2061 }
2062
2063 #[test]
2064 fn paste_undoes_in_one_step() {
2065 let mut p = three();
2066 let before = shape(&p);
2067 assert!(p.paste(6, PASTED));
2068 assert!(p.undo());
2069 assert_eq!(shape(&p), before, "a paste is one undo step");
2070 }
2071
2072 #[test]
2073 fn a_copy_outlives_the_clip_it_came_from() {
2074 let mut p = three();
2075 let copied = p.clips()[1]; // [3,5)
2076 assert!(p.delete(1));
2077 // Just a frame range: the source is still on disk either way.
2078 assert!(p.paste(0, copied));
2079 assert_eq!(p.map_timeline(0), Some((0, 3)));
2080 assert_eq!(p.timeline_frames(), 9);
2081 }
2082
2083 #[test]
2084 fn delete_closes_the_gap_on_both_lanes() {
2085 let mut p = three();
2086 assert!(p.delete(1));
2087 assert_eq!(p.timeline_frames(), 7);
2088 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
2089 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
2090 // timeline 3 used to be source 3; the gap closed so it is source 5 now
2091 assert_eq!(p.map_timeline(3), Some((1, 5)));
2092 assert_eq!(p.map_timeline(6), Some((1, 8)));
2093 assert_eq!(p.map_timeline(7), None);
2094 }
2095
2096 #[test]
2097 fn delete_first_last_and_only() {
2098 let mut p = three();
2099 assert!(p.delete(0));
2100 assert_eq!(p.map_timeline(0), Some((0, 3)));
2101 assert_eq!(p.timeline_frames(), 6);
2102
2103 let mut p = three();
2104 assert!(p.delete(2));
2105 assert_eq!(p.timeline_frames(), 5);
2106 assert_eq!(p.map_timeline(4), Some((1, 4)));
2107
2108 assert!(!p.delete(2), "index past the end");
2109 assert!(p.delete(1));
2110 assert!(p.delete(0), "and the last remaining clip goes too");
2111 assert_eq!(p.clips().len(), 0);
2112 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
2113 assert!(!p.delete(0), "there is nothing left to delete");
2114 assert!(p.undo(), "one gesture, one undo");
2115 assert_eq!(p.clips().len(), 1);
2116 }
2117
2118 /// The offset model's point: one lane loses a clip, the other does not move.
2119 #[test]
2120 fn a_lift_leaves_a_gap_and_moves_nothing() {
2121 let mut p = three();
2122 let video_before = shape(&p)[0].clone();
2123 assert!(p.lift(Lane::A1, 1));
2124 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
2125 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
2126 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
2127 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
2128 assert_eq!(p.map(Lane::A1, 4), None);
2129 assert_eq!(
2130 p.span_at(Lane::A1, 3),
2131 Some(Span {
2132 start: 3,
2133 len: 2,
2134 from: None
2135 })
2136 );
2137 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
2138 assert!(p.undo());
2139 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
2140 }
2141
2142 #[test]
2143 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
2144 let mut p = three();
2145 assert!(p.lift(Lane::A1, 2));
2146 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
2147 assert_eq!(
2148 p.span_at(Lane::A1, 5),
2149 Some(Span {
2150 start: 5,
2151 len: 4,
2152 from: None
2153 }),
2154 "the audio lane holds silence to the end of the picture"
2155 );
2156 assert_eq!(p.span_at(Lane::A1, 9), None);
2157 // Every lane covers the timeline exactly, gaps included.
2158 for l in p.lanes() {
2159 let spans = p.spans_from(l, 0);
2160 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
2161 assert_eq!(spans[0].start, 0);
2162 }
2163 }
2164
2165 /// The timeline is emptiable: the last placement comes off like any other,
2166 /// the project holds "nothing on any lane" as a state, and one undo per
2167 /// gesture brings it back.
2168 #[test]
2169 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
2170 let mut p = Project::single(FILE, 9);
2171 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
2172 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
2173 assert_eq!(p.timeline_frames(), 0);
2174 assert_eq!(p.composite_span_at(0), None, "nothing to show");
2175 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
2176 assert!(!p.lift(Lane::A1, 0), "index past the end");
2177 assert!(p.undo(), "and the last lift comes back");
2178 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
2179 // A saved-and-loaded empty timeline is a project like any other, and it
2180 // still names the file its frame rate came from.
2181 assert!(p.lift(Lane::V1, 0));
2182 let (sources, lanes, eq, color) = p.without_orphan_sources();
2183 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
2184 let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
2185 assert_eq!(back.timeline_frames(), 0);
2186 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
2187 }
2188
2189 /// What a keyboard selection walks: one answer per lane, gaps included --
2190 /// the composite's own answer is one lane's and cannot say what the audio
2191 /// lane holds under the same playhead.
2192 #[test]
2193 fn lane_clip_at_answers_for_each_lane_separately() {
2194 let mut p = Project::single(FILE, 9);
2195 assert!(p.split(3), "both lanes split");
2196 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
2197 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
2198 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
2199 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
2200 // A gap on one lane leaves the other's clip selectable there.
2201 assert!(p.lift(Lane::A1, 0));
2202 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
2203 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(0), "indices moved with it");
2204 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
2205 // A lane that is not there is not a panic.
2206 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
2207 }
2208
2209 #[test]
2210 fn place_overwrites_only_its_own_lane() {
2211 let mut p = three();
2212 let audio_before = shape(&p)[1].clone();
2213 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
2214 // is trimmed, nothing shifts.
2215 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
2216 assert_eq!(
2217 shape(&p)[0],
2218 vec![
2219 clip(0, 0, 3, 0),
2220 clip(3, 3, 4, 0),
2221 clip(4, 100, 102, 0),
2222 clip(6, 6, 9, 0),
2223 ]
2224 );
2225 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
2226 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
2227
2228 // Placed inside one clip, it splits it in two.
2229 let mut p = Project::single(FILE, 9);
2230 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
2231 assert_eq!(
2232 shape(&p)[0],
2233 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
2234 );
2235 // ...and placed past the end it makes a gap, which is the whole point.
2236 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
2237 assert_eq!(p.timeline_frames(), 22);
2238 assert_eq!(
2239 p.span_at(Lane::V1, 9),
2240 Some(Span {
2241 start: 9,
2242 len: 11,
2243 from: None
2244 })
2245 );
2246 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
2247 }
2248
2249 /// The drag between tracks: the clip keeps its frames, one undo takes it
2250 /// back, and every way it can be refused leaves the project untouched.
2251 #[test]
2252 fn move_to_lane_keeps_the_frames_and_refuses_the_rest() {
2253 let v2 = Lane::new(LaneKind::Video, 1);
2254 let mut p = three();
2255 assert_eq!(p.add_lane(LaneKind::Video), v2);
2256 let before = shape(&p);
2257
2258 assert!(p.move_to_lane(Lane::V1, 1, v2), "V1's middle clip moves up");
2259 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
2260 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
2261 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
2262 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
2263 // One snapshot: a single undo, and the lane list survives it.
2264 assert!(p.undo());
2265 assert_eq!(shape(&p), before);
2266
2267 // A lane that is not there, the lane it is already on, an index that is
2268 // not there, and a move across kinds: all refused, nothing changed.
2269 let history = p.history.len();
2270 for (from, idx, to) in [
2271 (Lane::V1, 1, Lane::new(LaneKind::Video, 7)),
2272 (Lane::V1, 1, Lane::V1),
2273 (Lane::V1, 9, v2),
2274 (Lane::V1, 1, Lane::A1),
2275 (Lane::A1, 1, v2),
2276 ] {
2277 assert!(!p.move_to_lane(from, idx, to), "{from:?} {idx} -> {to:?}");
2278 }
2279 assert_eq!(shape(&p), before);
2280 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
2281
2282 // Landing on another clip is refused rather than overwriting it: the
2283 // pointer named the lane, never the take already sitting there.
2284 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
2285 assert!(!p.move_to_lane(Lane::V1, 1, v2), "[3,5) would land on it");
2286 assert!(p.move_to_lane(Lane::V1, 0, v2), "[0,3) merely abuts it");
2287 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
2288 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
2289 }
2290
2291 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2292 /// [`three`] cuts up all nine of its frames.
2293 const SRC: &[u32] = &[9];
2294
2295 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2296 /// else on the lane moves, and every wall stops the edge rather than
2297 /// refusing the gesture.
2298 #[test]
2299 fn trimming_the_tail_stops_at_every_wall() {
2300 let mut p = three();
2301
2302 // Pulled in: a gap opens behind it and the clip after it stays put.
2303 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2304 assert_eq!(
2305 shape(&p)[0],
2306 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2307 );
2308 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2309 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2310
2311 // ...and back out, no further than the clip behind it.
2312 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2313 assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2314 assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2315
2316 // One frame of clip always survives, however far back the pointer went.
2317 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2318 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2319
2320 // The last clip has no neighbour, so what stops it is the file: nine
2321 // frames is nine frames.
2322 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2323 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2324 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2325 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2326 // A source nobody told us the length of may not grow at all -- an
2327 // out-point past the end of a file is a save that will not open again.
2328 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2329 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2330 }
2331
2332 /// The head pulled in takes the in-point with it -- what stays plays what it
2333 /// always played -- and stops at the source's own first frame.
2334 #[test]
2335 fn trimming_the_head_moves_the_in_point() {
2336 let mut p = three();
2337 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2338 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2339 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2340 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2341 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2342 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2343 // One frame survives here too.
2344 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2345 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2346
2347 // A clip that does not begin at its source's first frame: its head goes
2348 // back to source frame 0 and not one frame further.
2349 let mut p = Project::single(FILE, 9);
2350 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2351 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2352 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2353 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2354 }
2355
2356 /// A clip whose in-point is *past* its own start -- what a ripple delete
2357 /// leaves, the piece in front of it gone and this one slid back to frame 0
2358 /// carrying the in-point the cut gave it. Its head has more source behind it
2359 /// than the timeline has room for, and the timeline's own first frame is the
2360 /// wall: asking is not an overflow, and the answer is 0.
2361 #[test]
2362 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
2363 let mut p = Project::single(FILE, 9);
2364 assert!(p.split(5));
2365 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
2366 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
2367
2368 assert_eq!(
2369 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
2370 Some((0, 3)),
2371 "back to frame 0 at most, and one frame of clip always survives"
2372 );
2373 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
2374 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2375 assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
2376 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
2377 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
2378 }
2379
2380 /// Linked halves trim as one: a link is one span on however many lanes, so
2381 /// the sound follows the picture's edge -- and the tightest wall of the two
2382 /// is what stops both.
2383 #[test]
2384 fn linked_halves_trim_together() {
2385 let mut p = three();
2386 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2387 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2388
2389 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2390 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2391 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2392 assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2393 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2394 links_are_consistent(&p.lanes).expect("one id per lane, one span");
2395
2396 // Something in the way on the *audio* lane stops the picture's tail as
2397 // well: the group can only go as far as its tightest member.
2398 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2399 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2400 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2401 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2402 links_are_consistent(&p.lanes).expect("still one span");
2403 }
2404
2405 /// A whole drag is one undo step -- the front-end commits once, at the
2406 /// release -- and an edge asked to stay where it is costs none at all.
2407 #[test]
2408 fn a_trim_is_one_undo_step() {
2409 let mut p = three();
2410 let before = shape(&p);
2411 let history = p.history.len();
2412
2413 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2414 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2415 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2416 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2417 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2418 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2419
2420 assert!(p.undo());
2421 assert_eq!(shape(&p), before, "both halves back, in one step");
2422 }
2423
2424 /// A moved half stays in its group: a link names a span, not a lane, so the
2425 /// picture on `V2` is still the same take as the sound under it on `A1`.
2426 #[test]
2427 fn move_to_lane_keeps_the_group() {
2428 let v2 = Lane::new(LaneKind::Video, 1);
2429 let mut p = three();
2430 p.add_lane(LaneKind::Video);
2431 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
2432 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
2433 assert!(p.move_to_lane(Lane::V1, 1, v2));
2434 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
2435 links_are_consistent(&p.lanes).expect("one id per lane, one span");
2436 assert_eq!(
2437 p.lane(v2)[0].start,
2438 p.lane(Lane::A1)[1].start,
2439 "and still covers the same span as its sound"
2440 );
2441 }
2442
2443 #[test]
2444 fn ripple_delete_spans_partial_clips() {
2445 let mut p = three();
2446 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
2447 assert!(p.ripple_delete(2, 4));
2448 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
2449 assert_eq!(shape(&p)[1], shape(&p)[0]);
2450 assert_eq!(p.timeline_frames(), 5);
2451 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
2452 assert!(p.undo());
2453 assert_eq!(shape(&p), shape(&three()));
2454 // One that takes everything is a delete like any other: the timeline
2455 // empties, and the undo it cost brings it back whole.
2456 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
2457 assert_eq!(p.timeline_frames(), 0);
2458 assert!(
2459 !p.ripple_delete(0, 100),
2460 "and a delete with nothing left to take is not an undo step"
2461 );
2462 assert!(p.undo());
2463 assert_eq!(shape(&p), shape(&three()));
2464 }
2465
2466 #[test]
2467 fn undo_restores_exactly() {
2468 let mut p = three();
2469 let after_splits = shape(&p);
2470 assert!(p.delete(1));
2471 assert!(p.undo());
2472 assert_eq!(shape(&p), after_splits);
2473
2474 // walk all the way back through both splits, then run dry
2475 assert!(p.undo());
2476 assert_eq!(p.clips().len(), 2);
2477 assert!(p.undo());
2478 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
2479 assert!(!p.undo(), "empty history");
2480 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
2481 }
2482
2483 /// Undo/redo by hand across a split must never merge two takes into one
2484 /// group by reusing an id.
2485 #[test]
2486 fn group_ids_are_never_reused() {
2487 let mut p = Project::single(FILE, 9);
2488 assert!(p.split(3));
2489 let first = p.clips()[1].link;
2490 assert!(p.undo());
2491 assert!(p.split(5));
2492 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
2493 }
2494
2495 #[test]
2496 fn segments_from_reads_the_audio_lane() {
2497 let p = three();
2498 // mid-clip: partial first segment, whole clips after it
2499 assert_eq!(
2500 p.segments_from(4, FPS),
2501 vec![
2502 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
2503 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
2504 ]
2505 );
2506 // on a boundary: nothing partial
2507 assert_eq!(
2508 p.segments_from(3, FPS),
2509 vec![
2510 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
2511 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
2512 ]
2513 );
2514 // from the top: one entry per clip
2515 assert_eq!(p.segments_from(0, FPS).len(), 3);
2516 // last clip only
2517 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
2518 // past the end / unusable fps
2519 assert!(p.segments_from(9, FPS).is_empty());
2520 assert!(p.segments_from(0, 0.0).is_empty());
2521 assert!(p.segments_from(0, f64::NAN).is_empty());
2522 }
2523
2524 #[test]
2525 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
2526 let mut p = three();
2527 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
2528 assert_eq!(
2529 p.segments_from(0, FPS),
2530 vec![
2531 (Some(0), 0.0, 3.0 / 30.0),
2532 (None, 0.0, 2.0 / 30.0),
2533 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
2534 ]
2535 );
2536 // The list still covers exactly the timeline: that is what stops the
2537 // master clock stalling at the hole.
2538 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
2539 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
2540 // Starting inside the gap trims the silence, not the clip after it.
2541 assert_eq!(
2542 p.segments_from(4, FPS),
2543 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
2544 );
2545 // ...and a lane that is nothing but gap is a run of silence.
2546 assert!(p.lift(Lane::A1, 0));
2547 assert!(p.lift(Lane::A1, 0));
2548 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
2549 }
2550
2551 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
2552 /// of source 0 then [0,4) of source 1.
2553 fn two_sources() -> Project {
2554 let mut p = three();
2555 let s = p.import(FILE2, 0);
2556 assert_eq!(s, 1);
2557 assert!(p.append_clip(s, 4));
2558 p
2559 }
2560
2561 #[test]
2562 fn import_dedups_and_appends() {
2563 let mut p = Project::single(FILE, 9);
2564 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
2565 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
2566 assert_eq!(p.import(FILE2, 0), 1);
2567 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
2568 // ...but the same file on another audio stream is another source: it is
2569 // what a clip names, and a clip plays exactly one stream.
2570 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
2571 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
2572 assert_eq!(p.sources()[2].audio_stream, 1);
2573 assert!(p.append_clip(2, 4), "a stream entry is placeable");
2574 assert!(p.undo());
2575 assert_eq!(p.sources().len(), 3);
2576 assert!(!p.append_clip(3, 5), "unknown source index");
2577 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
2578
2579 // Two spellings of one real file are one source: this is the case the
2580 // raw-path comparison above would get wrong.
2581 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
2582 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
2583 let mut p = Project::single(here, 9);
2584 assert_eq!(p.import(detour, 0), 0);
2585 assert_eq!(p.sources().len(), 1);
2586 }
2587
2588 #[test]
2589 fn append_clip_is_one_undo_step() {
2590 let mut p = two_sources();
2591 assert_eq!(p.timeline_frames(), 13);
2592 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
2593 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
2594 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
2595 assert!(p.undo());
2596 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
2597 assert_eq!(
2598 p.sources().len(),
2599 2,
2600 "the orphan source entry stays -- indexes are forever"
2601 );
2602 // ...and it is still usable, so a redo-by-hand costs no reimport.
2603 assert!(p.append_clip(1, 0));
2604 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
2605 }
2606
2607 #[test]
2608 fn edits_carry_the_source_along() {
2609 let mut p = two_sources();
2610 // A split inside the second source splits into two source-1 clips.
2611 assert!(p.split(11));
2612 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
2613 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
2614
2615 // A source-1 clip pasted into source-0 territory keeps its file, and so
2616 // does the source-0 half that got split off around it.
2617 let copied = p.clips()[4];
2618 assert!(p.paste(1, copied));
2619 assert_eq!(p.clips()[1].source, 1);
2620 assert_eq!(p.clips()[1].in_frame, 2);
2621 assert_eq!(p.clips()[2].source, 0);
2622 assert!(p.undo());
2623 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
2624 }
2625
2626 #[test]
2627 fn segments_from_names_the_source() {
2628 let p = two_sources();
2629 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
2630 assert_eq!(
2631 p.segments_from(4, FPS),
2632 vec![
2633 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
2634 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
2635 (Some(1), 0.0, 4.0 / 30.0),
2636 ]
2637 );
2638 // Mid-clip in source 1: only that source is left.
2639 assert_eq!(
2640 p.segments_from(10, FPS),
2641 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
2642 );
2643 assert!(p.segments_from(13, FPS).is_empty());
2644 // Segments still cover exactly the timeline across the join.
2645 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
2646 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
2647 }
2648
2649 #[test]
2650 fn segments_follow_deletes_and_fps() {
2651 let mut p = three();
2652 assert!(p.delete(0));
2653 // source seconds, not timeline: deleting the head does not shift them
2654 let segs = p.segments_from(0, 25.0);
2655 assert_eq!(
2656 segs,
2657 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
2658 );
2659 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
2660 assert!(
2661 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
2662 "segments must cover exactly the timeline: {played}"
2663 );
2664 }
2665
2666 #[test]
2667 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
2668 // Import a second file, undo it: source 1 is now an orphan.
2669 let mut p = two_sources();
2670 assert!(p.undo());
2671 let (sources, lanes, eq, color) = p.without_orphan_sources();
2672 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
2673 assert!(eq.is_empty(), "and a project with no equalizer writes none");
2674 assert!(color.is_empty(), "nor a colour it never graded with");
2675 assert_eq!(
2676 lanes,
2677 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
2678 "the clips are untouched"
2679 );
2680
2681 // Three sources where only the middle one is orphaned: the survivors
2682 // renumber, and the clips follow.
2683 let mut p = Project::single(FILE, 9);
2684 assert_eq!(p.import(FILE2, 0), 1);
2685 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
2686 assert!(p.append_clip(2, 4));
2687 let (sources, lanes, eq, color) = p.without_orphan_sources();
2688 assert_eq!(
2689 sources,
2690 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
2691 );
2692 assert_eq!(
2693 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
2694 [0, 1]
2695 );
2696 // ...and what comes out is loadable, with the same timeline.
2697 let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
2698 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
2699 assert_eq!(reloaded.sources().len(), 2);
2700 }
2701
2702 /// A clip's equalizer is the clip's: it survives every edit that copies a
2703 /// placement, and it comes back with an undo.
2704 #[test]
2705 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
2706 let mut p = three();
2707 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
2708 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
2709 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
2710 assert!(
2711 p.eq_of(Lane::V1, 0).is_none(),
2712 "one clip, not the lane above"
2713 );
2714
2715 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
2716 assert!(p.split(1));
2717 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
2718 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
2719 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
2720
2721 // A clipboard copy carries it -- onto another lane, at that.
2722 let copied = p.lane(Lane::A1)[1];
2723 assert!(p.place(Lane::V1, 20, copied));
2724 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
2725 assert!(p.undo());
2726 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
2727
2728 // ...and a change to one is one undo step, in both directions.
2729 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
2730 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
2731 assert!(p.undo());
2732 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
2733 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
2734 assert!(p.eq_of(Lane::A1, 0).is_none());
2735 assert!(p.undo());
2736 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
2737
2738 // Two refusals, neither of which costs an undo step.
2739 let mut nan = band_at(1);
2740 nan.bands[0].q = f32::INFINITY;
2741 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
2742 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
2743 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
2744 assert!(p.undo());
2745 assert_eq!(
2746 p.lane(Lane::A1).len(),
2747 3,
2748 "one step back is before the split"
2749 );
2750 assert!(p.undo());
2751 assert!(
2752 p.eq_of(Lane::A1, 0).is_none(),
2753 "and the next is before the setting: the refusals pushed none"
2754 );
2755 }
2756
2757 /// The table is append-only within a session, exactly as the sources are, so
2758 /// an undone setting is still in it -- and a save is where it goes.
2759 #[test]
2760 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
2761 let mut p = three();
2762 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
2763 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
2764 assert!(p.undo(), "back to the first setting");
2765 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
2766
2767 let (_, lanes, eq, _) = p.without_orphan_sources();
2768 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
2769 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
2770 assert_eq!(lanes[0].1[1].eq, None);
2771
2772 // One curve on three clips is one entry: settings that are equal share.
2773 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
2774 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
2775 let (_, lanes, eq, _) = p.without_orphan_sources();
2776 assert_eq!(eq.len(), 1, "equal settings share their entry");
2777 assert_eq!(lanes[1].1[2].eq, Some(0));
2778 reloads(&p, "an equalizer that outlived an undo");
2779 }
2780
2781 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
2782 /// grade is the clip's, through every edit that copies a placement.
2783 #[test]
2784 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
2785 let mut p = three();
2786 assert!(
2787 p.color_of(Lane::V1, 0).is_none(),
2788 "a fresh clip is ungraded"
2789 );
2790 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
2791 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2792 assert!(
2793 p.color_of(Lane::A1, 0).is_none(),
2794 "one clip, not the lane below"
2795 );
2796 assert!(
2797 p.eq_of(Lane::V1, 0).is_none(),
2798 "and a grade is not an equalizer"
2799 );
2800
2801 // Cutting a graded clip must not grade half of it: both halves inherit.
2802 assert!(p.split(1));
2803 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2804 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
2805 assert!(
2806 p.color_of(Lane::V1, 2).is_none(),
2807 "the clip after it is ungraded"
2808 );
2809
2810 // A clipboard copy carries it -- onto another lane, at that.
2811 let copied = p.lane(Lane::V1)[1];
2812 assert!(p.place(Lane::A1, 20, copied));
2813 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
2814 assert!(p.undo());
2815 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
2816
2817 // ...and a change to one is one undo step, in both directions.
2818 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
2819 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
2820 assert!(p.undo());
2821 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2822 assert!(
2823 p.set_color(Lane::V1, 0, None),
2824 "and taking it off is an edit"
2825 );
2826 assert!(p.color_of(Lane::V1, 0).is_none());
2827 assert!(p.undo());
2828 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2829
2830 // Two refusals, neither of which costs an undo step.
2831 let nan = ColorParams {
2832 contrast: f32::NAN,
2833 ..grade_at(1)
2834 };
2835 assert!(
2836 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
2837 "no clip there"
2838 );
2839 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
2840 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2841 assert!(p.undo());
2842 assert_eq!(
2843 p.lane(Lane::V1).len(),
2844 3,
2845 "one step back is before the split"
2846 );
2847 assert!(p.undo());
2848 assert!(
2849 p.color_of(Lane::V1, 0).is_none(),
2850 "and the next is before the grade: the refusals pushed none"
2851 );
2852 }
2853
2854 /// A slider drag is one gesture: the press snapshots, every sample after it
2855 /// only regrades, and the single undo lands on what the clip was *before*
2856 /// the hand touched it -- not one step back down the drag.
2857 #[test]
2858 fn a_whole_colour_drag_undoes_in_one_step() {
2859 let mut p = three();
2860 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
2861 for n in 2..=8 {
2862 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
2863 }
2864 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
2865 assert!(p.undo());
2866 assert!(
2867 p.color_of(Lane::V1, 0).is_none(),
2868 "one undo is the whole gesture, back to ungraded"
2869 );
2870
2871 // The live write refuses what the snapshotting one refuses, and a
2872 // refusal still costs no history either way.
2873 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
2874 assert!(!p.set_color_live(
2875 Lane::V1,
2876 0,
2877 Some(ColorParams {
2878 contrast: f32::NAN,
2879 ..grade_at(1)
2880 })
2881 ));
2882 assert!(p.undo());
2883 assert_eq!(
2884 p.lane(Lane::V1).len(),
2885 2,
2886 "the next step back is the split before the drag: no sample pushed one"
2887 );
2888 }
2889
2890 /// The colour table is append-only within a session, exactly as the eq one
2891 /// is -- and a save is where an undone grade goes.
2892 #[test]
2893 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
2894 let mut p = three();
2895 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
2896 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
2897 assert!(p.undo(), "back to the first grade");
2898 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
2899
2900 let (_, lanes, _, color) = p.without_orphan_sources();
2901 assert_eq!(
2902 color,
2903 vec![grade_at(1)],
2904 "what nothing plays is not written"
2905 );
2906 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
2907 assert_eq!(lanes[0].1[1].color, None);
2908
2909 // One grade on three clips is one entry: settings that are equal share.
2910 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
2911 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
2912 let (_, lanes, _, color) = p.without_orphan_sources();
2913 assert_eq!(color.len(), 1, "equal grades share their entry");
2914 assert_eq!(lanes[1].1[2].color, Some(0));
2915 reloads(&p, "a colour that outlived an undo");
2916
2917 // An equalizer and a grade on one clip are two independent tables.
2918 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
2919 let (_, lanes, eq, color) = p.without_orphan_sources();
2920 assert_eq!((eq.len(), color.len()), (1, 1));
2921 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
2922 }
2923
2924 /// Not a claim about correctness but about cost: a clip is copied on every
2925 /// paste, every undo snapshot and every lane clone, so its size is worth
2926 /// knowing. The eq index fit the padding a `Copy` clip already had; the
2927 /// colour one did not, and the struct grew a word.
2928 #[test]
2929 fn a_clip_is_still_a_small_copy() {
2930 assert_eq!(
2931 std::mem::size_of::<Clip>(),
2932 40,
2933 "Clip changed size -- 32 before the colour index, 40 after"
2934 );
2935 }
2936
2937 #[test]
2938 fn from_parts_has_no_history_and_checks_the_invariants() {
2939 let (sources, lanes, eq, color) = three().without_orphan_sources();
2940 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
2941 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
2942 .expect("valid parts");
2943 assert_eq!(p.clips(), three().clips());
2944 assert!(!p.undo(), "a loaded project has nothing to undo");
2945 assert!(p.split(4), "...and is editable from there");
2946 assert!(p.undo());
2947
2948 // A lane may be empty, and so may every lane -- an emptied timeline is a
2949 // project. No lane at all is not one: there would be nothing to place on.
2950 assert!(
2951 Project::from_parts(
2952 sources.clone(),
2953 two(video.clone(), Vec::new()),
2954 Vec::new(),
2955 Vec::new(),
2956 )
2957 .is_ok()
2958 );
2959 assert!(
2960 Project::from_parts(
2961 sources.clone(),
2962 two(Vec::new(), Vec::new()),
2963 Vec::new(),
2964 Vec::new(),
2965 )
2966 .is_ok()
2967 );
2968 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
2969 let bad: [Vec<Clip>; 5] = [
2970 vec![clip(0, 0, 3, 1)], // source that is not there
2971 vec![clip(0, 3, 3, 0)], // empty clip
2972 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
2973 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
2974 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
2975 ];
2976 for clips in bad {
2977 assert!(
2978 Project::from_parts(
2979 sources.clone(),
2980 two(clips.clone(), Vec::new()),
2981 Vec::new(),
2982 Vec::new(),
2983 )
2984 .is_err(),
2985 "{clips:?}"
2986 );
2987 assert!(
2988 Project::from_parts(
2989 sources.clone(),
2990 two(video.clone(), clips.clone()),
2991 Vec::new(),
2992 Vec::new(),
2993 )
2994 .is_err()
2995 );
2996 // ...and on a third lane, which is checked by the same walk.
2997 assert!(
2998 Project::from_parts(
2999 sources.clone(),
3000 vec![
3001 (LaneKind::Video, video.clone()),
3002 (LaneKind::Audio, audio.clone()),
3003 (LaneKind::Video, clips),
3004 ],
3005 Vec::new(),
3006 Vec::new(),
3007 )
3008 .is_err()
3009 );
3010 }
3011 // An equalizer index no table entry answers, and a table entry the file
3012 // format could not have written, are refused at this door too.
3013 let eqd = |i: u16| {
3014 vec![Clip {
3015 eq: Some(i),
3016 ..video[0]
3017 }]
3018 };
3019 assert!(
3020 Project::from_parts(
3021 sources.clone(),
3022 two(eqd(0), Vec::new()),
3023 Vec::new(),
3024 Vec::new(),
3025 )
3026 .is_err()
3027 );
3028 let mut nan = band_at(1);
3029 nan.bands[0].freq_hz = f32::NAN;
3030 assert!(
3031 Project::from_parts(
3032 sources.clone(),
3033 two(eqd(0), Vec::new()),
3034 vec![nan],
3035 Vec::new(),
3036 )
3037 .is_err()
3038 );
3039 let loaded = Project::from_parts(
3040 sources.clone(),
3041 two(eqd(0), Vec::new()),
3042 vec![band_at(1)],
3043 Vec::new(),
3044 )
3045 .expect("an eq the table holds");
3046 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
3047
3048 // The same two refusals for a colour, at the same door.
3049 let graded = |i: u16| {
3050 vec![Clip {
3051 color: Some(i),
3052 fit: FitPolicy::default(),
3053 ..video[0]
3054 }]
3055 };
3056 assert!(
3057 Project::from_parts(
3058 sources.clone(),
3059 two(graded(0), Vec::new()),
3060 Vec::new(),
3061 Vec::new(),
3062 )
3063 .is_err(),
3064 "a colour index no entry answers"
3065 );
3066 assert!(
3067 Project::from_parts(
3068 sources.clone(),
3069 two(graded(0), Vec::new()),
3070 Vec::new(),
3071 vec![ColorParams {
3072 tint: f32::NAN,
3073 ..grade_at(1)
3074 }],
3075 )
3076 .is_err(),
3077 "a value the file format could not have written"
3078 );
3079 let loaded = Project::from_parts(
3080 sources.clone(),
3081 two(graded(0), Vec::new()),
3082 Vec::new(),
3083 vec![grade_at(1)],
3084 )
3085 .expect("a colour the table holds");
3086 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
3087
3088 // Group ids survive a load, and the next split gets a fresh one.
3089 let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
3090 assert!(p.split(4));
3091 assert!(p.clips().iter().all(|c| c.link.is_some()));
3092 }
3093
3094 /// The grouping rules, at the untrusted door and after every edit that can
3095 /// touch a link. A link id is at most one clip per lane and, wherever it is
3096 /// carried, one span -- and no sequence of edits may produce otherwise,
3097 /// because what an edit produces is what a save writes and a load reads.
3098 ///
3099 /// Amended for the lane model: the two errors name their lane `V1`/`A1`
3100 /// rather than "video"/"audio", because with N lanes "the video lane" is no
3101 /// longer a lane. Same causes, same door, same claim.
3102 #[test]
3103 fn a_link_id_is_never_two_clips_of_one_lane() {
3104 let sources = vec![Source::new(FILE, 0)];
3105 let linked = |start, in_frame, out_frame, link| Clip {
3106 start,
3107 in_frame,
3108 out_frame,
3109 source: 0,
3110 link: Some(link),
3111 eq: None,
3112 color: None,
3113 fit: FitPolicy::default(),
3114 };
3115
3116 // The door: named errors, one per cause.
3117 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
3118 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
3119 .expect_err("refused")
3120 .to_string()
3121 };
3122 assert!(
3123 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
3124 .contains("link 7 names two clips in the V1 lane"),
3125 "a duplicate id inside one lane is refused by name"
3126 );
3127 assert!(
3128 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
3129 .contains("link 2 covers [0, 5) in V1 and [0, 3) in A1"),
3130 "a pair that does not cover one span is refused by name"
3131 );
3132 // A one-sided link is *not* an error: it is what a lift leaves behind.
3133 let mut p = Project::single(FILE, 9);
3134 assert!(p.lift(Lane::A1, 0));
3135 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
3136 assert!(
3137 Project::from_parts(sources, lanes, eq, color).is_ok(),
3138 "a lifted lane's project has to load again"
3139 );
3140
3141 // The edits: nothing below may break either rule.
3142 let consistent = |p: &Project, what: &str| {
3143 assert!(
3144 links_are_consistent(&p.lanes).is_ok(),
3145 "{what}: {:?}",
3146 p.lanes
3147 );
3148 };
3149 let mut p = three();
3150 let copied = p.clips()[0];
3151 assert!(
3152 copied.link.is_some(),
3153 "the clipboard clip carries its group"
3154 );
3155 assert!(p.lift(Lane::V1, 0));
3156 assert!(p.place(Lane::V1, 0, copied));
3157 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
3158 assert_eq!(
3159 p.clips().iter().filter(|c| c.link == copied.link).count(),
3160 0,
3161 "a placement belongs to no group, so it cannot duplicate one"
3162 );
3163 consistent(&p, "lift + place twice");
3164 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
3165 consistent(&p, "place through a grouped clip");
3166 assert!(p.paste(6, copied), "a rippling paste through another");
3167 consistent(&p, "paste");
3168 assert!(p.split(2));
3169 consistent(&p, "split");
3170 assert!(p.ripple_delete(1, 3));
3171 consistent(&p, "ripple_delete");
3172 assert!(p.undo());
3173 consistent(&p, "undo");
3174 }
3175
3176 /// What an edit produces is what a save writes, so *every* state the public
3177 /// API can reach has to load again. The two the verifier panel found where
3178 /// it did not: a split and a regroup handed one group id to two clips that
3179 /// were not the same span, because the lanes had been edited apart.
3180 #[test]
3181 fn every_reachable_state_reloads() {
3182 let mut p = Project::single(FILE, 150);
3183 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
3184 assert!(p.split(10), "the lanes are cut apart at 10");
3185 reloads(&p, "place on one lane, then split");
3186
3187 let mut p = Project::single(FILE, 150);
3188 assert!(p.split(30));
3189 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
3190 assert!(p.regroup(30), "only the audio lane can rejoin");
3191 assert!(p.split(60));
3192 reloads(&p, "lift, regroup one lane, split");
3193
3194 // Two audio streams of one file, both placed: two source entries with
3195 // one path between them, which is the state a stream picked out of the
3196 // library reaches -- and the state a save has to write and read back.
3197 let mut p = Project::single(FILE, 150);
3198 let second = p.import(FILE, 1);
3199 assert_eq!(second, 1, "the same file on another stream is a new source");
3200 assert!(p.append_clip(second, 150));
3201 assert!(p.split(200));
3202 reloads(
3203 &p,
3204 "a second audio stream of the same file, placed and split",
3205 );
3206 let (sources, ..) = p.without_orphan_sources();
3207 assert_eq!(
3208 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
3209 [0, 1],
3210 "both entries survive the orphan prune: both are played"
3211 );
3212 }
3213
3214 /// The same claim, swept: random op sequences off the public surface, the
3215 /// project reloaded after every one of them. A failure prints its seed, and
3216 /// the seed replays the whole sequence.
3217 #[test]
3218 fn random_edit_sequences_reload() {
3219 for seed in 0..200u64 {
3220 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
3221 let mut next = move |n: u32| {
3222 // xorshift64*: no dependency, and the seed replays it exactly.
3223 rng ^= rng << 13;
3224 rng ^= rng >> 7;
3225 rng ^= rng << 17;
3226 (rng >> 33) as u32 % n
3227 };
3228 let mut p = Project::single(FILE, 40);
3229 for step in 0..24 {
3230 let frame = next(44);
3231 // A clipboard copy carries the group id of the take it came from
3232 // -- the input that made a placement duplicate an id.
3233 let copied = *p
3234 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
3235 .get(next(4) as usize)
3236 .unwrap_or(&clip(0, 0, 5, 0));
3237 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
3238 let idx = next(4) as usize;
3239 let _ = match next(13) {
3240 0 => p.split(frame),
3241 1 => p.regroup(frame),
3242 2 => p.lift(lane, idx),
3243 3 => p.place(lane, frame, copied),
3244 4 => p.paste(frame, copied),
3245 5 => p.ripple_delete(frame, next(9)),
3246 6 => p.delete(idx),
3247 7 => p.undo(),
3248 // An equalizer put on and taken off in the mix: what a clip
3249 // carries has to reload with it, and the entries an undo
3250 // orphans must not come back out of the prune.
3251 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
3252 9 => p.set_eq(lane, idx, None),
3253 // ...and a colour grade in the same mix, for the same
3254 // reason: it rides on the clip and its orphans must go.
3255 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
3256 11 => p.set_color(lane, idx, None),
3257 _ => p.append_clip(0, 1 + next(9)),
3258 };
3259 reloads(&p, &format!("seed {seed}, step {step}"));
3260 }
3261 }
3262 }
3263
3264 /// The save/load round trip a project must survive: the parts a save writes,
3265 /// handed back to the constructor a load goes through -- every lane of them,
3266 /// and the reloaded timeline has to be the same lanes in the same order.
3267 fn reloads(p: &Project, what: &str) {
3268 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
3269 match Project::from_parts(sources, lanes, eq, color) {
3270 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
3271 Ok(back) => {
3272 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
3273 // Placements, not whole clips: an orphan prune renumbers the
3274 // sources a clip names, which is the point of it.
3275 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
3276 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
3277 };
3278 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
3279 // The prune renumbers the eq table too, so what has to survive
3280 // is the settings themselves, clip by clip.
3281 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
3282 p.lanes()
3283 .into_iter()
3284 .map(|l| {
3285 (0..p.lane(l).len())
3286 .map(|i| p.eq_of(l, i).cloned())
3287 .collect()
3288 })
3289 .collect()
3290 };
3291 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
3292 // The colour table renumbers in the same prune, so the same
3293 // claim: the params a clip names, not the index it names them by.
3294 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
3295 p.lanes()
3296 .into_iter()
3297 .map(|l| {
3298 (0..p.lane(l).len())
3299 .map(|i| p.color_of(l, i).copied())
3300 .collect()
3301 })
3302 .collect()
3303 };
3304 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
3305 }
3306 }
3307 }
3308
3309 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
3310 /// -- each one sorted and disjoint, and one span per group id -- asserted
3311 /// directly, where the point is the invariant rather than the round trip.
3312 fn invariants_hold(p: &Project, what: &str) {
3313 for lane in p.lanes() {
3314 assert!(
3315 sorted_disjoint(p.lane(lane)),
3316 "{what}: {} is out of order or overlaps itself: {:?}",
3317 lane.label(),
3318 p.lane(lane)
3319 );
3320 }
3321 if let Err(e) = links_are_consistent(&p.lanes) {
3322 panic!("{what}: {e}\n{:?}", p.lanes);
3323 }
3324 }
3325
3326 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
3327 /// edited without any other lane hearing about it. A handle naming a lane
3328 /// that is not there reads as empty and refuses to mutate.
3329 #[test]
3330 fn a_third_lane_is_a_peer() {
3331 let mut p = three();
3332 assert_eq!(p.lane_count(LaneKind::Video), 1);
3333 assert_eq!(p.lane_count(LaneKind::Audio), 1);
3334 let v2 = p.add_lane(LaneKind::Video);
3335 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
3336 assert_eq!(v2.label(), "V2");
3337 assert_eq!(p.lane_count(LaneKind::Video), 2);
3338 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
3339 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
3340
3341 // A handle for a lane that is not there: empty, and no mutation takes.
3342 let v3 = Lane::new(LaneKind::Video, 2);
3343 assert!(p.lane(v3).is_empty());
3344 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
3345 assert!(!p.lift(v3, 0));
3346 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
3347
3348 // Placing on V2 moves nothing else, and the lane can outrun the rest.
3349 let before = shape(&p);
3350 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
3351 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
3352 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
3353 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
3354 assert_eq!(
3355 p.timeline_frames(),
3356 16,
3357 "the last lane to end sets the length"
3358 );
3359 assert_eq!(p.map(v2, 5), Some((0, 21)));
3360 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
3361 assert_eq!(
3362 p.span_at(v2, 0),
3363 Some(Span {
3364 start: 0,
3365 len: 4,
3366 from: None
3367 })
3368 );
3369 // Every lane still covers the whole timeline, gaps included.
3370 for l in p.lanes() {
3371 let spans = p.spans_from(l, 0);
3372 assert_eq!(
3373 spans.iter().map(|s| s.len).sum::<u32>(),
3374 16,
3375 "{}",
3376 l.label()
3377 );
3378 }
3379 // ...and playback still reads V1 and A1, whatever else is there.
3380 assert_eq!(p.clips(), p.lane(Lane::V1));
3381 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
3382 let segments = p.segments_from(0, FPS);
3383 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
3384 assert_eq!(
3385 segments[3],
3386 (None, 0.0, 7.0 / FPS),
3387 "A1 keeps the clock counting over the picture V2 added"
3388 );
3389 invariants_hold(&p, "place on V2");
3390
3391 // A lift is that lane's business too, and the lane list undoes.
3392 assert!(p.lift(v2, 0));
3393 assert!(p.lane(v2).is_empty());
3394 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
3395 assert!(p.undo());
3396 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
3397 assert!(p.undo());
3398 assert!(p.lane(v2).is_empty(), "the placement came off V2");
3399 assert!(p.undo(), "and one more step takes the lane itself back");
3400 assert_eq!(p.lane_count(LaneKind::Video), 1);
3401 assert_eq!(shape(&p), shape(&three()));
3402 }
3403
3404 /// The grouping rule across more than two lanes: a link id is one *span*,
3405 /// on however many lanes carry it -- not a video/audio pair and not a
3406 /// pairing by `ord`. So a split shares an id with every lane whose half
3407 /// lines up, and gives its own to every lane whose half does not.
3408 #[test]
3409 fn a_group_id_is_one_span_across_every_lane() {
3410 let mut p = Project::single(FILE, 9);
3411 let v2 = p.add_lane(LaneKind::Video);
3412 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "three lanes, one span");
3413 assert!(p.split(4));
3414 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
3415 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
3416 };
3417 let (left, right) = (side(&p, 0), side(&p, 1));
3418 assert!(
3419 left[0].is_some() && left.iter().all(|id| *id == left[0]),
3420 "one id for three left halves: {left:?}"
3421 );
3422 assert!(right.iter().all(|id| *id == right[0]), "{right:?}");
3423 assert_ne!(left[0], right[0], "the halves are no longer one take");
3424 invariants_hold(&p, "split across three lanes");
3425
3426 // V2 ends early: same start, so the left halves are one take; different
3427 // end, so the right halves cannot be.
3428 let mut p = Project::single(FILE, 9);
3429 let v2 = p.add_lane(LaneKind::Video);
3430 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
3431 assert!(p.split(3));
3432 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "same [0, 3)");
3433 assert_ne!(
3434 p.lane(Lane::V1)[1].link,
3435 p.lane(v2)[1].link,
3436 "[3,9) vs [3,6)"
3437 );
3438 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
3439 invariants_hold(&p, "split where one lane ends early");
3440
3441 // The inverse rejoins all three, and groups them the same way.
3442 assert!(p.regroup(3));
3443 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
3444 assert_ne!(
3445 p.lane(Lane::V1)[0].link,
3446 p.lane(v2)[0].link,
3447 "V2 rejoins into a span of its own"
3448 );
3449 invariants_hold(&p, "regroup across three lanes");
3450
3451 // ...and the rule is enforced, not merely produced: two video lanes
3452 // carrying one id over two spans is refused, by lane name.
3453 let linked = |out_frame, link| Clip {
3454 start: 0,
3455 in_frame: 0,
3456 out_frame,
3457 source: 0,
3458 link: Some(link),
3459 eq: None,
3460 color: None,
3461 fit: FitPolicy::default(),
3462 };
3463 let lanes = vec![
3464 LaneData {
3465 kind: LaneKind::Video,
3466 clips: vec![linked(3, 4)],
3467 },
3468 LaneData {
3469 kind: LaneKind::Video,
3470 clips: vec![linked(5, 4)],
3471 },
3472 ];
3473 assert_eq!(
3474 links_are_consistent(&lanes).unwrap_err().to_string(),
3475 "link 4 covers [0, 3) in V1 and [0, 5) in V2"
3476 );
3477 }
3478
3479 /// A group is a set of clips over one span, at most one per lane: a picture
3480 /// may be grouped with sound in *any* audio lane -- there is no paired ord,
3481 /// and the lanes in between may be empty -- and the two ways to break that
3482 /// name the lane they broke it on. Lanes built by hand, because the rule is
3483 /// checked at the untrusted door and no edit can produce these.
3484 #[test]
3485 fn a_group_may_span_any_lane() {
3486 let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips };
3487 let one = |start: u32, end: u32, link| Clip {
3488 start,
3489 in_frame: start,
3490 out_frame: end,
3491 source: 0,
3492 link: Some(link),
3493 eq: None,
3494 color: None,
3495 fit: FitPolicy::default(),
3496 };
3497 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
3498 let kinds = [
3499 LaneKind::Video,
3500 LaneKind::Audio,
3501 LaneKind::Video,
3502 LaneKind::Audio,
3503 ];
3504 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
3505 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
3506 };
3507 let take = || vec![one(0, 4, 7)];
3508 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
3509 // The same take on V1 + A2 only, the lanes between it empty: legal, the
3510 // way a lifted half is legal.
3511 let across = build([take(), Vec::new(), Vec::new(), take()]);
3512 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
3513 // Disagreeing about the span is not, and the message names both lanes.
3514 let apart = build([take(), Vec::new(), Vec::new(), vec![one(0, 6, 7)]]);
3515 assert_eq!(
3516 links_are_consistent(&apart).unwrap_err().to_string(),
3517 "link 7 covers [0, 4) in V1 and [0, 6) in A2"
3518 );
3519 // ...and one id twice in one lane is still that lane's error, by name.
3520 let twice = build([
3521 Vec::new(),
3522 Vec::new(),
3523 vec![one(0, 4, 7), one(4, 8, 7)],
3524 Vec::new(),
3525 ]);
3526 assert_eq!(
3527 links_are_consistent(&twice).unwrap_err().to_string(),
3528 "link 7 names two clips in the V2 lane"
3529 );
3530 }
3531
3532 /// Every lane a save writes comes out, in display order and with its kind --
3533 /// an empty one included, since it is state a front-end shows -- and a
3534 /// two-lane project still writes exactly the parts it always did.
3535 #[test]
3536 fn a_save_writes_every_lane_it_has() {
3537 let mut p = three();
3538 let before = p.without_orphan_sources();
3539 assert_eq!(before.1.len(), 2, "V1 and A1");
3540 let v2 = p.add_lane(LaneKind::Video);
3541 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
3542 let a2 = p.add_lane(LaneKind::Audio);
3543 let (sources, lanes, eq, color) = p.without_orphan_sources();
3544 assert_eq!(
3545 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
3546 [
3547 LaneKind::Video,
3548 LaneKind::Audio,
3549 LaneKind::Video,
3550 LaneKind::Audio
3551 ],
3552 "display order, not video-then-audio"
3553 );
3554 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
3555 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
3556 // ...and all four load again as the same four.
3557 let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
3558 assert_eq!(back.lanes(), p.lanes());
3559 assert_eq!(back.lane(a2), p.lane(a2));
3560
3561 // Taking the lanes back leaves exactly what a two-lane save wrote.
3562 for _ in 0..3 {
3563 assert!(p.undo());
3564 }
3565 assert_eq!(
3566 p.without_orphan_sources(),
3567 before,
3568 "byte for byte the same parts a two-lane save always wrote"
3569 );
3570 }
3571
3572 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
3573 /// three lanes and grows more: every lane's own order and the one
3574 /// span-per-id rule after every op, *and* the reload the v4 format restored
3575 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
3576 /// project of any number of lanes.
3577 #[test]
3578 fn random_edit_sequences_keep_many_lanes_consistent() {
3579 for seed in 0..200u64 {
3580 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
3581 let mut next = move |n: u32| {
3582 rng ^= rng << 13;
3583 rng ^= rng >> 7;
3584 rng ^= rng << 17;
3585 (rng >> 33) as u32 % n
3586 };
3587 let mut p = Project::single(FILE, 40);
3588 let v2 = p.add_lane(LaneKind::Video);
3589 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
3590 let lanes = [Lane::V1, Lane::A1, v2];
3591 for step in 0..24 {
3592 let frame = next(44);
3593 let copied = *p
3594 .lane(lanes[next(3) as usize])
3595 .get(next(4) as usize)
3596 .unwrap_or(&clip(0, 0, 5, 0));
3597 let lane = lanes[next(3) as usize];
3598 let idx = next(4) as usize;
3599 let _ = match next(12) {
3600 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
3601 11 => p.set_eq(lane, idx, None),
3602 0 => p.split(frame),
3603 1 => p.regroup(frame),
3604 2 => p.lift(lane, idx),
3605 3 => p.place(lane, frame, copied),
3606 4 => p.paste(frame, copied),
3607 5 => p.ripple_delete(frame, next(9)),
3608 6 => p.delete(idx),
3609 7 => p.undo(),
3610 8 => {
3611 p.add_lane(if next(2) == 0 {
3612 LaneKind::Video
3613 } else {
3614 LaneKind::Audio
3615 });
3616 true
3617 }
3618 _ => p.append_clip(0, 1 + next(9)),
3619 };
3620 invariants_hold(&p, &format!("seed {seed}, step {step}"));
3621 reloads(&p, &format!("seed {seed}, step {step}"));
3622 }
3623 }
3624 }
3625
3626 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
3627 /// there, `V1` shows again on either side of it, and a frame no video lane
3628 /// covers is a gap however many lanes there are.
3629 #[test]
3630 fn the_composite_is_the_topmost_lane_with_a_clip() {
3631 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
3632 let lanes = vec![
3633 // V1: the whole 30 frames of source 0.
3634 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
3635 // V2: source 1 over the middle third.
3636 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
3637 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
3638 ];
3639 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
3640 assert_eq!(
3641 p.composite_spans_from(0),
3642 vec![
3643 Span {
3644 start: 0,
3645 len: 10,
3646 from: Some((0, 0))
3647 },
3648 Span {
3649 start: 10,
3650 len: 10,
3651 from: Some((1, 5))
3652 },
3653 Span {
3654 start: 20,
3655 len: 10,
3656 from: Some((0, 20))
3657 },
3658 ],
3659 "V2 takes over for its own span and hands V1 back"
3660 );
3661 // A mid-span ask resolves the same way, which is what a seek does.
3662 assert_eq!(
3663 p.composite_span_at(15),
3664 Some(Span {
3665 start: 15,
3666 len: 5,
3667 from: Some((1, 10))
3668 })
3669 );
3670 assert_eq!(p.composite_span_at(30), None, "past the end");
3671
3672 // A hole in V1 under V2's clip: black between the two, and black after
3673 // both run out (the audio lane is still holding the timeline open).
3674 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
3675 let holed = vec![
3676 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
3677 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
3678 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
3679 ];
3680 let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts");
3681 assert_eq!(
3682 p.composite_spans_from(0),
3683 vec![
3684 Span {
3685 start: 0,
3686 len: 5,
3687 from: Some((0, 0))
3688 },
3689 Span {
3690 start: 5,
3691 len: 5,
3692 from: None
3693 },
3694 Span {
3695 start: 10,
3696 len: 10,
3697 from: Some((1, 0))
3698 },
3699 Span {
3700 start: 20,
3701 len: 10,
3702 from: None
3703 },
3704 ]
3705 );
3706
3707 // One video lane: the composite *is* that lane, span for span -- the
3708 // promise every existing two-lane project rests on.
3709 let p = Project::single(FILE, 30);
3710 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
3711 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
3712 }
3713
3714 /// Every audio lane holding something gets a play list, and only those.
3715 #[test]
3716 fn audio_segments_cover_every_lane_that_holds_something() {
3717 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
3718 let lanes = vec![
3719 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
3720 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
3721 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
3722 (LaneKind::Audio, Vec::new()),
3723 ];
3724 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
3725 let lists = p.audio_segments_from(0, FPS);
3726 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
3727 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
3728 // A2 is a gap up to frame 15, then the whole of source 1.
3729 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
3730
3731 // No audio lane holds anything: one all-gap list, so such a timeline
3732 // still plays silence against a master clock.
3733 let p = Project::from_parts(
3734 vec![Source::new(FILE, 0)],
3735 vec![
3736 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
3737 (LaneKind::Audio, Vec::new()),
3738 ],
3739 vec![],
3740 vec![],
3741 )
3742 .expect("valid parts");
3743 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
3744 }
3745}