forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB11603ecTahinli3 months ago110 commits

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