forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

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