forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbdcc2fbTahinli3 months ago176 commits

project.rs5269 lines, 226.5 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/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
72/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
73/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
74/// comparable nor exactly writable, and `.edith` has to read back the very
75/// number that was set. A thousandth is finer than any card can drag and coarser
76/// than any rounding anyone can hear.
77///
78/// The rate alone: a speeded clip is resampled, so its pitch moves with it (the
79/// tape effect). Nothing here preserves pitch and nothing here plays backwards
80/// -- [`Speed::MIN`] is a quarter speed, [`Speed::MAX`] four times.
81#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
82pub struct Speed(u16);
83
84impl Speed {
85 /// Real time -- what every clip is until something says otherwise, and the
86 /// value every path in this engine short-circuits on.
87 pub const NORMAL: Speed = Speed(1000);
88 pub const MIN: Speed = Speed(250);
89 pub const MAX: Speed = Speed(4000);
90
91 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
92 /// unrepresentable rather than merely refused: nothing downstream divides
93 /// by a speed that could be nothing.
94 pub fn from_permille(permille: u16) -> Self {
95 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
96 }
97
98 pub fn permille(self) -> u16 {
99 self.0
100 }
101
102 pub fn is_normal(self) -> bool {
103 self == Self::NORMAL
104 }
105
106 /// As a multiplier, for the sound worker and for a label.
107 pub fn as_f64(self) -> f64 {
108 f64::from(self.0) / 1000.
109 }
110
111 /// How many *timeline* frames `source` source frames occupy at this rate --
112 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
113 /// clip that occupied no frames would be an empty placement, which the lane
114 /// invariant forbids and which nothing could ever click on again.
115 pub fn frames(self, source: u32) -> u32 {
116 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
117 n.clamp(1, u64::from(u32::MAX)) as u32
118 }
119
120 /// The mapping itself: which source frame of a clip the `offset`th timeline
121 /// frame of it plays. Floored, so the first timeline frame is the clip's own
122 /// in-point at every rate.
123 pub fn source_at(self, offset: u32) -> u32 {
124 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
125 }
126
127 /// Its inverse, for a decoder's frames on their way back out: which timeline
128 /// frame of the clip the `offset`th *source* frame of it lands on.
129 ///
130 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
131 /// decoded frame with this and shows the newest whose stamp has come due, so
132 /// what is on screen at timeline offset `d` is the last source frame with
133 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
134 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
135 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
136 /// the two the same way would put the preview a frame off the export at some
137 /// speeds and a whole held frame off at slow ones -- drift that no test of
138 /// either side alone would catch.
139 pub fn timeline_at(self, offset: u32) -> u32 {
140 (u64::from(offset) * 1000)
141 .div_ceil(u64::from(self.0))
142 .min(u64::from(u32::MAX)) as u32
143 }
144
145 /// The longest source range that still *fits* in `frames` timeline frames at
146 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
147 /// any room narrower than the four timeline frames one source frame occupies.
148 ///
149 /// What a trim commits and what a hole-punch leaves behind: rounding could
150 /// otherwise hand back a range wider than the room, and a clip that outgrew
151 /// its room would overlap its neighbour -- the one thing a lane may never do.
152 /// `None` is not an error, it is "no remainder": the caller drops that piece
153 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
154 /// is `frames` itself, so nothing about an unspeeded edit changes.
155 pub fn fit(self, frames: u32) -> Option<u32> {
156 if frames == 0 || self.frames(1) > frames {
157 return None;
158 }
159 let mut src = self.source_at(frames).max(1);
160 // At most a step or two: `frames` is monotone in `src` and the rounding
161 // above can only overshoot by one source frame's worth.
162 while src > 1 && self.frames(src) > frames {
163 src -= 1;
164 }
165 Some(src)
166 }
167
168 /// How many timeline frames `source` source frames of head (or tail) are
169 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
170 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
171 /// empty, but the room in front of one may well be.
172 pub fn room(self, source: u32) -> u32 {
173 match source {
174 0 => 0,
175 n => self.frames(n),
176 }
177 }
178
179 /// How many timeline frames from `offset` on show the **same** source frame:
180 /// one at real time and faster, more when the clip is slowed. What an export
181 /// encodes without decoding the same picture twice, and the count that makes
182 /// its frame walk exactly as long as the span.
183 pub fn repeats(self, offset: u32, len: u32) -> u32 {
184 let want = self.source_at(offset);
185 (offset..len)
186 .take_while(|&t| self.source_at(t) == want)
187 .count() as u32
188 }
189
190 /// Where in the source a cut `offset` timeline frames into a clip of `len`
191 /// source frames falls -- and `None` when this rate cannot address that
192 /// frame at all.
193 ///
194 /// At half speed a clip of ten source frames is twenty timeline frames long
195 /// and every source frame is on screen twice, so a cut between the two
196 /// showings of one frame is not a cut in the *file*: taking it would leave
197 /// two halves whose lengths no longer add up to the clip that was cut --
198 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
199 /// the model stays exact and the front-end can say why. At real time every
200 /// interior frame answers, which is the path a project without speeds is on.
201 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
202 let src = self.source_at(offset);
203 (src > 0
204 && src < len
205 && self.frames(src) == offset
206 && self.frames(len - src) == self.frames(len) - offset)
207 .then_some(src)
208 }
209}
210
211impl Default for Speed {
212 fn default() -> Self {
213 Self::NORMAL
214 }
215}
216
217impl std::fmt::Display for Speed {
218 /// `2.00x` -- what a card prints and what a clip box is marked with.
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 write!(f, "{:.2}x", self.as_f64())
221 }
222}
223
224/// A half-open `[in_frame, out_frame)` range of frames of source
225/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
226/// Never empty.
227#[derive(Clone, Copy, PartialEq, Eq, Debug)]
228pub struct Clip {
229 /// Timeline frame the clip's first frame is shown at. Meaningless on a
230 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
231 /// with where the caller asked for.
232 pub start: u32,
233 pub in_frame: u32,
234 pub out_frame: u32,
235 /// Index into [`Project::sources`].
236 pub source: usize,
237 /// Group id: clips sharing one were split from the same take. `None` for a
238 /// clip that belongs to no group.
239 pub link: Option<u32>,
240 /// Index into the project's equalizer table
241 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
242 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
243 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
244 /// plain assignment. The table is append-only within a session, so an index
245 /// on a clipboard clip or inside an undo snapshot can never dangle.
246 pub eq: Option<u16>,
247 /// Index into the project's colour table
248 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
249 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
250 /// promises: `Copy`, append-only within a session, never dangling.
251 pub color: Option<u16>,
252 /// How this clip's picture meets a project canvas of another shape
253 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
254 /// two above: it is one byte with no parameters, so there is nothing for a
255 /// table to share, and a clip that is the project's own size never consults
256 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
257 /// where the aspect does not agree.
258 pub fit: FitPolicy,
259 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
260 /// eq and colour indexes: it is two bytes with nothing to share, and a table
261 /// would put a level of indirection between the mapping and the one number
262 /// every frame of it is divided by.
263 ///
264 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
265 /// the clip plays, so a trim and a split still address the file. What it
266 /// changes is how many *timeline* frames that range is spread over
267 /// ([`Clip::frames`]).
268 pub speed: Speed,
269}
270
271impl Clip {
272 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
273 /// reads out of its file -- not how long it is on the timeline, which is
274 /// [`Clip::frames`] and differs the moment it is speeded.
275 pub fn len(&self) -> u32 {
276 self.out_frame - self.in_frame
277 }
278
279 /// Timeline frames it occupies: its source range at its own speed, never
280 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
281 /// what it overlaps, how wide its box is -- is asked of this and not of
282 /// [`Clip::len`].
283 pub fn frames(&self) -> u32 {
284 self.speed.frames(self.len())
285 }
286
287 /// One past the last timeline frame it covers.
288 pub fn end(&self) -> u32 {
289 self.start + self.frames()
290 }
291}
292
293/// A file the timeline plays from, and *which* of its audio streams it plays:
294/// a file carrying one track per language is several sources, one per stream,
295/// sharing a path. Two entries differing only in the stream are two sources --
296/// they are what a clip names, and a clip plays exactly one stream.
297///
298/// The path is always canonical ([`Source::new`]), so the same file reached by
299/// two paths is one source.
300#[derive(Clone, Debug, PartialEq, Eq)]
301pub struct Source {
302 pub path: PathBuf,
303 /// Position among the file's audio tracks in file order, the numbering
304 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
305 /// single track, and for a silent one.
306 pub audio_stream: usize,
307}
308
309impl Source {
310 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
311 Self {
312 path: canonical(path.as_ref()),
313 audio_stream,
314 }
315 }
316}
317
318/// What a lane carries, which is what a *gap* in it means: black frames on a
319/// video lane, silence on an audio one.
320#[derive(Clone, Copy, PartialEq, Eq, Debug)]
321pub enum LaneKind {
322 Video,
323 Audio,
324}
325
326/// Which lane an operation acts on: a kind plus a 0-based position among the
327/// lanes of that kind, so [`Lane::V1`] is the first video lane and
328/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
329///
330/// A handle, not the lane itself. It stays meaningful while lanes are added,
331/// and one naming a lane that is not there reads as an empty lane and refuses
332/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
333/// bounds check of its own.
334#[derive(Clone, Copy, PartialEq, Eq, Debug)]
335pub struct Lane {
336 pub kind: LaneKind,
337 pub ord: usize,
338}
339
340impl Lane {
341 /// The first video lane: what a decoder plays and what an export renders.
342 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
343 /// The first audio lane: what the audio worker plays.
344 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
345
346 pub const fn new(kind: LaneKind, ord: usize) -> Self {
347 Self { kind, ord }
348 }
349
350 /// `V1`, `A2`: how a lane is written in a header column and named in an
351 /// error about it.
352 pub fn label(self) -> String {
353 let kind = match self.kind {
354 LaneKind::Video => 'V',
355 LaneKind::Audio => 'A',
356 };
357 format!("{kind}{}", self.ord + 1)
358 }
359}
360
361/// One lane: what it is and what it holds. A struct rather than a bare
362/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
363/// compositing mode, a name -- and it belongs next to the clips it applies to.
364#[derive(Clone, Debug)]
365struct LaneData {
366 kind: LaneKind,
367 /// Sorted by `start` and disjoint ([`sorted_disjoint`]).
368 clips: Vec<Clip>,
369}
370
371impl LaneData {
372 /// The two lanes a project starts with: `V1` then `A1`, in display order.
373 /// One place, because a freshly opened file is exactly this pair.
374 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
375 vec![
376 LaneData {
377 kind: LaneKind::Video,
378 clips: video,
379 },
380 LaneData {
381 kind: LaneKind::Audio,
382 clips: audio,
383 },
384 ]
385 }
386}
387
388/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
389#[derive(Clone, Copy, PartialEq, Eq, Debug)]
390pub enum Edge {
391 /// Its first timeline frame; moving it changes where in the source the clip
392 /// starts reading, so the picture behind the edge slides with it.
393 Start,
394 /// One past its last timeline frame; moving it only says how much of the
395 /// source to keep.
396 End,
397}
398
399/// What a lane holds over one stretch of the timeline: either a placed clip or
400/// a gap. Returned already trimmed to the position it was asked about, so a
401/// caller can hand `len` straight to a decoder (or to a black-frame generator).
402#[derive(Clone, Copy, PartialEq, Eq, Debug)]
403pub struct Span {
404 /// Timeline frame the span starts at.
405 pub start: u32,
406 /// Frames it covers; `>= 1`.
407 pub len: u32,
408 /// `(source index, first source frame)`, or `None` for a gap -- which the
409 /// engine renders as black frames and as silence.
410 pub from: Option<(usize, u32)>,
411 /// The rate the clip this came off plays at ([`Clip::speed`]);
412 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
413 /// timeline frames whatever it says -- the speed is how many *source* frames
414 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
415 /// come back to the timeline.
416 pub speed: Speed,
417}
418
419impl Span {
420 /// One past the last timeline frame it covers.
421 pub fn end(&self) -> u32 {
422 self.start + self.len
423 }
424
425 /// How many source frames it reads: what a decoder is asked for and how wide
426 /// an audio window is. `len` at real time, and the one arithmetic both the
427 /// picture and the sound go through, so they cannot disagree about where a
428 /// speeded clip ends.
429 pub fn source_len(&self) -> u32 {
430 match self.from {
431 // The last timeline frame's own source frame is the last one needed
432 // -- never one more, which at a slow rate would read a frame the
433 // next clip owns and at a fast one would decode a picture nothing
434 // shows.
435 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
436 None => self.len,
437 }
438 }
439
440 /// Where a source frame of this span lands on the timeline: the stamp
441 /// playback puts on a decoded frame, through the ceil half of the pair
442 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
443 /// frame, so a frame before it stamps at the span's start.
444 pub fn timeline_at(&self, source_frame: u32) -> u32 {
445 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
446 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
447 }
448}
449
450/// What one speeded audio segment asks of the worker: how many source frames to
451/// consume per output frame, and how many seconds of timeline it has to fill.
452/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
453/// resampling at all.
454#[derive(Clone, Copy, PartialEq, Debug)]
455pub struct Stretch {
456 /// Source frames per output frame -- the speed as a multiplier.
457 pub step: f64,
458 /// What the segment owes the timeline, which is what it is padded or
459 /// trimmed to.
460 pub timeline_secs: f64,
461}
462
463/// What a save writes and a load takes back: the sources, every lane in
464/// display order with its kind, and the equalizer and colour tables their clips
465/// index into -- [`Project::without_orphan_sources`] out,
466/// [`Project::from_parts`] in.
467pub type Parts = (
468 Vec<Source>,
469 Vec<(LaneKind, Vec<Clip>)>,
470 Vec<EqParams>,
471 Vec<ColorParams>,
472);
473
474/// The edit list plus its undo history.
475#[derive(Clone, Debug)]
476pub struct Project {
477 /// Append-only: never popped, never reordered. See the module docs.
478 sources: Vec<Source>,
479 /// In display order, which is the order [`Lane::ord`] counts in: the nth
480 /// lane of a kind here is that kind's `ord` n. Never empty.
481 lanes: Vec<LaneData>,
482 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
483 eq: Vec<EqParams>,
484 /// The same, for [`Clip::color`].
485 color: Vec<ColorParams>,
486 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
487 /// whole lane list, so adding a lane undoes as well.
488 history: Vec<Vec<LaneData>>,
489 /// Never rolled back by an undo: an id retired by an undone split must not
490 /// come back and group two clips that were never together.
491 next_link: u32,
492}
493
494impl Project {
495 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
496 /// grouped -- the state of a freshly opened video, where the timeline is the
497 /// source. `frame_count` of 0 would break the never-empty invariant, so it
498 /// is clamped to one frame.
499 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
500 let clip = Clip {
501 start: 0,
502 in_frame: 0,
503 out_frame: frame_count.max(1),
504 source: 0,
505 link: Some(0),
506 eq: None,
507 color: None,
508 fit: FitPolicy::default(),
509 speed: Speed::NORMAL,
510 };
511 Self {
512 // A file is opened on its first audio stream: nothing has picked
513 // one yet, and every file with audio at all has that one.
514 sources: vec![Source::new(path, 0)],
515 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
516 eq: Vec::new(),
517 color: Vec::new(),
518 history: Vec::new(),
519 next_link: 1,
520 }
521 }
522
523 /// A project rebuilt from a saved edit list -- the load half of
524 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
525 /// an `ord` is a lane's position among the lanes of that kind, exactly as
526 /// [`Project::lanes`] hands them back. History is *not* saved, so
527 /// [`Project::undo`] is `false` until the first edit of the new session.
528 /// This is the one door untrusted parts come in through, so every invariant
529 /// every other constructor keeps is checked here, by name and in release:
530 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
531 /// or a colour) that is not there, a clip whose end overflows, a lane that is
532 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
533 /// below.
534 ///
535 /// A project whose lanes are all *empty* is not among them: an emptied
536 /// timeline is a project like any other -- it plays black and silent, it
537 /// saves, and it loads back. What a project cannot be is laneless, because
538 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
539 /// handle indexes into.
540 pub fn from_parts(
541 sources: Vec<Source>,
542 lanes: Vec<(LaneKind, Vec<Clip>)>,
543 eq: Vec<EqParams>,
544 color: Vec<ColorParams>,
545 ) -> crate::Result<Self> {
546 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
547 return Err(format!("eq {bad} holds a band that is not a finite number").into());
548 }
549 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
550 return Err(format!("color {bad} holds a value that is not a finite number").into());
551 }
552 if lanes.is_empty() {
553 return Err("no lanes at all: that is not a project".into());
554 }
555 let lanes: Vec<LaneData> = lanes
556 .into_iter()
557 .map(|(kind, clips)| LaneData { kind, clips })
558 .collect();
559 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
560 let name = lane.label();
561 for c in &data.clips {
562 if c.out_frame <= c.in_frame {
563 return Err(format!(
564 "{name} clip at {} plays the empty range [{}, {})",
565 c.start, c.in_frame, c.out_frame
566 )
567 .into());
568 }
569 if c.source >= sources.len() {
570 return Err(format!(
571 "{name} clip at {} names source {} of {}",
572 c.start,
573 c.source,
574 sources.len()
575 )
576 .into());
577 }
578 if c.start.checked_add(c.frames()).is_none() {
579 return Err(format!(
580 "{name} clip at {} runs past the last frame there is",
581 c.start
582 )
583 .into());
584 }
585 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
586 return Err(format!(
587 "{name} clip at {} names eq {} of {}",
588 c.start,
589 c.eq.unwrap_or_default(),
590 eq.len()
591 )
592 .into());
593 }
594 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
595 return Err(format!(
596 "{name} clip at {} names color {} of {}",
597 c.start,
598 c.color.unwrap_or_default(),
599 color.len()
600 )
601 .into());
602 }
603 }
604 if !sorted_disjoint(&data.clips) {
605 return Err(format!("the {name} lane is out of order or overlaps itself").into());
606 }
607 }
608 links_are_consistent(&lanes)?;
609 let next_link = lanes
610 .iter()
611 .flat_map(|l| &l.clips)
612 .filter_map(|c| c.link)
613 .max()
614 // Saturating so a crafted file cannot make the counter wrap: at the
615 // ceiling ids stop being fresh, which loses grouping, not memory.
616 .map_or(0, |m| m.saturating_add(1));
617 Ok(Self {
618 sources: sources
619 .iter()
620 .map(|s| Source::new(&s.path, s.audio_stream))
621 .collect(),
622 lanes,
623 eq,
624 color,
625 history: Vec::new(),
626 next_link,
627 })
628 }
629
630 /// The first video lane -- what an export renders and what a single-lane
631 /// caller still means by "the clips".
632 pub fn clips(&self) -> &[Clip] {
633 self.lane(Lane::V1)
634 }
635
636 /// The clips of `lane`, or nothing at all for a lane that is not there.
637 pub fn lane(&self, lane: Lane) -> &[Clip] {
638 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
639 }
640
641 /// Every lane's handle, in display order -- what a walk over "all lanes"
642 /// iterates, and what a front-end lays out top to bottom.
643 pub fn lanes(&self) -> Vec<Lane> {
644 handles(&self.lanes)
645 }
646
647 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
648 /// for every `ord` below it, and none at or above it.
649 pub fn lane_count(&self, kind: LaneKind) -> usize {
650 self.lanes.iter().filter(|l| l.kind == kind).count()
651 }
652
653 /// Appends an empty lane of `kind` and hands back its handle. One undo
654 /// step, because the lane list is state a front-end shows: an added lane
655 /// that could not be taken back would be the one edit with no way out.
656 /// Nothing plays differently until something is placed on it.
657 ///
658 /// An empty lane is a lane like any other -- so is a whole project of them
659 /// ([`Project::from_parts`]); nothing plays until something is placed.
660 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
661 self.snapshot();
662 self.lanes.push(LaneData {
663 kind,
664 clips: Vec::new(),
665 });
666 Lane::new(kind, self.lane_count(kind) - 1)
667 }
668
669 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
670 /// one undo step like it, which restores the lane where it stood.
671 ///
672 /// Refused, changing nothing, while the lane holds anything: the refusal
673 /// names the clips (file and first frame), because a track removal that
674 /// deleted takes with it would be the one edit nobody sees coming. Refused
675 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
676 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
677 /// kind and *skips* a kind that is not there), so a project without one
678 /// would swallow half of every file dropped on it, silently.
679 ///
680 /// The lanes below it move up one `ord`, so a handle a caller was holding
681 /// (a selection, an open card) names the lane after it from here on -- the
682 /// one thing a front-end owes this call.
683 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
684 let Some(i) = self.index(lane) else {
685 return Err(format!("there is no {} to remove", lane.label()).into());
686 };
687 if self.lane_count(lane.kind) == 1 {
688 return Err(format!(
689 "{} is the only {} track: every import lands on it",
690 lane.label(),
691 match lane.kind {
692 LaneKind::Video => "video",
693 LaneKind::Audio => "audio",
694 }
695 )
696 .into());
697 }
698 let clips = &self.lanes[i].clips;
699 if !clips.is_empty() {
700 // Three names and a count: a lane can hold forty clips and a
701 // refusal nobody reads to the end says nothing at all.
702 let named: Vec<String> = clips
703 .iter()
704 .take(3)
705 .map(|c| {
706 let name = self.sources.get(c.source).map_or_else(
707 || format!("source {}", c.source),
708 |s| s.path.display().to_string(),
709 );
710 format!("{name} at frame {}", c.start)
711 })
712 .collect();
713 let rest = match clips.len().saturating_sub(named.len()) {
714 0 => String::new(),
715 n => format!(" and {n} more"),
716 };
717 return Err(format!(
718 "{} still holds {}{rest}: delete those clips (or drag them to \
719 another track) first",
720 lane.label(),
721 named.join(", ")
722 )
723 .into());
724 }
725 self.snapshot();
726 self.lanes.remove(i);
727 Ok(())
728 }
729
730 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
731 /// not there. The one place a handle becomes a position.
732 fn index(&self, lane: Lane) -> Option<usize> {
733 self.lanes
734 .iter()
735 .enumerate()
736 .filter(|(_, l)| l.kind == lane.kind)
737 .map(|(i, _)| i)
738 .nth(lane.ord)
739 }
740
741 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
742 let i = self.index(lane)?;
743 Some(&mut self.lanes[i].clips)
744 }
745
746 /// The files the clips index into, in import order; index 0 is the file the
747 /// project was opened with.
748 pub fn sources(&self) -> &[Source] {
749 &self.sources
750 }
751
752 /// The same list in the `(path, stream)` shape the audio engine indexes
753 /// into -- [`crate::AudioSession::open_multi_streams`] and
754 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
755 /// was placed with is the stream that plays *and* the stream that exports.
756 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
757 self.sources
758 .iter()
759 .map(|s| (s.path.clone(), s.audio_stream))
760 .collect()
761 }
762
763 /// Index for `path` played on `audio_stream`, appending it if it is new.
764 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
765 /// by two paths imports once and two streams of one file are two sources.
766 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
767 /// no history: a source entry alone changes nothing playable.
768 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
769 let source = Source::new(path, audio_stream);
770 match self.sources.iter().position(|s| *s == source) {
771 Some(idx) => idx,
772 None => {
773 self.sources.push(source);
774 self.sources.len() - 1
775 }
776 }
777 }
778
779 /// Append a whole-file clip of `source` to the end of *every* lane, grouped
780 /// -- an import lands as one take. One history snapshot, so an import is one
781 /// undo step, and undoing it leaves the (harmless) source entry behind,
782 /// because indexes are forever. Refused for an unknown source index.
783 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
784 if source >= self.sources.len() {
785 return false;
786 }
787 self.snapshot();
788 let start = self.timeline_frames();
789 let clip = Clip {
790 start,
791 in_frame: 0,
792 out_frame: frame_count.max(1),
793 source,
794 link: Some(self.new_link()),
795 eq: None,
796 color: None,
797 fit: FitPolicy::default(),
798 speed: Speed::NORMAL,
799 };
800 for data in &mut self.lanes {
801 data.clips.push(clip);
802 }
803 true
804 }
805
806 /// Drops a source entry -- the file a library row *is* -- and renumbers
807 /// every clip that indexed past it, which is why this is more than a
808 /// `Vec::remove`.
809 ///
810 /// Refused, changing nothing, while any clip still plays from it: the
811 /// refusal names the lanes and how many clips each holds, so a caller can
812 /// say what has to be deleted first. The *last* entry goes like any other
813 /// -- a project may name no file at all, which is an empty library over an
814 /// empty timeline (nothing can play, since a clip would have refused the
815 /// removal). What a front-end does with that is its own decision: `edith`'s
816 /// window goes back to the empty state it launches in, and
817 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
818 /// refuses to write a project that names nothing, because no such file
819 /// could be opened again.
820 ///
821 /// Every index past `idx` moves down by one, so a caller holding a *raw*
822 /// source index of its own -- a clipboard, which is the one thing outside
823 /// this type that does -- has to fix it up or drop it, or a paste plays a
824 /// different file. [`PlaybackSession::remove_source`] hands back the index
825 /// that went for exactly that.
826 ///
827 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
828 /// snapshot older than the removal can name the very source being removed
829 /// (delete a file's clips, then remove the file) and restoring it would
830 /// point a clip at an entry that is gone. The upgrade path is snapshotting
831 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
832 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
833 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
834 /// exists) currently rules out.
835 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
836 let Some(source) = self.sources.get(idx) else {
837 return Err(format!("there is no source {idx} to remove").into());
838 };
839 let name = source.path.display().to_string();
840 let used: Vec<String> = handles(&self.lanes)
841 .into_iter()
842 .zip(&self.lanes)
843 .filter_map(
844 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
845 0 => None,
846 1 => Some(format!("{} (1 clip)", lane.label())),
847 n => Some(format!("{} ({n} clips)", lane.label())),
848 },
849 )
850 .collect();
851 if !used.is_empty() {
852 return Err(format!("{name} still plays on {}", used.join(", ")).into());
853 }
854 self.sources.remove(idx);
855 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
856 if c.source > idx {
857 c.source -= 1;
858 }
859 }
860 self.history.clear();
861 Ok(())
862 }
863
864 /// The sources a clip actually names, with the clips reindexed onto them
865 /// -- what a save writes. Indexes are forever *inside* a session (see
866 /// [`Project::append_clip`]), so an undone import leaves an orphan source
867 /// entry behind; writing that orphan to a project file would let a file
868 /// nothing plays refuse a future load. New indexes are assigned in order of
869 /// first use -- lane by lane, in display order -- so the same project always
870 /// emits the same bytes.
871 ///
872 /// Every lane comes out, in display order and with its kind: that is what a
873 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
874 /// takes back.
875 ///
876 /// The equalizer and colour tables are pruned the same way and for the same
877 /// reason: an undone [`set_eq`](Project::set_eq) or
878 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
879 /// and this is the one moment they can go -- the indexes that survive it are
880 /// only the ones a clip names.
881 ///
882 /// One exception, and it is the emptied timeline's: a project no clip plays
883 /// from still keeps its first source, if it has one. A file is what a
884 /// reopened project scaffolds itself from -- the frame rate is written
885 /// nowhere else -- so a save that pruned the last of them would write a
886 /// project that cannot be loaded back at all.
887 ///
888 /// What comes out is *not* ordered by anything a reader may assume: first
889 /// use, lane by lane, means the entry at index 0 can be a still or a song
890 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
891 /// picks its rate and its audio reference by what a source *is*, never by
892 /// where it sits.
893 pub fn without_orphan_sources(&self) -> Parts {
894 let mut moved = vec![None; self.sources.len()];
895 let mut sources = Vec::new();
896 let mut moved_eq = vec![None; self.eq.len()];
897 let mut eq = Vec::new();
898 let mut moved_color = vec![None; self.color.len()];
899 let mut color = Vec::new();
900 let mut lanes = self.lanes.clone();
901 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
902 let old = c.source;
903 c.source = match moved[old] {
904 Some(new) => new,
905 None => {
906 sources.push(self.sources[old].clone());
907 moved[old] = Some(sources.len() - 1);
908 sources.len() - 1
909 }
910 };
911 if let Some(old) = c.eq.map(usize::from) {
912 c.eq = Some(match moved_eq[old] {
913 Some(new) => new,
914 None => {
915 eq.push(self.eq[old].clone());
916 let new = (eq.len() - 1) as u16;
917 moved_eq[old] = Some(new);
918 new
919 }
920 });
921 }
922 if let Some(old) = c.color.map(usize::from) {
923 c.color = Some(match moved_color[old] {
924 Some(new) => new,
925 None => {
926 color.push(self.color[old]);
927 let new = (color.len() - 1) as u16;
928 moved_color[old] = Some(new);
929 new
930 }
931 });
932 }
933 }
934 if sources.is_empty() {
935 sources.extend(self.sources.first().cloned());
936 }
937 (
938 sources,
939 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
940 eq,
941 color,
942 )
943 }
944
945 /// What the clip at `idx` of `lane` plays through, or `None` for one that
946 /// plays flat (and for an index that is not there) -- what a feeder and an
947 /// export ask before they build an [`crate::eq::EqState`].
948 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
949 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
950 }
951
952 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
953 /// take them off. One undo step, like every other edit. `false` -- and no
954 /// history -- for an index that is not there and for params holding a value
955 /// that is not finite, which is the one thing the file format could not
956 /// write and read back.
957 ///
958 /// Settings equal to ones already in the table share their entry, so a
959 /// project that puts the same curve on twenty clips writes it once.
960 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
961 if idx >= self.lane(lane).len() {
962 return false;
963 }
964 let slot = match params {
965 None => None,
966 Some(params) => {
967 if !finite(&params) {
968 return false;
969 }
970 Some(match self.eq.iter().position(|p| *p == params) {
971 Some(at) => at as u16,
972 // ponytail: the table is append-only within a session (see
973 // the module docs) and `Clip::eq` is a u16, so the 65535th
974 // *distinct* setting of one session is refused rather than
975 // silently aliased. Upgrade path if a UI ever drags a slider
976 // that far: widen `Clip::eq` to u32 (Clip has the room) or
977 // snapshot the table into the history and compact it here.
978 None if self.eq.len() >= usize::from(u16::MAX) => return false,
979 None => {
980 self.eq.push(params);
981 (self.eq.len() - 1) as u16
982 }
983 })
984 }
985 };
986 self.snapshot();
987 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
988 true
989 }
990
991 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
992 /// ungraded (and for an index that is not there) -- what the renderer and
993 /// the export ask before they call [`crate::color::apply_yuv`].
994 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
995 self.color
996 .get(usize::from(self.lane(lane).get(idx)?.color?))
997 }
998
999 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
1000 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
1001 /// (and no history) for an index that is not there or a value that is not
1002 /// finite, and equal settings share a table entry.
1003 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1004 self.write_color(lane, idx, params, true)
1005 }
1006
1007 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
1008 /// one pointer drag, whose first write (a plain `set_color`) already took the
1009 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
1010 /// not one per pixel -- and undoing it lands where the hand picked it up.
1011 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1012 self.write_color(lane, idx, params, false)
1013 }
1014
1015 fn write_color(
1016 &mut self,
1017 lane: Lane,
1018 idx: usize,
1019 params: Option<ColorParams>,
1020 snapshot: bool,
1021 ) -> bool {
1022 if idx >= self.lane(lane).len() {
1023 return false;
1024 }
1025 let slot = match params {
1026 None => None,
1027 Some(params) => {
1028 if !color_finite(&params) {
1029 return false;
1030 }
1031 Some(match self.color.iter().position(|p| *p == params) {
1032 Some(at) => at as u16,
1033 // ponytail: the 65535th *distinct* grade of one session is
1034 // refused rather than silently aliased, exactly as `set_eq`
1035 // refuses the 65535th curve; same upgrade path.
1036 None if self.color.len() >= usize::from(u16::MAX) => return false,
1037 None => {
1038 self.color.push(params);
1039 (self.color.len() - 1) as u16
1040 }
1041 })
1042 }
1043 };
1044 if snapshot {
1045 self.snapshot();
1046 }
1047 self.lane_mut(lane).expect("checked above")[idx].color = slot;
1048 true
1049 }
1050
1051 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
1052 /// index that is not there, which is what every clip starts at anyway.
1053 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
1054 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
1055 }
1056
1057 /// Sets it, for the clip **and its whole group**: a link is one span on
1058 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
1059 /// from its sound would be a group no save could load. One snapshot, so the
1060 /// group's change is one [`Project::undo`].
1061 ///
1062 /// The source range is untouched -- a speed says how many timeline frames
1063 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
1064 /// split still address the file afterwards.
1065 ///
1066 /// Refused, changing nothing and costing no undo step, when the clip would
1067 /// grow into the one after it on its own lane: slowing a clip down makes it
1068 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
1069 /// the way -- by lane and timeline frame -- because "it did not fit" is not
1070 /// something a user can go and fix. Also for an index that is not there.
1071 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
1072 self.write_speed(lane, idx, speed, true)
1073 }
1074
1075 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
1076 /// one pointer drag, whose first write (a plain `set_speed`) already took the
1077 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
1078 /// not one per rate it passed through -- exactly as
1079 /// [`set_color_live`](Self::set_color_live) is for a slider.
1080 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
1081 self.write_speed(lane, idx, speed, false)
1082 }
1083
1084 fn write_speed(
1085 &mut self,
1086 lane: Lane,
1087 idx: usize,
1088 speed: Speed,
1089 snapshot: bool,
1090 ) -> crate::Result<()> {
1091 let Some(members) = self.group_of(lane, idx) else {
1092 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
1093 };
1094 let labels = handles(&self.lanes);
1095 let mut span: Option<(Lane, u32, u32)> = None;
1096 for &(l, i) in &members {
1097 let clips = &self.lanes[l].clips;
1098 let mut moved = clips[i];
1099 moved.speed = speed;
1100 if let Some(next) = clips.get(i + 1)
1101 && moved.end() > next.start
1102 {
1103 let name = labels[l].label();
1104 return Err(format!(
1105 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
1106 move it along, or trim this one first",
1107 moved.end(),
1108 next.start
1109 )
1110 .into());
1111 }
1112 // A link is **one span on however many lanes**
1113 // ([`links_are_consistent`]), and one rate over two halves does not
1114 // guarantee that: two clips of *different source lengths* can occupy
1115 // the same timeline frames at their old rates (rounding collapses
1116 // neighbouring lengths onto one footprint at 4x), and re-rating them
1117 // pulls those footprints apart. Refused by name rather than written
1118 // -- a group whose halves disagree about their span is a project
1119 // that would not load again.
1120 match span {
1121 None => span = Some((labels[l], moved.start, moved.end())),
1122 Some((first, start, end)) if (start, end) != (moved.start, moved.end()) => {
1123 return Err(format!(
1124 "at {speed} the {} half would cover [{}, {}) and the {} half [{start}, {end}): \
1125 they are one take and a take is one span -- detach them first",
1126 labels[l].label(),
1127 moved.start,
1128 moved.end(),
1129 first.label()
1130 )
1131 .into());
1132 }
1133 Some(_) => {}
1134 }
1135 }
1136 if snapshot {
1137 self.snapshot();
1138 }
1139 for (l, i) in members {
1140 self.lanes[l].clips[i].speed = speed;
1141 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1142 }
1143 debug_assert!(links_are_consistent(&self.lanes).is_ok());
1144 Ok(())
1145 }
1146
1147 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
1148 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
1149 /// every clip starts at anyway.
1150 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
1151 self.lane(lane)
1152 .get(idx)
1153 .map_or(FitPolicy::default(), |c| c.fit)
1154 }
1155
1156 /// Sets it. One undo step like every other edit, and `false` (with no
1157 /// history) for an index that is not there. Unlike an eq or a grade there is
1158 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
1159 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
1160 if idx >= self.lane(lane).len() {
1161 return false;
1162 }
1163 self.snapshot();
1164 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
1165 true
1166 }
1167
1168 /// Length of the timeline in frames: where the *last* lane runs out. A lane
1169 /// that ends early is a trailing gap in that lane, not a shorter timeline.
1170 pub fn timeline_frames(&self) -> u32 {
1171 self.lanes
1172 .iter()
1173 .filter_map(|l| l.clips.last().map(Clip::end))
1174 .max()
1175 .unwrap_or(0)
1176 }
1177
1178 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
1179 /// to lay clips out. Gaps show up as the holes between consecutive entries.
1180 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
1181 self.lane_spans(Lane::V1)
1182 }
1183
1184 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
1185 // Timeline frames, not source ones: a box on a lane is as wide as the
1186 // clip is long *there*, which a speed halves or quadruples.
1187 self.lane(lane)
1188 .iter()
1189 .map(|c| (c.start, c.frames()))
1190 .collect()
1191 }
1192
1193 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
1194 /// and past the end -- [`Project::span_at`] is the version that tells those
1195 /// two apart.
1196 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
1197 let clips = self.lane(lane);
1198 let idx = at(clips, timeline_frame)?;
1199 Some((idx, source_frame(&clips[idx], timeline_frame)))
1200 }
1201
1202 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
1203 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
1204 self.map(Lane::V1, timeline_frame)
1205 }
1206
1207 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
1208 /// it, or the gap running to the next clip (or to the end of the timeline,
1209 /// which is where a lane shorter than its neighbour keeps showing black).
1210 /// `None` at or past the end of the timeline, which is the only "nothing
1211 /// left" there is.
1212 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
1213 let total = self.timeline_frames();
1214 if timeline_frame >= total {
1215 return None;
1216 }
1217 let clips = self.lane(lane);
1218 Some(match at(clips, timeline_frame) {
1219 Some(idx) => Span {
1220 start: timeline_frame,
1221 len: clips[idx].end() - timeline_frame,
1222 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
1223 speed: clips[idx].speed,
1224 },
1225 None => Span {
1226 start: timeline_frame,
1227 speed: Speed::NORMAL,
1228 // The next placement, or the end of the timeline: a gap is
1229 // bounded by what comes after it, never by its own bookkeeping.
1230 len: clips
1231 .iter()
1232 .find(|c| c.start > timeline_frame)
1233 .map_or(total, |c| c.start)
1234 - timeline_frame,
1235 from: None,
1236 },
1237 })
1238 }
1239
1240 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
1241 /// gaps included -- the whole play list, which is what an export walks.
1242 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
1243 let mut out = Vec::new();
1244 let mut t = timeline_frame;
1245 while let Some(span) = self.span_at(lane, t) {
1246 t = span.end();
1247 out.push(span);
1248 }
1249 out
1250 }
1251
1252 /// What the *composite* shows from `timeline_frame` on -- the answer
1253 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
1254 /// video lane by one rule: **the topmost lane with a clip there wins**, and
1255 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
1256 /// (the usual overlay convention). A frame no video lane covers is a gap,
1257 /// which is black however many lanes are above or below it.
1258 ///
1259 /// No blending, so exactly one lane is visible at a time and the composite
1260 /// is itself a span list -- which is why one decoder plays it, the same one
1261 /// a single-lane timeline uses, rather than N running at once.
1262 ///
1263 /// The span is cut short wherever a *higher* lane's clip starts, because
1264 /// from that frame on a different lane wins; that is what makes walking
1265 /// [`composite_spans_from`](Project::composite_spans_from) correct.
1266 ///
1267 /// ponytail: alpha, opacity or any blend mode makes this untrue -- two
1268 /// lanes would then be visible in one frame and the caller needs a decoder
1269 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
1270 /// (this same walk, per lane) feeding N decoders.
1271 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
1272 let total = self.timeline_frames();
1273 if timeline_frame >= total {
1274 return None;
1275 }
1276 let video = self.video_lanes();
1277 // The last covering lane is the winner; only the lanes above it can
1278 // interrupt what it shows.
1279 let winner = video
1280 .iter()
1281 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
1282 let (from, speed, until) = match winner {
1283 Some(i) => {
1284 let clips = self.lane(video[i]);
1285 let idx = at(clips, timeline_frame).expect("just found above");
1286 (
1287 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
1288 clips[idx].speed,
1289 clips[idx].end(),
1290 )
1291 }
1292 // Nothing covers it: black until something above the floor starts.
1293 None => (None, Speed::NORMAL, total),
1294 };
1295 let takeover = video[winner.map_or(0, |i| i + 1)..]
1296 .iter()
1297 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
1298 .map(|c| c.start)
1299 .min();
1300 Some(Span {
1301 start: timeline_frame,
1302 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
1303 from,
1304 speed,
1305 })
1306 }
1307
1308 /// The video lanes in display order, topmost last -- the order the composite
1309 /// rule counts in.
1310 fn video_lanes(&self) -> Vec<Lane> {
1311 self.lanes()
1312 .into_iter()
1313 .filter(|l| l.kind == LaneKind::Video)
1314 .collect()
1315 }
1316
1317 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
1318 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
1319 /// index on that lane. `None` over a gap and past the end. What a front-end
1320 /// asks to act on "the clip on screen" without re-deriving the rule.
1321 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
1322 let video = self.video_lanes();
1323 let winner = video
1324 .iter()
1325 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
1326 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
1327 }
1328
1329 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
1330 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
1331 /// answers "the clip on screen"; this answers it per lane, which is what
1332 /// walking the lanes for something to select needs.
1333 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
1334 at(self.lane(lane), timeline_frame)
1335 }
1336
1337 /// How the composite is graded at `timeline_frame`, so the picture playback
1338 /// converts and the one an export encodes are graded from one answer.
1339 /// `None` over a gap (black is black) and for a clip nobody has graded,
1340 /// which is the byte-identical path everywhere.
1341 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
1342 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
1343 self.color_of(lane, idx)
1344 }
1345
1346 /// How the composite meets the project canvas at `timeline_frame`, so the
1347 /// picture playback composes and the one an export encodes are placed from
1348 /// one answer. `Fit` over a gap, where black is already the canvas.
1349 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
1350 self.composite_clip_at(timeline_frame)
1351 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
1352 }
1353
1354 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
1355 /// viewer sees from `timeline_frame` to the end, in order. What an export
1356 /// encodes and what playback walks at a clip boundary.
1357 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
1358 let mut out = Vec::new();
1359 let mut t = timeline_frame;
1360 while let Some(span) = self.composite_span_at(t) {
1361 t = span.end();
1362 out.push(span);
1363 }
1364 out
1365 }
1366
1367 /// Split every lane at `timeline_frame`, so that frame becomes the first
1368 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
1369 /// (`false`, no change) when no lane has a clip to split there -- at a
1370 /// placement's own start, in a gap, and past the end -- all of which would
1371 /// produce an empty clip or nothing at all.
1372 ///
1373 /// Lanes' halves share an id only where they are the *same* span: the lanes
1374 /// are edited apart, so the clip being cut here may start (or end)
1375 /// somewhere else on another lane, and a group id whose clips disagree
1376 /// about their span is not one take (see [`links_are_consistent`], which
1377 /// refuses to load one).
1378 ///
1379 /// Metadata only: no mapping changes, in any lane.
1380 pub fn split(&mut self, timeline_frame: u32) -> bool {
1381 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
1382 }
1383
1384 /// [`split`](Project::split), with the snapshot optional and the lanes
1385 /// named: a batch that has already taken a snapshot
1386 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
1387 /// region and must still be one undo press, and a *scoped* batch must not
1388 /// cut a lane it was told to leave alone.
1389 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
1390 let cut: Vec<Option<Clip>> = self
1391 .lanes
1392 .iter()
1393 .enumerate()
1394 .map(|(i, l)| {
1395 on.contains(&i)
1396 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
1397 .flatten()
1398 })
1399 .collect();
1400 if cut.iter().all(Option::is_none) {
1401 return false;
1402 }
1403 if snapshot {
1404 self.snapshot();
1405 }
1406 // Each side is its own question: two clips may start together and end
1407 // apart, and every lane whose halves do line up stays one take.
1408 let starts: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.start)).collect();
1409 let ends: Vec<Option<u32>> = cut.iter().map(|c| c.map(|c| c.end())).collect();
1410 let left = self.group_ids(&starts);
1411 let right = self.group_ids(&ends);
1412 for (((data, left), right), cut) in self
1413 .lanes
1414 .iter_mut()
1415 .zip(left)
1416 .zip(right)
1417 .zip(cut.iter().map(Option::is_some))
1418 {
1419 // The lanes this call was not scoped to are not cut, whatever their
1420 // own clips would allow.
1421 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut) else {
1422 continue;
1423 };
1424 let mut tail = data.clips[idx];
1425 // Where the cut lands *in the file*, which is the clip's own rate
1426 // away from where it lands on the timeline. Both halves keep the
1427 // speed, and `splittable` has already refused any frame at which
1428 // the two would not add up to the one being cut.
1429 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
1430 tail.start = timeline_frame;
1431 tail.link = right;
1432 data.clips[idx].out_frame = tail.in_frame;
1433 data.clips[idx].link = left;
1434 data.clips.insert(idx + 1, tail);
1435 }
1436 true
1437 }
1438
1439 /// The inverse of [`split`](Project::split): rejoin the placements that meet
1440 /// at `timeline_frame` in every lane and put the result back in one group.
1441 /// Only what a split could have produced is rejoined -- the two sides must
1442 /// touch on the timeline *and* be consecutive frames of the same source --
1443 /// so the clip list comes back exactly as it was and traversal with it.
1444 /// `false` when no lane has such a pair. The rejoined clips share one id
1445 /// only when they rejoin into the same span, for [`split`](Project::split)'s
1446 /// reason.
1447 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
1448 // What each lane would end up covering, if it joins here at all.
1449 let joined: Vec<Option<(u32, u32)>> = self
1450 .lanes
1451 .iter()
1452 .map(|l| {
1453 joinable(&l.clips, timeline_frame)
1454 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
1455 })
1456 .collect();
1457 if joined.iter().all(Option::is_none) {
1458 return false;
1459 }
1460 self.snapshot();
1461 let ids = self.group_ids(&joined);
1462 for (data, link) in self.lanes.iter_mut().zip(ids) {
1463 let Some(idx) = joinable(&data.clips, timeline_frame) else {
1464 continue;
1465 };
1466 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
1467 data.clips[idx].link = link;
1468 data.clips.remove(idx + 1);
1469 }
1470 true
1471 }
1472
1473 /// Take the clip at `idx` of `lane` out of its group: every clip carrying
1474 /// its id -- on however many lanes -- is handed an id of its own, so from
1475 /// here on each half moves, trims and is deleted alone. The music video
1476 /// whose sound is to be cut against its picture starts here.
1477 ///
1478 /// An id of its own rather than none at all: a half no other lane is grouped
1479 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
1480 /// (see [`links_are_consistent`]), and it is what a front-end already draws
1481 /// as detached. `None` would instead say "was never part of a take", which
1482 /// is what a one-lane [`place`](Project::place) means.
1483 ///
1484 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
1485 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
1486 /// the group back. Refused (`false`, nothing changed) for an index that is
1487 /// not there, a clip in no group at all, and one whose group has no other
1488 /// half -- that one is already detached, and a refusal must not cost an undo
1489 /// step.
1490 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
1491 let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else {
1492 return false;
1493 };
1494 let members = self
1495 .lanes
1496 .iter()
1497 .flat_map(|l| &l.clips)
1498 .filter(|c| c.link == Some(id))
1499 .count();
1500 if members < 2 {
1501 return false;
1502 }
1503 self.snapshot();
1504 // Drawn before the walk: `new_link` takes the whole project, and the
1505 // walk holds the lanes.
1506 let mut fresh = (0..members).map(|_| self.new_link()).collect::<Vec<_>>();
1507 for data in &mut self.lanes {
1508 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
1509 c.link = fresh.pop();
1510 }
1511 }
1512 debug_assert!(links_are_consistent(&self.lanes).is_ok());
1513 true
1514 }
1515
1516 /// Put two clips on two lanes into one group, so what moves one moves the
1517 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
1518 /// how a picture is regrouped with sound it was never opened with. Whatever
1519 /// either of them was grouped with comes along: those clips cover this same
1520 /// span already, so the result is one group and not two overlapping ones.
1521 ///
1522 /// Same frames or nothing: a group id names **one span** on however many
1523 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
1524 /// clips that do not cover the same frames cannot be one take, and the
1525 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
1526 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
1527 /// mean, not the rule.
1528 ///
1529 /// Metadata only, one snapshot. The error says what is wrong, because
1530 /// `false` would not: a bad index, one lane twice (a group is at most one
1531 /// clip per lane), spans that disagree, and a pair that is already one take
1532 /// -- nothing changes, and none of them costs an undo step.
1533 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
1534 if a == b {
1535 return Err(format!(
1536 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
1537 a.label()
1538 )
1539 .into());
1540 }
1541 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
1542 p.lane(lane)
1543 .get(idx)
1544 .copied()
1545 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
1546 };
1547 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
1548 if (x.start, x.end()) != (y.start, y.end()) {
1549 return Err(format!(
1550 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
1551 a.label(),
1552 x.start,
1553 x.end(),
1554 b.label(),
1555 y.start,
1556 y.end()
1557 )
1558 .into());
1559 }
1560 if x.link.is_some() && x.link == y.link {
1561 return Err("those two are one take already".into());
1562 }
1563 self.snapshot();
1564 let id = self.new_link();
1565 // Every clip either of them was grouped with, by the same rule: all of
1566 // them cover this span, so one id over the lot stays consistent.
1567 let old = [x.link, y.link];
1568 for data in &mut self.lanes {
1569 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
1570 if old.contains(&c.link) {
1571 c.link = Some(id);
1572 }
1573 }
1574 }
1575 // And the two themselves, which a `place` may have left in no group.
1576 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
1577 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
1578 debug_assert!(links_are_consistent(&self.lanes).is_ok());
1579 Ok(())
1580 }
1581
1582 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
1583 /// lands on and leaving every other clip exactly where it is -- the
1584 /// per-lane paste. Anything already there is trimmed away (and split in two
1585 /// if `clip` lands inside it), which is what keeps the lane sorted and
1586 /// disjoint; nothing ripples, so a gap before the placement simply stays a
1587 /// gap. Refused only for an empty `clip`.
1588 ///
1589 /// The placement belongs to no group: a clipboard clip carries the link id
1590 /// of the take it was copied from, and placing it twice -- or placing a copy
1591 /// back over the clip it came from -- would put that id on two clips of one
1592 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
1593 /// `None` rather than a fresh id because a one-lane placement has nothing on
1594 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
1595 /// become a group again.
1596 ///
1597 /// Refused for an empty `clip` and for a lane that is not there.
1598 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
1599 if clip.out_frame <= clip.in_frame || self.index(lane).is_none() {
1600 return false;
1601 }
1602 self.snapshot();
1603 let clip = Clip {
1604 start: timeline_frame,
1605 link: None,
1606 ..clip
1607 };
1608 let clips = self.lane_mut(lane).expect("checked above");
1609 clear(clips, clip.start, clip.end());
1610 let idx = clips.partition_point(|c| c.start < clip.start);
1611 clips.insert(idx, clip);
1612 debug_assert!(sorted_disjoint(clips));
1613 true
1614 }
1615
1616 /// Move the clip at `idx` of `from` onto `to`, keeping the timeline frames
1617 /// it covers: the drag that rearranges takes across tracks. One snapshot, so
1618 /// one [`Project::undo`] puts it back where it was.
1619 ///
1620 /// Its group id travels with it, and that is not a desync: a link means
1621 /// "these cover one span on however many lanes" and names no lane at all
1622 /// (see [`links_are_consistent`]), so a picture moved from `V1` to `V2` is
1623 /// still the same take as the sound under it. The span never changes here --
1624 /// only which lane draws it.
1625 ///
1626 /// Refused, changing nothing, for a lane that is not there, an index that is
1627 /// not there, a move onto the lane it is already on, a move across *kinds*
1628 /// (a picture cannot play on an audio lane, and the save it wrote would not
1629 /// open again), and a landing that would touch another clip -- a move that
1630 /// overwrote what it landed on would destroy a take the pointer never named,
1631 /// which is what [`place`](Project::place) may do and a drag may not.
1632 pub fn move_to_lane(&mut self, from: Lane, idx: usize, to: Lane) -> bool {
1633 if from.kind != to.kind || from == to || self.index(to).is_none() {
1634 return false;
1635 }
1636 let Some(clip) = self.lane(from).get(idx).copied() else {
1637 return false;
1638 };
1639 if self
1640 .lane(to)
1641 .iter()
1642 .any(|c| c.start < clip.end() && clip.start < c.end())
1643 {
1644 return false;
1645 }
1646 self.snapshot();
1647 self.lane_mut(from).expect("checked above").remove(idx);
1648 let clips = self.lane_mut(to).expect("checked above");
1649 let at = clips.partition_point(|c| c.start < clip.start);
1650 clips.insert(at, clip);
1651 debug_assert!(sorted_disjoint(clips));
1652 true
1653 }
1654
1655 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1656 /// the drag on a clip's end that makes it play more or less of its source.
1657 /// The rest of the lane stays exactly where it is (nothing ripples), so what
1658 /// a shortened clip leaves behind is a gap and what a lengthened one takes
1659 /// is room that was already empty. One snapshot, so a whole drag is one
1660 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1661 /// sample. Changes the timeline->source mapping: the caller must reseek.
1662 ///
1663 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1664 /// exactly what they played before, which is what makes this a trim and not
1665 /// a slip.
1666 ///
1667 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1668 /// legal means "as far as it goes", and stopping the box there is the
1669 /// affordance. The walls are: one frame of clip always survives, an edge
1670 /// never crosses the neighbouring clip on its own lane, an in-point never
1671 /// walks back past the source's first frame, and an out-point never runs
1672 /// past `source_frames[clip.source]` -- the caller's table of how long each
1673 /// source actually is ([`Project`] does not know, and a clip ending past its
1674 /// file's last frame is a save that will not open again; see
1675 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1676 /// there may not grow at all.
1677 ///
1678 /// Linked clips trim *together*, to one clamped edge: a link is one span on
1679 /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1680 /// from its sound would be a group no save could load. The room is therefore
1681 /// what every member of the group has -- the tightest wall wins.
1682 ///
1683 /// `false`, changing nothing and costing no undo step, for an index that is
1684 /// not there and for an edge that is already where it was asked to go.
1685 pub fn trim(
1686 &mut self,
1687 lane: Lane,
1688 idx: usize,
1689 edge: Edge,
1690 to: u32,
1691 source_frames: &[u32],
1692 ) -> bool {
1693 let (Some((lo, hi)), Some(clip)) = (
1694 self.trim_room(lane, idx, edge, source_frames),
1695 self.lane(lane).get(idx).copied(),
1696 ) else {
1697 return false;
1698 };
1699 let to = to.clamp(lo, hi);
1700 let at = match edge {
1701 Edge::Start => clip.start,
1702 Edge::End => clip.end(),
1703 };
1704 if to == at {
1705 return false;
1706 }
1707 // Worked out before anything moves: at a slow rate a room can be too
1708 // narrow to hold even one source frame ([`Speed::fit`]), and a member
1709 // that cannot fit must refuse the whole gesture rather than be given a
1710 // range wider than its room -- which is the overlap the lane invariant
1711 // exists to forbid. The walls below leave that room, so this is the
1712 // backstop for a project that came in through another door.
1713 let members = self.group_of(lane, idx).expect("checked above");
1714 let mut fitted = Vec::with_capacity(members.len());
1715 for &(l, i) in &members {
1716 let c = self.lanes[l].clips[i];
1717 let room = match edge {
1718 // The frames that stay play what they played, so what survives
1719 // is measured from the *end*.
1720 Edge::Start => c.end() - to,
1721 Edge::End => to - c.start,
1722 };
1723 match c.speed.fit(room) {
1724 // Not clamped to the clip's current length: an out-point trim
1725 // *grows* the range, and the source wall in `hi` is what bounds
1726 // that. The in-point's own clamp is at the write below.
1727 Some(keep) => fitted.push(keep),
1728 None => return false,
1729 }
1730 }
1731 self.snapshot();
1732 for (&(l, i), keep) in members.iter().zip(fitted) {
1733 let still = self.is_still(&self.lanes[l].clips[i]);
1734 let c = &mut self.lanes[l].clips[i];
1735 match edge {
1736 // A still has no earlier frame to walk an in-point back to --
1737 // every frame of it is the same picture -- so its head grows
1738 // *forward*: the range it plays is however long the new room
1739 // is, anchored at the source's frame 0. Bounded by `lo`, which
1740 // is where the cap in `source_frames` is applied.
1741 Edge::Start if still => {
1742 c.in_frame = 0;
1743 c.out_frame = keep;
1744 c.start = to;
1745 }
1746 Edge::Start => {
1747 // Non-negative by `lo`, which is what keeps the in-point on
1748 // the source.
1749 c.in_frame = c.out_frame - keep.min(c.out_frame);
1750 c.start = to;
1751 }
1752 // Never wider than the room the edge was clamped to: see
1753 // [`Speed::fit`].
1754 Edge::End => c.out_frame = c.in_frame + keep,
1755 }
1756 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1757 }
1758 true
1759 }
1760
1761 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1762 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1763 /// What a front-end drawing the box *during* a drag asks, so the live width
1764 /// is the width the release will commit and an edge stops under the pointer
1765 /// rather than snapping back. `None` for an index that is not there.
1766 pub fn trim_room(
1767 &self,
1768 lane: Lane,
1769 idx: usize,
1770 edge: Edge,
1771 source_frames: &[u32],
1772 ) -> Option<(u32, u32)> {
1773 let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1774 for (l, i) in self.group_of(lane, idx)? {
1775 let clips = &self.lanes[l].clips;
1776 let c = clips[i];
1777 let (member_lo, member_hi) = match edge {
1778 Edge::Start => (
1779 // Back to the source's own first frame -- as many *timeline*
1780 // frames as that head is worth at the clip's rate, which at
1781 // real time is the head itself -- and never over the clip in
1782 // front of it. Saturating because a clip may hold *more*
1783 // head than the timeline has room for -- a ripple delete
1784 // slides a clip back to frame 0 with its in-point wherever
1785 // the cut left it -- and frame 0 is the other wall.
1786 //
1787 // A still is measured from its *tail* instead: it has no
1788 // in-point worth the name (every frame the same picture), so
1789 // its head reaches exactly as far as its tail does -- out to
1790 // the length the caller's table gives it, whole. Measured
1791 // from the in-point it would have no head room at all, which
1792 // is a placed picture whose left edge cannot be dragged out.
1793 // No entry in the table means no growth, as it does at the
1794 // other end.
1795 if self.is_still(&c) {
1796 c.end().saturating_sub(
1797 c.speed
1798 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
1799 )
1800 } else {
1801 c.start.saturating_sub(c.speed.room(c.in_frame))
1802 }
1803 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1804 // One *frame of clip* always survives, and at a rate below
1805 // real time one frame of clip is several frames of timeline
1806 // ([`Speed::room`]): an edge dragged closer than that would
1807 // ask for a range no source frame fits in. At real time this
1808 // is `end - 1`, unchanged.
1809 c.end() - c.speed.room(1),
1810 ),
1811 Edge::End => (
1812 // ...and the same wall from the other end: the shortest this
1813 // clip can be is the room one source frame of it takes.
1814 c.start + c.speed.room(1),
1815 // Out to whatever is left of the source -- again in timeline
1816 // frames, at this clip's rate -- and never over the clip
1817 // behind it.
1818 c.start
1819 .saturating_add(
1820 c.speed.room(
1821 source_frames
1822 .get(c.source)
1823 .copied()
1824 .unwrap_or(c.out_frame)
1825 .saturating_sub(c.in_frame),
1826 ),
1827 )
1828 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1829 ),
1830 };
1831 lo = lo.max(member_lo);
1832 hi = hi.min(member_hi);
1833 }
1834 // `hi.max(lo)`: for a clip the invariants hold for, the range always
1835 // contains the edge's own place, and a caller's wrong `source_frames`
1836 // must not become an empty range (or a panicking `clamp`) here.
1837 Some((lo, hi.max(lo)))
1838 }
1839
1840 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
1841 /// every frame is the same picture, so which frame of it a clip's in-point
1842 /// names is not a question -- what [`Project::trim`] lets grow at either
1843 /// end. `false` for a source that is not there.
1844 fn is_still(&self, clip: &Clip) -> bool {
1845 self.sources
1846 .get(clip.source)
1847 .is_some_and(|s| crate::is_image(&s.path))
1848 }
1849
1850 /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1851 /// whatever carries its link on the other lanes -- as `(lane storage index,
1852 /// clip index)` pairs. `None` for an index that is not there.
1853 fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1854 let clip = *self.lane(lane).get(idx)?;
1855 Some(match clip.link {
1856 Some(link) => self
1857 .lanes
1858 .iter()
1859 .enumerate()
1860 .filter_map(|(l, data)| {
1861 Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1862 })
1863 .collect(),
1864 None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1865 })
1866 }
1867
1868 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
1869 /// new group, pushing everything from there on later by its length in
1870 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
1871 /// the clip it lands in is split around it; at or past the end of the
1872 /// timeline it is appended, because a paste means "put it here", not "put it
1873 /// here and leave black in front".
1874 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
1875 ///
1876 /// `V1` and `A1` and no other lane, because a take is one picture and one
1877 /// sound: copying it onto every lane there is would play the same audio
1878 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
1879 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
1880 /// video lane it is a clip that decodes to nothing, and a save carrying one
1881 /// does not open again -- and a still image ([`crate::is_image`]) reaches
1882 /// `V1` only, for the mirror of that reason. The room is still opened
1883 /// everywhere, or the lanes it was not inserted into would slide out of step
1884 /// with the ones it was.
1885 ///
1886 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
1887 /// Changes the timeline->source mapping: the caller must reseek. Refused for
1888 /// an empty `clip` and for one naming a source that is not there (both of
1889 /// which the public fields let a caller build), and for a paste whose ripple
1890 /// would push a clip past the last frame there is -- nothing is changed by
1891 /// any of them.
1892 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
1893 let Some(source) = self.sources.get(clip.source) else {
1894 return false;
1895 };
1896 if clip.out_frame <= clip.in_frame {
1897 return false;
1898 }
1899 let audio_only = crate::is_audio(&source.path);
1900 // ...and its mirror: a still is a picture and no sound, so a copy of one
1901 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
1902 // worker tries to demux -- which silences the *whole session*, not just
1903 // that clip -- and a save the engine's own `open_project` then refuses.
1904 let picture_only = crate::is_image(&source.path);
1905 let at = timeline_frame.min(self.timeline_frames());
1906 // The room it takes on the timeline, which its speed decides -- not the
1907 // source range it reads.
1908 let len = clip.frames();
1909 // Room for it: `open_room` adds `len` to every start from `at` on, and a
1910 // hand-written file may hold a clip that ends at the very last frame
1911 // (`edith::check` permits `start + len == u32::MAX`). Refused here
1912 // rather than wrapped there -- a wrapped start lands *behind* the clip
1913 // it belongs after, which is an overlap no save will read back.
1914 if at.checked_add(len).is_none()
1915 || self
1916 .lanes
1917 .iter()
1918 .flat_map(|l| &l.clips)
1919 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
1920 {
1921 return false;
1922 }
1923 // ...and room *to open*: the paste splits whatever it lands inside of,
1924 // and a speeded clip can only be cut where its own rate has a source
1925 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
1926 // of one, which is the overlap a lane may never hold. At real time every
1927 // frame answers, so this cannot refuse an unspeeded paste.
1928 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
1929 if self
1930 .lanes
1931 .iter()
1932 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
1933 {
1934 return false;
1935 }
1936 self.snapshot();
1937 let clip = Clip {
1938 start: at,
1939 link: Some(self.new_link()),
1940 ..clip
1941 };
1942 // Only lanes that can play the source: a file with no picture belongs on
1943 // an audio lane and nowhere else, exactly as `place_stream_at` decides
1944 // it for an import. On a video lane it would decode to nothing, and the
1945 // save it wrote would not open again.
1946 let kinds: &[LaneKind] = match (audio_only, picture_only) {
1947 (true, _) => &[LaneKind::Audio],
1948 (_, true) => &[LaneKind::Video],
1949 _ => &[LaneKind::Video, LaneKind::Audio],
1950 };
1951 let takes: Vec<usize> = kinds
1952 .iter()
1953 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
1954 .collect();
1955 for (i, data) in self.lanes.iter_mut().enumerate() {
1956 open_room(&mut data.clips, at, len);
1957 if takes.contains(&i) {
1958 let idx = data.clips.partition_point(|c| c.start < at);
1959 data.clips.insert(idx, clip);
1960 }
1961 debug_assert!(sorted_disjoint(&data.clips));
1962 }
1963 true
1964 }
1965
1966 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
1967 /// silence, and nothing else moves. Refused only for an out-of-range index
1968 /// (which a lane that is not there always is) -- lifting the last placement
1969 /// there is leaves an *empty* timeline, which is a state the project holds
1970 /// like any other and an undo brings back.
1971 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
1972 if idx >= self.lane(lane).len() {
1973 return false;
1974 }
1975 self.snapshot();
1976 self.lane_mut(lane).expect("checked above").remove(idx);
1977 true
1978 }
1979
1980 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
1981 /// the hole: everything after slides back by `len`. The rippling delete --
1982 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
1983 /// empty range; a delete that leaves nothing behind empties the timeline,
1984 /// which is a state like any other and one undo away.
1985 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
1986 if len == 0 {
1987 return false;
1988 }
1989 // Nothing reaches past `at`: there is nothing to cut and nothing to
1990 // slide back, and a delete that changes nothing must not cost an undo
1991 // step (see [`snapshot`](Project::snapshot)).
1992 if !self.lanes.iter().flat_map(|l| &l.clips).any(|c| c.end() > at) {
1993 return false;
1994 }
1995 self.snapshot();
1996 let on = all_lanes(&self.lanes);
1997 ripple(&mut self.lanes, &on, at, len);
1998 true
1999 }
2000
2001 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
2002 /// out of the lanes in `scope` and close each hole, as one edit: the
2003 /// jumpcut a silence scan asks for ([`crate::silence`]).
2004 ///
2005 /// A lane that is not in `scope` **does not move**, which is the whole
2006 /// point of the parameter: the silences of a podcast track come out
2007 /// without the music track under it sliding. `scope` is an arbitrary set of
2008 /// lanes and not a kind or a range, so a caller with its own idea of what
2009 /// is selected (a take, a track, everything) says it in lanes and nothing
2010 /// here has to learn about selection.
2011 ///
2012 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
2013 /// reason this exists rather than a caller's loop over
2014 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
2015 /// undo press, not forty. Cut back to front, so a region's frames still
2016 /// mean what the caller measured while the ones before it are cut.
2017 ///
2018 /// The list is sorted and overlapping entries are merged before anything is
2019 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
2020 /// other's frames. Refused, with no undo step, for an empty list, for a
2021 /// scope naming no lane that is there, and -- by name -- when the scope
2022 /// would take one half of a take with it
2023 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
2024 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
2025 let regions = tidy(regions);
2026 let on = self.scoped(scope)?;
2027 let Some(&(first, _)) = regions.first() else {
2028 return Err("nothing to cut".into());
2029 };
2030 self.scope_holds_takes_whole(&on, first)?;
2031 self.snapshot();
2032 for &(at, len) in regions.iter().rev() {
2033 ripple(&mut self.lanes, &on, at, len);
2034 }
2035 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2036 Ok(())
2037 }
2038
2039 /// The storage indices of `scope`, which is what every batch below walks.
2040 /// `Err` for a scope that names nothing there rather than a silent no-op:
2041 /// an edit asked for on a lane that is not there did not happen, and the
2042 /// caller has to hear so.
2043 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
2044 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
2045 match on.is_empty() {
2046 true => Err("no track to work on".into()),
2047 false => Ok(on),
2048 }
2049 }
2050
2051 /// The law a scoped ripple lives under: **a link is one span on however
2052 /// many lanes**, so a batch that moves one half of a take and not the other
2053 /// would leave a group whose halves disagree -- a project no save could
2054 /// load ([`links_are_consistent`]).
2055 ///
2056 /// Refused by name rather than widened silently. Widening would edit a
2057 /// track the user did not scope, which is exactly the surprise scoping
2058 /// exists to end; a front-end that wants the take is free to *say* the
2059 /// take's lanes, and to name them in what it tells the user afterwards.
2060 ///
2061 /// Only from `from` on: a take sitting entirely before the first cut does
2062 /// not move, so it is not this rule's business.
2063 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
2064 let labels = handles(&self.lanes);
2065 for &i in on {
2066 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
2067 let Some(id) = c.link else { continue };
2068 for (j, data) in self.lanes.iter().enumerate() {
2069 if on.contains(&j) {
2070 continue;
2071 }
2072 if let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) {
2073 return Err(format!(
2074 "the {} clip at frame {} is one take with the {} clip at frame {}: \
2075 moving one track of a take would pull it apart -- take the whole take, \
2076 or detach them first",
2077 labels[i].label(),
2078 c.start,
2079 labels[j].label(),
2080 half.start
2081 )
2082 .into());
2083 }
2084 }
2085 }
2086 }
2087 Ok(())
2088 }
2089
2090 /// Play every one of `regions` at `speed` instead of cutting it: each is
2091 /// split out of whatever covers it, re-rated, and the room it no longer
2092 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
2093 /// does not ripple, and a hole where a silence shrank is the one thing this
2094 /// must not leave. One snapshot for the lot, like
2095 /// [`cut_regions`](Project::cut_regions).
2096 ///
2097 /// The rate is **absolute**, not a multiplier on what is there: running it
2098 /// twice over the same stretch leaves it at `speed`, not at `speed`
2099 /// squared, so a second pass over an already-cut timeline changes nothing.
2100 ///
2101 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
2102 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
2103 ///
2104 /// Refused by name, with nothing changed and no undo step, when:
2105 ///
2106 /// * the scope would take one half of a take with it
2107 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
2108 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
2109 /// shrink by different amounts and the ripple would pull them apart,
2110 /// which is what cutting does not suffer and why delete mode has no such
2111 /// refusal;
2112 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
2113 /// piece could not be split out exactly;
2114 /// * two lanes' pieces would end up different lengths, which is a group
2115 /// whose halves disagree about their span (the refusal
2116 /// [`write_speed`](Project::write_speed) already makes, in its words);
2117 /// * the region would grow rather than shrink, i.e. it already plays faster
2118 /// than `speed`.
2119 pub fn speed_regions(
2120 &mut self,
2121 regions: &[(u32, u32)],
2122 speed: Speed,
2123 scope: &[Lane],
2124 ) -> crate::Result<()> {
2125 let regions = tidy(regions);
2126 let on = self.scoped(scope)?;
2127 let Some(&(first, _)) = regions.first() else {
2128 return Err("nothing to speed up".into());
2129 };
2130 self.scope_holds_takes_whole(&on, first)?;
2131 let labels = handles(&self.lanes);
2132 // Before anything is touched, because this is the refusal a person can
2133 // act on: a clip that laps over the edge of a silence has to be trimmed
2134 // (or the silences cut instead), and saying so after a rollback would
2135 // be saying it about a timeline that already looks different.
2136 for &(at, len) in &regions {
2137 for &l in &on {
2138 for c in &self.lanes[l].clips {
2139 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
2140 {
2141 return Err(format!(
2142 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
2143 speeding it up would pull the lanes apart -- trim it first, or cut the \
2144 silences out instead",
2145 labels[l].label(),
2146 c.start,
2147 at + len
2148 )
2149 .into());
2150 }
2151 }
2152 }
2153 }
2154 // The rest is checked as it is built: a split's own arithmetic is what
2155 // says whether a rate can address an edge. So the snapshot is taken
2156 // first and *rolled back* on a refusal -- one undo either way, and a
2157 // refusal still costs no step (`undo` pops the one just pushed).
2158 self.snapshot();
2159 for &(at, len) in regions.iter().rev() {
2160 self.write_split(at, false, &on);
2161 self.write_split(at + len, false, &on);
2162 let mut room: Option<(Lane, u32)> = None;
2163 let mut refused = None;
2164 for &l in &on {
2165 let clips = &self.lanes[l].clips;
2166 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
2167 if (c.start, c.end()) != (at, at + len) {
2168 // *Which* edge did not come off: a rate that cannot
2169 // address the end of the silence is not a rate that
2170 // cannot address its start, and naming the wrong frame
2171 // sends the user looking in the wrong place.
2172 let edge = match c.start == at {
2173 true => at + len,
2174 false => at,
2175 };
2176 refused = Some(format!(
2177 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
2178 detach it, or put it back to 1.00x first",
2179 labels[l].label(),
2180 c.start,
2181 c.speed
2182 ));
2183 continue;
2184 }
2185 let after = speed.frames(c.len());
2186 match room {
2187 None => room = Some((labels[l], after)),
2188 Some((first, n)) if n != after => {
2189 refused = Some(format!(
2190 "at {speed} the {} half of the silence at frame {at} would cover \
2191 {after} frames and the {} half {n}: they are one take and a take \
2192 is one span -- detach them first",
2193 labels[l].label(),
2194 first.label()
2195 ));
2196 }
2197 Some(_) => {}
2198 }
2199 }
2200 }
2201 let shrunk = match (refused, room) {
2202 (Some(e), _) => {
2203 self.undo();
2204 return Err(e.into());
2205 }
2206 // A gap on every lane: nothing to re-rate, and nothing to close.
2207 (None, None) => continue,
2208 (None, Some((_, after))) => after,
2209 };
2210 let Some(delta) = len.checked_sub(shrunk) else {
2211 self.undo();
2212 return Err(format!(
2213 "the silence at frame {at} already plays faster than {speed}: \
2214 at that rate it would be {shrunk} frames instead of {len}"
2215 )
2216 .into());
2217 };
2218 for &l in &on {
2219 for c in &mut self.lanes[l].clips {
2220 if c.start == at && c.end() == at + len {
2221 c.speed = speed;
2222 } else if c.start >= at + len {
2223 c.start -= delta;
2224 }
2225 }
2226 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2227 }
2228 }
2229 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2230 Ok(())
2231 }
2232
2233 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
2234 /// -- the whole-group delete a single-lane front-end means. `false` for a
2235 /// bad index. Changes the mapping: the caller must reseek.
2236 pub fn delete(&mut self, idx: usize) -> bool {
2237 self.delete_in(Lane::V1, idx)
2238 }
2239
2240 /// [`delete`](Project::delete) for the lane the clip was picked on: the
2241 /// clip's own span is cut out of *every* lane, so a take deletes whole from
2242 /// whichever half of it was clicked. `false` for a bad index, and for a lane
2243 /// that is not there.
2244 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
2245 let Some(clip) = self.lane(lane).get(idx).copied() else {
2246 return false;
2247 };
2248 self.ripple_delete(clip.start, clip.frames())
2249 }
2250
2251 /// Restore every lane from before the last successful edit -- the clips and
2252 /// the lane list both. `false` when there is nothing left to undo.
2253 pub fn undo(&mut self) -> bool {
2254 match self.history.pop() {
2255 Some(prev) => {
2256 self.lanes = prev;
2257 true
2258 }
2259 None => false,
2260 }
2261 }
2262
2263 /// Half-open `(source, start, end)` segments in *source* seconds, from
2264 /// `timeline_frame` to the end of the timeline -- the play list for the
2265 /// audio worker, read off **`A1`**. A `None` source is a gap: the
2266 /// worker synthesises that many seconds of silence, which is what keeps the
2267 /// audio master clock counting across a hole instead of stalling on it.
2268 /// The first entry is partial when the position is mid-clip. Empty when the
2269 /// position is past the end or `fps` is not usable.
2270 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
2271 self.lane_segments_from(Lane::A1, timeline_frame, fps)
2272 }
2273
2274 /// [`segments_from`](Project::segments_from) for a named lane.
2275 pub fn lane_segments_from(
2276 &self,
2277 lane: Lane,
2278 timeline_frame: u32,
2279 fps: f64,
2280 ) -> Vec<(Option<usize>, f64, f64)> {
2281 if !(fps.is_finite() && fps > 0.0) {
2282 return Vec::new();
2283 }
2284 self.spans_from(lane, timeline_frame)
2285 .iter()
2286 .map(|span| match span.from {
2287 // A clip's window is in *source* seconds: where in the file it
2288 // reads from, which a delete before it never shifts. How many
2289 // source frames that is, is the span's own arithmetic -- at a
2290 // speed it is not the timeline length ([`Span::source_len`]).
2291 Some((source, in_frame)) => (
2292 Some(source),
2293 f64::from(in_frame) / fps,
2294 f64::from(in_frame + span.source_len()) / fps,
2295 ),
2296 // A gap has no file, so all it can say is how long it is.
2297 None => (None, 0.0, f64::from(span.len) / fps),
2298 })
2299 .collect()
2300 }
2301
2302 /// One play list per audio lane that *holds* something, in display order --
2303 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
2304 /// what an export asks how many lanes it would have to mix.
2305 ///
2306 /// Never empty: a timeline whose audio lanes are all empty (or which has no
2307 /// audio lane at all) still yields one all-gap list, so it plays silence
2308 /// against a master clock exactly as it did before there were lanes to
2309 /// count. Lanes with nothing on them are left out rather than mixed in as
2310 /// silence: they would cost a decode thread each and add zero.
2311 pub fn audio_segments_from(
2312 &self,
2313 timeline_frame: u32,
2314 fps: f64,
2315 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
2316 self.audio_lanes()
2317 .into_iter()
2318 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
2319 .collect()
2320 }
2321
2322 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
2323 /// builds a play list for, in the same order. Public because everything
2324 /// asked per audio lane -- which clip a segment's equalizer belongs to,
2325 /// which lane an mp4 export would copy -- has to read the very list the
2326 /// sound comes off, or the two answers drift apart (which is exactly how an
2327 /// `A2`-only project once exported silently, ledger).
2328 pub fn audio_lanes(&self) -> Vec<Lane> {
2329 let lanes: Vec<Lane> = self
2330 .lanes()
2331 .into_iter()
2332 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
2333 .collect();
2334 match lanes.is_empty() {
2335 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
2336 // no sound still plays silence against the master clock.
2337 true => vec![Lane::A1],
2338 false => lanes,
2339 }
2340 }
2341
2342 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
2343 /// segments plays at, and how long the timeline gives it: the same lanes in
2344 /// the same order, one entry per segment, `None` for a segment at real time
2345 /// -- which is every segment of a project nobody has speeded, and the path
2346 /// the audio worker leaves bit-identical.
2347 ///
2348 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
2349 /// the segment tuple is what every opener and a dozen tests speak, and a
2350 /// rate is not part of *which samples* a segment names.
2351 ///
2352 /// The seconds are what makes a resample exact: a segment's own window
2353 /// resolves to whole source frames, and dividing that by the rate would
2354 /// leave each clip a fraction of a frame short or long -- a drift that grows
2355 /// clip by clip. Told how much timeline it owes, the worker pads or trims
2356 /// the last few samples of each segment instead, so the sound stays locked
2357 /// to the picture however many speeded cuts it walks through.
2358 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
2359 self.audio_lanes()
2360 .into_iter()
2361 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
2362 .collect()
2363 }
2364
2365 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
2366 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
2367 /// same walk, same `fps` refusal.
2368 pub fn lane_speeds_from(
2369 &self,
2370 lane: Lane,
2371 timeline_frame: u32,
2372 fps: f64,
2373 ) -> Vec<Option<Stretch>> {
2374 if !(fps.is_finite() && fps > 0.0) {
2375 return Vec::new();
2376 }
2377 self.spans_from(lane, timeline_frame)
2378 .iter()
2379 .map(|span| {
2380 (!span.speed.is_normal()).then(|| Stretch {
2381 step: span.speed.as_f64(),
2382 timeline_secs: f64::from(span.len) / fps,
2383 })
2384 })
2385 .collect()
2386 }
2387
2388 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
2389 /// segments plays through: the same lanes in the same order, one entry per
2390 /// segment, `None` where the segment is a gap or its clip plays flat.
2391 ///
2392 /// A parallel list rather than a fourth element of the segment tuple: that
2393 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
2394 /// and an effect is not part of *which samples* a segment names. A short
2395 /// list therefore means "flat from here on" rather than a length mismatch --
2396 /// see [`crate::AudioSession::open_mixed_streams_eq`].
2397 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
2398 self.audio_lanes()
2399 .into_iter()
2400 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
2401 .collect()
2402 }
2403
2404 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
2405 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
2406 /// same walk, same `fps` refusal, so the two lists cannot come out different
2407 /// lengths.
2408 pub fn lane_eqs_from(
2409 &self,
2410 lane: Lane,
2411 timeline_frame: u32,
2412 fps: f64,
2413 ) -> Vec<Option<EqParams>> {
2414 if !(fps.is_finite() && fps > 0.0) {
2415 return Vec::new();
2416 }
2417 self.spans_from(lane, timeline_frame)
2418 .iter()
2419 // A span off a clip covers that clip's frames and no others, so its
2420 // own start names the clip -- the index a [`Span`] does not carry.
2421 .map(|span| {
2422 self.map(lane, span.start)
2423 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
2424 })
2425 .collect()
2426 }
2427
2428 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
2429 /// it has decided it will succeed -- a refusal must not cost an undo step.
2430 fn snapshot(&mut self) {
2431 self.history.push(self.lanes.clone());
2432 }
2433
2434 fn new_link(&mut self) -> u32 {
2435 let id = self.next_link;
2436 self.next_link = self.next_link.saturating_add(1);
2437 id
2438 }
2439
2440 /// One fresh group id per *distinct* key, in lane order, and `None` where a
2441 /// lane has no key -- how [`split`](Project::split) and
2442 /// [`regroup`](Project::regroup) hand out ids across however many lanes.
2443 /// Lanes sharing a key end up sharing an id, which is exactly the rule
2444 /// [`links_are_consistent`] enforces: one id, one span.
2445 fn group_ids<K: PartialEq>(&mut self, keys: &[Option<K>]) -> Vec<Option<u32>> {
2446 // Linear, over a handful of lanes: a hash of a lane list would cost
2447 // more than it saves and would not be deterministic for free.
2448 let mut seen: Vec<(&K, u32)> = Vec::new();
2449 let mut out = Vec::with_capacity(keys.len());
2450 for key in keys {
2451 out.push(
2452 key.as_ref()
2453 .map(|k| match seen.iter().find(|(other, _)| *other == k) {
2454 Some(&(_, id)) => id,
2455 None => {
2456 let id = self.new_link();
2457 seen.push((k, id));
2458 id
2459 }
2460 }),
2461 );
2462 }
2463 out
2464 }
2465}
2466
2467/// The handle of every lane, in storage order -- the one definition of what
2468/// [`Lane::ord`] counts.
2469fn handles(lanes: &[LaneData]) -> Vec<Lane> {
2470 let (mut video, mut audio) = (0, 0);
2471 lanes
2472 .iter()
2473 .map(|l| match l.kind {
2474 LaneKind::Video => {
2475 video += 1;
2476 Lane::new(LaneKind::Video, video - 1)
2477 }
2478 LaneKind::Audio => {
2479 audio += 1;
2480 Lane::new(LaneKind::Audio, audio - 1)
2481 }
2482 })
2483 .collect()
2484}
2485
2486/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
2487/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
2488/// a speed cannot be applied twice or forgotten in one of them.
2489fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
2490 // Clamped inside the clip's own range: rounding at a slow rate can put the
2491 // last timeline frame of a clip a frame past its out-point, and a source
2492 // frame outside the range is one the next clip owns.
2493 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
2494}
2495
2496/// Index of the clip covering `frame`, or `None` for a gap or past the end.
2497/// Binary search: the sorted-disjoint invariant is what makes it legal.
2498fn at(clips: &[Clip], frame: u32) -> Option<usize> {
2499 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
2500 (frame < clips[idx].end()).then_some(idx)
2501}
2502
2503/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
2504/// there would cut in two. A placement's own first frame is not inside it.
2505fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
2506 let idx = at(clips, frame)?;
2507 // ...and, on a speeded clip, one its rate can actually address
2508 // ([`Speed::split_at`]): a cut between two showings of one source frame
2509 // would leave halves that no longer add up to the clip that was cut.
2510 (frame > clips[idx].start)
2511 .then_some(idx)
2512 .filter(|&idx| split_source(&clips[idx], frame).is_some())
2513}
2514
2515/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
2516/// rate cannot address that frame.
2517fn split_source(c: &Clip, frame: u32) -> Option<u32> {
2518 c.speed
2519 .split_at(c.len(), frame - c.start)
2520 .map(|src| c.in_frame + src)
2521}
2522
2523/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
2524/// rejoin: they must touch there, and be consecutive frames of one source.
2525fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
2526 let idx = clips.iter().position(|c| c.end() == frame)?;
2527 let next = clips.get(idx + 1)?;
2528 let joined = clips[idx].len() + next.len();
2529 (next.start == frame
2530 && next.source == clips[idx].source
2531 && next.in_frame == clips[idx].out_frame
2532 // ...at one rate, and one that puts the rejoined clip back in exactly
2533 // the room the two took up: what a split could have produced, which is
2534 // all this undoes.
2535 && next.speed == clips[idx].speed
2536 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
2537 .then_some(idx)
2538}
2539
2540/// The lane invariant: sorted by `start`, no two placements overlapping, no
2541/// empty placement. Checked at every constructor and asserted after every
2542/// mutation -- the offset model is only tractable while it holds.
2543/// The one thing an equalizer setting may not be: a value the text format
2544/// cannot write and read back as itself. Checked wherever params come in, so
2545/// what an edit produces is always what a save writes and a load reads.
2546fn finite(params: &EqParams) -> bool {
2547 params
2548 .bands
2549 .iter()
2550 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
2551}
2552
2553/// The same for a colour grade: [`crate::color`] itself falls back to identity
2554/// on a non-finite value, but a value that cannot be written and read back as
2555/// itself has no business reaching the model.
2556fn color_finite(p: &ColorParams) -> bool {
2557 p.brightness.is_finite()
2558 && p.contrast.is_finite()
2559 && p.saturation.is_finite()
2560 && p.tint.is_finite()
2561}
2562
2563fn sorted_disjoint(clips: &[Clip]) -> bool {
2564 clips.iter().all(|c| c.out_frame > c.in_frame)
2565 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
2566}
2567
2568/// The grouping invariant, checked in release at [`Project::from_parts`] and
2569/// asserted by the tests after every edit: a link id names **at most one** clip
2570/// per lane, and every clip carrying it covers the same timeline span -- that is
2571/// all "these move together" can mean.
2572///
2573/// Deliberately *not* a pairing of two lanes: with N lanes a take may run on
2574/// `V1`, `V2` and `A1` at once, and the rule that makes an id meaningful is span
2575/// identity, not which lane (or which `ord`) the partner sits on. Two lanes are
2576/// the case where it reads as "the picture and its sound".
2577///
2578/// A link no other lane carries is legal and is not an error: lifting one half
2579/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
2580/// timeline has to load again.
2581fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
2582 let handles = handles(lanes);
2583 for (data, lane) in lanes.iter().zip(&handles) {
2584 for (i, c) in data.clips.iter().enumerate() {
2585 let Some(id) = c.link else { continue };
2586 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
2587 return Err(
2588 format!("link {id} names two clips in the {} lane", lane.label()).into(),
2589 );
2590 }
2591 }
2592 }
2593 // First lane to carry an id fixes the span every other lane must agree on.
2594 let mut seen: Vec<(u32, Lane, u32, u32)> = Vec::new();
2595 for (data, &lane) in lanes.iter().zip(&handles) {
2596 for c in &data.clips {
2597 let Some(id) = c.link else { continue };
2598 match seen.iter().find(|(other, ..)| *other == id) {
2599 Some(&(_, first, start, end)) => {
2600 if (start, end) != (c.start, c.end()) {
2601 return Err(format!(
2602 "link {id} covers [{start}, {end}) in {} and [{}, {}) in {}",
2603 first.label(),
2604 c.start,
2605 c.end(),
2606 lane.label()
2607 )
2608 .into());
2609 }
2610 }
2611 None => seen.push((id, lane, c.start, c.end())),
2612 }
2613 }
2614 }
2615 Ok(())
2616}
2617
2618/// Removes the timeline frames `[start, end)` from `clips`: placements inside
2619/// it go, one straddling it is split in two, one overlapping an edge is
2620/// trimmed. Source frames follow the trim, so what is left plays what it always
2621/// played. Leaves the lane sorted and disjoint.
2622///
2623/// A piece the hole cut is no longer the take its group id names -- and both
2624/// halves of a straddled placement carrying that id would be the same id twice
2625/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
2626fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
2627 let mut out = Vec::with_capacity(clips.len() + 1);
2628 for c in clips.drain(..) {
2629 // Disjoint from the hole: untouched.
2630 if c.end() <= start || c.start >= end {
2631 out.push(c);
2632 continue;
2633 }
2634 // The head that survives in front of the hole -- as much source as fits
2635 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
2636 // which at real time is that room itself. Never *more*: a head that
2637 // outgrew its room would reach into the hole it is being cut out of,
2638 // which is exactly the overlap a slow clip punched at a frame its rate
2639 // cannot address used to leave (at 0.25x a single source frame is four
2640 // timeline frames, and three frames of room hold none of it). `None`
2641 // there means no remainder at all, and the piece simply goes.
2642 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
2643 && c.start < start
2644 {
2645 out.push(Clip {
2646 out_frame: c.in_frame + keep.min(c.len()),
2647 link: None,
2648 ..c
2649 });
2650 }
2651 // ...and the tail behind it, which keeps reading up to where it would
2652 // have: measured from its out-point for the head's reason, so what it
2653 // occupies still ends where the whole clip did -- and dropped whole on
2654 // the same `None`.
2655 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
2656 && c.end() > end
2657 {
2658 out.push(Clip {
2659 start: end,
2660 in_frame: c.out_frame - keep.min(c.len()),
2661 link: None,
2662 ..c
2663 });
2664 }
2665 }
2666 *clips = out;
2667}
2668
2669/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
2670/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
2671/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
2672/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
2673/// the caller.
2674fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
2675 for &i in on {
2676 let clips = &mut lanes[i].clips;
2677 clear(clips, at, at + len);
2678 for c in clips.iter_mut().filter(|c| c.start >= at) {
2679 c.start -= len;
2680 }
2681 debug_assert!(sorted_disjoint(clips));
2682 }
2683}
2684
2685/// Every lane, as the index list the two above take: what "the whole timeline"
2686/// is spelled as, and the scope [`Project::ripple_delete`] and
2687/// [`Project::split`] have always had.
2688fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
2689 (0..lanes.len()).collect()
2690}
2691
2692/// A caller's region list as a batch may use it: sorted by start, empty entries
2693/// dropped, and touching or overlapping entries merged into one.
2694///
2695/// Overlapping regions are the one thing a batch cannot take -- cutting the
2696/// second would cut frames the first already moved -- and a detector handing
2697/// back two that touch means one silence, not two cuts. Merged rather than
2698/// refused: this is arithmetic on a preview, not a user's mistake.
2699fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
2700 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
2701 sorted.sort_by_key(|&(at, _)| at);
2702 let mut out: Vec<(u32, u32)> = Vec::new();
2703 for (at, len) in sorted {
2704 let end = at.saturating_add(len);
2705 match out.last_mut() {
2706 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
2707 _ => out.push((at, len)),
2708 }
2709 }
2710 out
2711}
2712
2713/// Slides everything from `at` on later by `len`, splitting a placement that
2714/// straddles `at` so the two halves end up on either side of the hole. The
2715/// insert half of a rippling paste. The two halves lose the group id for the
2716/// reason [`clear`] gives.
2717fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
2718 if let Some(idx) = splittable(clips, at) {
2719 let mut tail = clips[idx];
2720 // The cut in *source* frames, at the clip's own rate. `splittable` has
2721 // already refused a frame the rate cannot address, which is why
2722 // [`Project::paste`] refuses one too rather than opening room inside a
2723 // clip that cannot be cut there.
2724 tail.in_frame = split_source(&tail, at).expect("splittable said so");
2725 tail.start = at;
2726 tail.link = None;
2727 clips[idx].out_frame = tail.in_frame;
2728 clips[idx].link = None;
2729 clips.insert(idx + 1, tail);
2730 }
2731 for c in clips.iter_mut().filter(|c| c.start >= at) {
2732 c.start += len;
2733 }
2734}
2735
2736/// Absolute, symlink-resolved when the file is reachable; the path as given
2737/// when it is not -- an unreadable path still deserves an index, it simply
2738/// dedups by spelling.
2739fn canonical(path: &Path) -> PathBuf {
2740 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
2741}
2742
2743#[cfg(test)]
2744mod tests {
2745 use super::*;
2746
2747 const FPS: f64 = 30.0;
2748 /// Never opened -- `Project` is pure data, so a path that does not exist is
2749 /// simply a path that dedups by spelling.
2750 const FILE: &str = "/nonexistent/a.mp4";
2751 const FILE2: &str = "/nonexistent/b.mp4";
2752
2753 /// A contiguous placement, group id ignored: what most assertions compare.
2754 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
2755 Clip {
2756 start,
2757 in_frame,
2758 out_frame,
2759 source,
2760 link: None,
2761 eq: None,
2762 color: None,
2763 fit: FitPolicy::default(),
2764 speed: Speed::NORMAL,
2765 }
2766 }
2767
2768 /// A recognisable equalizer setting: one peak band, `n` telling two of them
2769 /// apart -- which is what makes the table's dedup and its prune visible.
2770 fn band_at(n: u32) -> EqParams {
2771 EqParams {
2772 bands: vec![crate::eq::Band {
2773 freq_hz: 1000.0,
2774 gain_db: f64::from(n) as f32 * 1.5,
2775 q: 0.707,
2776 kind: crate::eq::BandKind::Peak,
2777 }],
2778 }
2779 }
2780
2781 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
2782 /// for the colour table.
2783 fn grade_at(n: u32) -> ColorParams {
2784 ColorParams {
2785 brightness: f64::from(n) as f32 * 0.05,
2786 ..Default::default()
2787 }
2788 }
2789
2790 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
2791 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
2792 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
2793 }
2794
2795 /// Every lane with its group ids blanked, for comparing shape.
2796 fn shape(p: &Project) -> Vec<Vec<Clip>> {
2797 p.lanes()
2798 .into_iter()
2799 .map(|l| {
2800 p.lane(l)
2801 .iter()
2802 .map(|c| Clip { link: None, ..*c })
2803 .collect()
2804 })
2805 .collect()
2806 }
2807
2808 /// The *source frame* every timeline frame reads, per lane -- the traversal
2809 /// a player performs. Deliberately not the clip index: a split changes which
2810 /// clip a frame belongs to, and nothing else.
2811 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
2812 (0..p.timeline_frames() + 2)
2813 .map(|f| {
2814 p.lanes()
2815 .into_iter()
2816 .map(|l| p.map(l, f).map(|(_, source)| source))
2817 .collect()
2818 })
2819 .collect()
2820 }
2821
2822 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
2823 /// fixture. Built through `split` so the constructor path is exercised too.
2824 fn three() -> Project {
2825 let mut p = Project::single(FILE, 9);
2826 assert!(p.split(3));
2827 assert!(p.split(5));
2828 assert_eq!(
2829 shape(&p),
2830 [
2831 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
2832 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
2833 ]
2834 );
2835 p
2836 }
2837
2838 #[test]
2839 fn single_is_the_whole_file_on_both_lanes() {
2840 let p = Project::single(FILE, 150);
2841 assert_eq!(p.clips().len(), 1);
2842 assert_eq!(p.lane(Lane::A1).len(), 1);
2843 assert_eq!(p.timeline_frames(), 150);
2844 assert_eq!(p.clip_spans(), vec![(0, 150)]);
2845 // grouped: video and audio carry the same link
2846 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
2847 assert!(p.clips()[0].link.is_some());
2848 // degenerate mapping: timeline == source
2849 assert_eq!(p.map_timeline(0), Some((0, 0)));
2850 assert_eq!(p.map_timeline(149), Some((0, 149)));
2851 assert_eq!(p.map_timeline(150), None);
2852 // never-empty invariant survives a bogus frame count
2853 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
2854 }
2855
2856 #[test]
2857 fn split_cuts_every_lane_and_regroups_it_back() {
2858 let mut p = Project::single(FILE, 9);
2859 let before = traversal(&p);
2860 let before_shape = shape(&p);
2861
2862 assert!(p.split(4));
2863 for l in p.lanes() {
2864 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
2865 }
2866 // The two sides are two groups, one per side, matching across the lanes.
2867 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
2868 assert_eq!(v[0].link, a[0].link);
2869 assert_eq!(v[1].link, a[1].link);
2870 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
2871 // A split changes no mapping, in either lane.
2872 assert_eq!(traversal(&p), before, "a split moves nothing");
2873
2874 assert!(p.regroup(4), "the inverse rejoins them");
2875 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
2876 assert_eq!(traversal(&p), before);
2877 assert_eq!(
2878 p.lane(Lane::V1)[0].link,
2879 p.lane(Lane::A1)[0].link,
2880 "and the rejoined clip is one group again"
2881 );
2882 }
2883
2884 /// The music video's own path: the take comes apart into halves that carry
2885 /// ids of their own, one undo puts it back, and two clips over the same
2886 /// frames become one take again by hand.
2887 #[test]
2888 fn a_take_comes_apart_and_goes_back_together() {
2889 let mut p = Project::single(FILE, 9);
2890 let one = p.clips()[0].link.expect("a fresh project is one take");
2891 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
2892
2893 // A third lane in the same group -- and the merge case with it: a
2894 // placement is in no group, and grouping it in leaves *one* group.
2895 let v2 = p.add_lane(LaneKind::Video);
2896 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
2897 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
2898 p.group(Lane::V1, 0, v2, 0)
2899 .expect("the same frames, one lane over");
2900 let id = p.clips()[0].link.expect("still a group");
2901 assert!(
2902 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2903 "one id over the three, not two groups sharing a span"
2904 );
2905 links_are_consistent(&p.lanes).expect("one id, one span");
2906
2907 // Detached by the sound: every half of the group, not only the two.
2908 assert!(p.ungroup(Lane::A1, 0));
2909 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
2910 assert!(
2911 ids.iter().all(Option::is_some),
2912 "a half keeps an id of its own"
2913 );
2914 assert!(
2915 ids.iter()
2916 .enumerate()
2917 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
2918 "and no two halves are the same group any more: {ids:?}"
2919 );
2920 links_are_consistent(&p.lanes).expect("a lone id is legal");
2921
2922 // One snapshot for the whole detach.
2923 assert!(p.undo());
2924 assert!(
2925 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2926 "one undo puts the whole group back"
2927 );
2928
2929 // And back together by hand: the two the pointer named, and only them.
2930 assert!(p.ungroup(Lane::V1, 0));
2931 p.group(Lane::V1, 0, Lane::A1, 0)
2932 .expect("both cover [0, 9)");
2933 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
2934 assert_ne!(
2935 p.lane(v2)[0].link,
2936 p.lane(Lane::V1)[0].link,
2937 "the third half stayed detached"
2938 );
2939 links_are_consistent(&p.lanes).expect("one id, one span");
2940 }
2941
2942 /// What a group may not be, and what a detach has nothing to take apart --
2943 /// none of which may cost an undo step.
2944 #[test]
2945 fn a_group_is_one_span_and_one_clip_per_lane() {
2946 let mut p = three();
2947 let before = shape(&p);
2948 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
2949
2950 assert!(
2951 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
2952 "two clips of one lane are never one take"
2953 );
2954 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
2955 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
2956 assert!(
2957 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
2958 "{spans}"
2959 );
2960 assert!(
2961 spans.contains("trim them to matching bounds first"),
2962 "{spans}"
2963 );
2964 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
2965
2966 // A half nothing else is grouped with is already detached, a placement
2967 // is in no group at all, and an index that is not there has nothing to
2968 // detach either.
2969 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
2970 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
2971 assert!(p.lift(Lane::A1, 0));
2972 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
2973 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
2974
2975 // Two undos, one per edit: not one of the refusals pushed a snapshot.
2976 assert!(p.undo());
2977 assert!(p.undo());
2978 assert_eq!(shape(&p), before);
2979 }
2980
2981 #[test]
2982 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
2983 let mut p = three();
2984 let before = shape(&p);
2985 assert!(!p.split(0), "timeline 0 has nothing before it");
2986 assert!(!p.split(3), "existing boundary");
2987 assert!(!p.split(5), "existing boundary");
2988 assert!(!p.split(9), "one past the last frame");
2989 assert!(!p.split(1_000));
2990 assert_eq!(shape(&p), before);
2991 // one undo lands before the *second* split, so the refusals pushed nothing
2992 assert!(p.undo());
2993 assert_eq!(p.clips().len(), 2, "refused splits push no history");
2994
2995 // ...and a frame that is a gap in both lanes has nothing to split.
2996 let mut p = three();
2997 assert!(p.lift(Lane::V1, 1));
2998 assert!(p.lift(Lane::A1, 1));
2999 assert!(!p.split(4), "a gap is not a clip");
3000 }
3001
3002 #[test]
3003 fn regroup_refuses_what_a_split_could_not_have_made() {
3004 let mut p = three();
3005 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
3006 assert!(p.regroup(5));
3007 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
3008 // A boundary with a gap on one side, and one where the sources do not
3009 // meet, are both refused.
3010 let mut p = three();
3011 assert!(p.lift(Lane::V1, 1));
3012 assert!(p.lift(Lane::A1, 1));
3013 assert!(!p.regroup(3), "nothing starts at 3 any more");
3014 let mut p = three();
3015 for l in p.lanes() {
3016 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
3017 }
3018 assert!(!p.regroup(3), "source 100 does not follow source 3");
3019 assert!(!p.regroup(0), "nothing ends at 0");
3020 assert!(!p.regroup(1_000));
3021 }
3022
3023 #[test]
3024 fn map_and_spans_sweep_every_boundary() {
3025 let p = three();
3026 assert_eq!(p.timeline_frames(), 9);
3027 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
3028 // contiguous source here, so the clip index is what actually moves
3029 let expect = [
3030 (0, (0, 0)),
3031 (1, (0, 1)),
3032 (2, (0, 2)),
3033 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
3034 (4, (1, 4)),
3035 (5, (2, 5)),
3036 (6, (2, 6)),
3037 (7, (2, 7)),
3038 (8, (2, 8)),
3039 ];
3040 for (t, want) in expect {
3041 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
3042 }
3043 assert_eq!(p.map_timeline(9), None);
3044 // A span is the rest of the clip from where it was asked about.
3045 assert_eq!(
3046 p.span_at(Lane::V1, 6),
3047 Some(Span {
3048 start: 6,
3049 len: 3,
3050 from: Some((0, 6)),
3051 speed: Speed::NORMAL
3052 })
3053 );
3054 assert_eq!(p.span_at(Lane::V1, 9), None);
3055 }
3056
3057 /// The fit policy is one byte *in* the clip rather than an index into a
3058 /// table like the eq and the grade: there is nothing for a table to share.
3059 /// It costs the clip nothing at all -- the fields before it (a `usize`
3060 /// source and two `Option<u16>`s) already left the struct padded to 40
3061 /// bytes, and the byte landed in that padding. This is the assert that says
3062 /// so: a clip that grew a word grew every undo snapshot and every clipboard
3063 /// copy with it.
3064 #[test]
3065 fn a_fit_policy_costs_the_clip_no_word() {
3066 assert_eq!(
3067 std::mem::size_of::<Clip>(),
3068 40,
3069 "Clip changed size: {} bytes",
3070 std::mem::size_of::<Clip>()
3071 );
3072 }
3073
3074 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
3075 /// anything in `three()` so it is recognisable wherever it lands.
3076 const PASTED: Clip = Clip {
3077 start: 0,
3078 in_frame: 100,
3079 out_frame: 102,
3080 source: 0,
3081 link: None,
3082 eq: None,
3083 color: None,
3084 fit: FitPolicy::Fit,
3085 speed: Speed::NORMAL,
3086 };
3087
3088 #[test]
3089 fn paste_mid_clip_splits_around_it() {
3090 let mut p = three();
3091 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
3092 assert_eq!(p.timeline_frames(), 11);
3093 assert_eq!(
3094 shape(&p)[0],
3095 vec![
3096 clip(0, 0, 3, 0),
3097 clip(3, 3, 5, 0),
3098 clip(5, 5, 6, 0),
3099 clip(6, 100, 102, 0),
3100 clip(8, 6, 9, 0),
3101 ]
3102 );
3103 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
3104 // The pasted frames are exactly where they were asked for, and the
3105 // split-off remainder resumes after them.
3106 assert_eq!(p.map_timeline(6), Some((3, 100)));
3107 assert_eq!(p.map_timeline(7), Some((3, 101)));
3108 assert_eq!(p.map_timeline(8), Some((4, 6)));
3109 }
3110
3111 #[test]
3112 fn paste_at_boundary_zero_and_end() {
3113 let mut p = three();
3114 assert!(p.paste(3, PASTED), "existing boundary: no split");
3115 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
3116 assert_eq!(p.map_timeline(3), Some((1, 100)));
3117
3118 let mut p = three();
3119 assert!(p.paste(0, PASTED));
3120 assert_eq!(p.map_timeline(0), Some((0, 100)));
3121 assert_eq!(p.map_timeline(2), Some((1, 0)));
3122
3123 // At the end and past it both append -- a paste never leaves black in
3124 // front of itself; `place` is the call that makes a gap.
3125 let mut p = three();
3126 assert!(p.paste(9, PASTED));
3127 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
3128 assert!(p.paste(1_000, PASTED));
3129 assert_eq!(p.timeline_frames(), 13);
3130
3131 // An empty clip is the one thing refused, and it pushes no history.
3132 let mut p = three();
3133 assert!(!p.paste(4, clip(0, 7, 7, 0)));
3134 assert_eq!(p.clips().len(), 3);
3135 }
3136
3137 /// The data-loss paste: a clip of a source with no picture used to land on
3138 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
3139 /// carried it was refused on the way back in ("a box with a larger size").
3140 #[test]
3141 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
3142 let mut p = three();
3143 let wav = p.import("/nonexistent/song.wav", 0);
3144 let copied = Clip {
3145 source: wav,
3146 ..PASTED
3147 };
3148 assert!(p.paste(3, copied));
3149 // The room is opened on every lane, or the two would slide apart...
3150 assert_eq!(p.timeline_frames(), 11);
3151 assert_eq!(
3152 shape(&p)[0],
3153 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
3154 "the video lane got room and nothing else"
3155 );
3156 // ...but the clip itself only reaches the lane that can play it.
3157 assert_eq!(
3158 shape(&p)[1],
3159 vec![
3160 clip(0, 0, 3, 0),
3161 clip(3, 100, 102, wav),
3162 clip(5, 3, 5, 0),
3163 clip(7, 5, 9, 0)
3164 ]
3165 );
3166 // A source with a picture is unchanged: still the grouped pair.
3167 let mut p = three();
3168 assert!(p.paste(3, PASTED));
3169 assert_eq!(shape(&p)[0], shape(&p)[1]);
3170 }
3171
3172 /// A hand-written file may hold a clip that ends at the very last frame
3173 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
3174 /// to wrap its start round to the front of the lane: an overlap in debug, a
3175 /// project no reload would accept in release.
3176 #[test]
3177 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
3178 let far = clip(u32::MAX - 90, 0, 90, 0);
3179 let parts = |c: Clip| {
3180 Project::from_parts(
3181 vec![Source::new(FILE, 0)],
3182 two(vec![c], vec![c]),
3183 Vec::new(),
3184 Vec::new(),
3185 )
3186 .expect("valid parts")
3187 };
3188 let mut p = parts(far);
3189 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
3190 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
3191 assert!(!p.undo(), "...and pushes no history either");
3192 assert!(
3193 !p.paste(u32::MAX, PASTED),
3194 "appending has nowhere to go either: the timeline ends at the last frame"
3195 );
3196 // With room for exactly those frames the same paste is taken.
3197 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
3198 assert!(p.paste(0, PASTED));
3199 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
3200 }
3201
3202 #[test]
3203 fn paste_undoes_in_one_step() {
3204 let mut p = three();
3205 let before = shape(&p);
3206 assert!(p.paste(6, PASTED));
3207 assert!(p.undo());
3208 assert_eq!(shape(&p), before, "a paste is one undo step");
3209 }
3210
3211 #[test]
3212 fn a_copy_outlives_the_clip_it_came_from() {
3213 let mut p = three();
3214 let copied = p.clips()[1]; // [3,5)
3215 assert!(p.delete(1));
3216 // Just a frame range: the source is still on disk either way.
3217 assert!(p.paste(0, copied));
3218 assert_eq!(p.map_timeline(0), Some((0, 3)));
3219 assert_eq!(p.timeline_frames(), 9);
3220 }
3221
3222 #[test]
3223 fn delete_closes_the_gap_on_both_lanes() {
3224 let mut p = three();
3225 assert!(p.delete(1));
3226 assert_eq!(p.timeline_frames(), 7);
3227 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
3228 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
3229 // timeline 3 used to be source 3; the gap closed so it is source 5 now
3230 assert_eq!(p.map_timeline(3), Some((1, 5)));
3231 assert_eq!(p.map_timeline(6), Some((1, 8)));
3232 assert_eq!(p.map_timeline(7), None);
3233 }
3234
3235 #[test]
3236 fn delete_first_last_and_only() {
3237 let mut p = three();
3238 assert!(p.delete(0));
3239 assert_eq!(p.map_timeline(0), Some((0, 3)));
3240 assert_eq!(p.timeline_frames(), 6);
3241
3242 let mut p = three();
3243 assert!(p.delete(2));
3244 assert_eq!(p.timeline_frames(), 5);
3245 assert_eq!(p.map_timeline(4), Some((1, 4)));
3246
3247 assert!(!p.delete(2), "index past the end");
3248 assert!(p.delete(1));
3249 assert!(p.delete(0), "and the last remaining clip goes too");
3250 assert_eq!(p.clips().len(), 0);
3251 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
3252 assert!(!p.delete(0), "there is nothing left to delete");
3253 assert!(p.undo(), "one gesture, one undo");
3254 assert_eq!(p.clips().len(), 1);
3255 }
3256
3257 /// The offset model's point: one lane loses a clip, the other does not move.
3258 #[test]
3259 fn a_lift_leaves_a_gap_and_moves_nothing() {
3260 let mut p = three();
3261 let video_before = shape(&p)[0].clone();
3262 assert!(p.lift(Lane::A1, 1));
3263 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
3264 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
3265 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
3266 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
3267 assert_eq!(p.map(Lane::A1, 4), None);
3268 assert_eq!(
3269 p.span_at(Lane::A1, 3),
3270 Some(Span {
3271 start: 3,
3272 len: 2,
3273 from: None,
3274 speed: Speed::NORMAL
3275 })
3276 );
3277 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
3278 assert!(p.undo());
3279 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
3280 }
3281
3282 #[test]
3283 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
3284 let mut p = three();
3285 assert!(p.lift(Lane::A1, 2));
3286 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
3287 assert_eq!(
3288 p.span_at(Lane::A1, 5),
3289 Some(Span {
3290 start: 5,
3291 len: 4,
3292 from: None,
3293 speed: Speed::NORMAL
3294 }),
3295 "the audio lane holds silence to the end of the picture"
3296 );
3297 assert_eq!(p.span_at(Lane::A1, 9), None);
3298 // Every lane covers the timeline exactly, gaps included.
3299 for l in p.lanes() {
3300 let spans = p.spans_from(l, 0);
3301 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
3302 assert_eq!(spans[0].start, 0);
3303 }
3304 }
3305
3306 /// The timeline is emptiable: the last placement comes off like any other,
3307 /// the project holds "nothing on any lane" as a state, and one undo per
3308 /// gesture brings it back.
3309 #[test]
3310 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
3311 let mut p = Project::single(FILE, 9);
3312 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
3313 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
3314 assert_eq!(p.timeline_frames(), 0);
3315 assert_eq!(p.composite_span_at(0), None, "nothing to show");
3316 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
3317 assert!(!p.lift(Lane::A1, 0), "index past the end");
3318 assert!(p.undo(), "and the last lift comes back");
3319 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
3320 // A saved-and-loaded empty timeline is a project like any other, and it
3321 // still names the file its frame rate came from.
3322 assert!(p.lift(Lane::V1, 0));
3323 let (sources, lanes, eq, color) = p.without_orphan_sources();
3324 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
3325 let back = Project::from_parts(sources, lanes, eq, color).expect("an empty project loads");
3326 assert_eq!(back.timeline_frames(), 0);
3327 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
3328 }
3329
3330 /// What a keyboard selection walks: one answer per lane, gaps included --
3331 /// the composite's own answer is one lane's and cannot say what the audio
3332 /// lane holds under the same playhead.
3333 #[test]
3334 fn lane_clip_at_answers_for_each_lane_separately() {
3335 let mut p = Project::single(FILE, 9);
3336 assert!(p.split(3), "both lanes split");
3337 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
3338 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
3339 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
3340 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
3341 // A gap on one lane leaves the other's clip selectable there.
3342 assert!(p.lift(Lane::A1, 0));
3343 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
3344 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(0), "indices moved with it");
3345 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
3346 // A lane that is not there is not a panic.
3347 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
3348 }
3349
3350 #[test]
3351 fn place_overwrites_only_its_own_lane() {
3352 let mut p = three();
3353 let audio_before = shape(&p)[1].clone();
3354 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
3355 // is trimmed, nothing shifts.
3356 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
3357 assert_eq!(
3358 shape(&p)[0],
3359 vec![
3360 clip(0, 0, 3, 0),
3361 clip(3, 3, 4, 0),
3362 clip(4, 100, 102, 0),
3363 clip(6, 6, 9, 0),
3364 ]
3365 );
3366 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
3367 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
3368
3369 // Placed inside one clip, it splits it in two.
3370 let mut p = Project::single(FILE, 9);
3371 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
3372 assert_eq!(
3373 shape(&p)[0],
3374 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
3375 );
3376 // ...and placed past the end it makes a gap, which is the whole point.
3377 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
3378 assert_eq!(p.timeline_frames(), 22);
3379 assert_eq!(
3380 p.span_at(Lane::V1, 9),
3381 Some(Span {
3382 start: 9,
3383 len: 11,
3384 from: None,
3385 speed: Speed::NORMAL
3386 })
3387 );
3388 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
3389 }
3390
3391 /// The drag between tracks: the clip keeps its frames, one undo takes it
3392 /// back, and every way it can be refused leaves the project untouched.
3393 #[test]
3394 fn move_to_lane_keeps_the_frames_and_refuses_the_rest() {
3395 let v2 = Lane::new(LaneKind::Video, 1);
3396 let mut p = three();
3397 assert_eq!(p.add_lane(LaneKind::Video), v2);
3398 let before = shape(&p);
3399
3400 assert!(p.move_to_lane(Lane::V1, 1, v2), "V1's middle clip moves up");
3401 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
3402 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
3403 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
3404 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
3405 // One snapshot: a single undo, and the lane list survives it.
3406 assert!(p.undo());
3407 assert_eq!(shape(&p), before);
3408
3409 // A lane that is not there, the lane it is already on, an index that is
3410 // not there, and a move across kinds: all refused, nothing changed.
3411 let history = p.history.len();
3412 for (from, idx, to) in [
3413 (Lane::V1, 1, Lane::new(LaneKind::Video, 7)),
3414 (Lane::V1, 1, Lane::V1),
3415 (Lane::V1, 9, v2),
3416 (Lane::V1, 1, Lane::A1),
3417 (Lane::A1, 1, v2),
3418 ] {
3419 assert!(!p.move_to_lane(from, idx, to), "{from:?} {idx} -> {to:?}");
3420 }
3421 assert_eq!(shape(&p), before);
3422 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
3423
3424 // Landing on another clip is refused rather than overwriting it: the
3425 // pointer named the lane, never the take already sitting there.
3426 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
3427 assert!(!p.move_to_lane(Lane::V1, 1, v2), "[3,5) would land on it");
3428 assert!(p.move_to_lane(Lane::V1, 0, v2), "[0,3) merely abuts it");
3429 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
3430 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
3431 }
3432
3433 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
3434 /// [`three`] cuts up all nine of its frames.
3435 const SRC: &[u32] = &[9];
3436
3437 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
3438 /// else on the lane moves, and every wall stops the edge rather than
3439 /// refusing the gesture.
3440 #[test]
3441 fn trimming_the_tail_stops_at_every_wall() {
3442 let mut p = three();
3443
3444 // Pulled in: a gap opens behind it and the clip after it stays put.
3445 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
3446 assert_eq!(
3447 shape(&p)[0],
3448 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
3449 );
3450 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
3451 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
3452
3453 // ...and back out, no further than the clip behind it.
3454 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
3455 assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
3456 assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
3457
3458 // One frame of clip always survives, however far back the pointer went.
3459 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
3460 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
3461
3462 // The last clip has no neighbour, so what stops it is the file: nine
3463 // frames is nine frames.
3464 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
3465 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
3466 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
3467 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
3468 // A source nobody told us the length of may not grow at all -- an
3469 // out-point past the end of a file is a save that will not open again.
3470 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
3471 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
3472 }
3473
3474 /// The head pulled in takes the in-point with it -- what stays plays what it
3475 /// always played -- and stops at the source's own first frame.
3476 #[test]
3477 fn trimming_the_head_moves_the_in_point() {
3478 let mut p = three();
3479 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
3480 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
3481 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
3482 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
3483 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
3484 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
3485 // One frame survives here too.
3486 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
3487 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
3488
3489 // A clip that does not begin at its source's first frame: its head goes
3490 // back to source frame 0 and not one frame further.
3491 let mut p = Project::single(FILE, 9);
3492 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
3493 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
3494 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
3495 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
3496 }
3497
3498 /// A clip whose in-point is *past* its own start -- what a ripple delete
3499 /// leaves, the piece in front of it gone and this one slid back to frame 0
3500 /// carrying the in-point the cut gave it. Its head has more source behind it
3501 /// than the timeline has room for, and the timeline's own first frame is the
3502 /// wall: asking is not an overflow, and the answer is 0.
3503 #[test]
3504 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
3505 let mut p = Project::single(FILE, 9);
3506 assert!(p.split(5));
3507 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
3508 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
3509
3510 assert_eq!(
3511 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
3512 Some((0, 3)),
3513 "back to frame 0 at most, and one frame of clip always survives"
3514 );
3515 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
3516 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
3517 assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
3518 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
3519 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
3520 }
3521
3522 /// A still is trimmed from its head exactly as it is from its tail: it has
3523 /// no earlier frame to walk an in-point back to, so the wall is the length
3524 /// the caller's table allows it, measured back from the tail. Measured from
3525 /// the in-point -- which a placed picture has at 0 -- its left edge could
3526 /// never be dragged outwards at all.
3527 #[test]
3528 fn a_stills_head_stretches_out_like_its_tail() {
3529 const STILL: &str = "/nonexistent/card.png";
3530 /// What a still is held to, as `PlaybackSession` fills the table in.
3531 const CAP: &[u32] = &[60];
3532
3533 let mut p = Project::single(STILL, 20);
3534 assert!(p.lift(Lane::A1, 0), "a picture is silent");
3535 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
3536 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
3537
3538 // A source with no entry in the table may not grow, here as at the tail.
3539 assert_eq!(
3540 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
3541 Some((100, 119)),
3542 "a length nobody told us buys no head room"
3543 );
3544 assert_eq!(
3545 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
3546 Some((60, 119)),
3547 "back to a whole cap's worth, one frame of clip surviving"
3548 );
3549 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
3550 assert_eq!(
3551 shape(&p)[0][0],
3552 clip(80, 0, 40, 0),
3553 "twenty frames longer, and still read from the source's first frame"
3554 );
3555 // Past the cap is clamped, exactly as the tail is -- not refused.
3556 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
3557 assert_eq!(shape(&p)[0][0], clip(60, 0, 60, 0), "a cap's worth, no more");
3558 // ...and the clip in front is the nearer wall of the two: no head trim
3559 // may open an overlap.
3560 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
3561 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
3562 assert_eq!(
3563 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
3564 Some((85, 119)),
3565 "up to the neighbour's last frame and not over it"
3566 );
3567 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
3568 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
3569 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
3570 }
3571
3572 /// Linked halves trim as one: a link is one span on however many lanes, so
3573 /// the sound follows the picture's edge -- and the tightest wall of the two
3574 /// is what stops both.
3575 #[test]
3576 fn linked_halves_trim_together() {
3577 let mut p = three();
3578 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
3579 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
3580
3581 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
3582 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
3583 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
3584 assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
3585 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
3586 links_are_consistent(&p.lanes).expect("one id per lane, one span");
3587
3588 // Something in the way on the *audio* lane stops the picture's tail as
3589 // well: the group can only go as far as its tightest member.
3590 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
3591 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
3592 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
3593 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
3594 links_are_consistent(&p.lanes).expect("still one span");
3595 }
3596
3597 /// A whole drag is one undo step -- the front-end commits once, at the
3598 /// release -- and an edge asked to stay where it is costs none at all.
3599 #[test]
3600 fn a_trim_is_one_undo_step() {
3601 let mut p = three();
3602 let before = shape(&p);
3603 let history = p.history.len();
3604
3605 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
3606 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
3607 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
3608 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
3609 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
3610 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
3611
3612 assert!(p.undo());
3613 assert_eq!(shape(&p), before, "both halves back, in one step");
3614 }
3615
3616 /// A moved half stays in its group: a link names a span, not a lane, so the
3617 /// picture on `V2` is still the same take as the sound under it on `A1`.
3618 #[test]
3619 fn move_to_lane_keeps_the_group() {
3620 let v2 = Lane::new(LaneKind::Video, 1);
3621 let mut p = three();
3622 p.add_lane(LaneKind::Video);
3623 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
3624 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
3625 assert!(p.move_to_lane(Lane::V1, 1, v2));
3626 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
3627 links_are_consistent(&p.lanes).expect("one id per lane, one span");
3628 assert_eq!(
3629 p.lane(v2)[0].start,
3630 p.lane(Lane::A1)[1].start,
3631 "and still covers the same span as its sound"
3632 );
3633 }
3634
3635 #[test]
3636 fn ripple_delete_spans_partial_clips() {
3637 let mut p = three();
3638 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
3639 assert!(p.ripple_delete(2, 4));
3640 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
3641 assert_eq!(shape(&p)[1], shape(&p)[0]);
3642 assert_eq!(p.timeline_frames(), 5);
3643 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
3644 assert!(p.undo());
3645 assert_eq!(shape(&p), shape(&three()));
3646 // One that takes everything is a delete like any other: the timeline
3647 // empties, and the undo it cost brings it back whole.
3648 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
3649 assert_eq!(p.timeline_frames(), 0);
3650 assert!(
3651 !p.ripple_delete(0, 100),
3652 "and a delete with nothing left to take is not an undo step"
3653 );
3654 assert!(p.undo());
3655 assert_eq!(shape(&p), shape(&three()));
3656 }
3657
3658 #[test]
3659 fn undo_restores_exactly() {
3660 let mut p = three();
3661 let after_splits = shape(&p);
3662 assert!(p.delete(1));
3663 assert!(p.undo());
3664 assert_eq!(shape(&p), after_splits);
3665
3666 // walk all the way back through both splits, then run dry
3667 assert!(p.undo());
3668 assert_eq!(p.clips().len(), 2);
3669 assert!(p.undo());
3670 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
3671 assert!(!p.undo(), "empty history");
3672 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
3673 }
3674
3675 /// Undo/redo by hand across a split must never merge two takes into one
3676 /// group by reusing an id.
3677 #[test]
3678 fn group_ids_are_never_reused() {
3679 let mut p = Project::single(FILE, 9);
3680 assert!(p.split(3));
3681 let first = p.clips()[1].link;
3682 assert!(p.undo());
3683 assert!(p.split(5));
3684 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
3685 }
3686
3687 #[test]
3688 fn segments_from_reads_the_audio_lane() {
3689 let p = three();
3690 // mid-clip: partial first segment, whole clips after it
3691 assert_eq!(
3692 p.segments_from(4, FPS),
3693 vec![
3694 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
3695 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
3696 ]
3697 );
3698 // on a boundary: nothing partial
3699 assert_eq!(
3700 p.segments_from(3, FPS),
3701 vec![
3702 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
3703 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
3704 ]
3705 );
3706 // from the top: one entry per clip
3707 assert_eq!(p.segments_from(0, FPS).len(), 3);
3708 // last clip only
3709 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
3710 // past the end / unusable fps
3711 assert!(p.segments_from(9, FPS).is_empty());
3712 assert!(p.segments_from(0, 0.0).is_empty());
3713 assert!(p.segments_from(0, f64::NAN).is_empty());
3714 }
3715
3716 #[test]
3717 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
3718 let mut p = three();
3719 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
3720 assert_eq!(
3721 p.segments_from(0, FPS),
3722 vec![
3723 (Some(0), 0.0, 3.0 / 30.0),
3724 (None, 0.0, 2.0 / 30.0),
3725 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
3726 ]
3727 );
3728 // The list still covers exactly the timeline: that is what stops the
3729 // master clock stalling at the hole.
3730 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
3731 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
3732 // Starting inside the gap trims the silence, not the clip after it.
3733 assert_eq!(
3734 p.segments_from(4, FPS),
3735 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
3736 );
3737 // ...and a lane that is nothing but gap is a run of silence.
3738 assert!(p.lift(Lane::A1, 0));
3739 assert!(p.lift(Lane::A1, 0));
3740 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
3741 }
3742
3743 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
3744 /// of source 0 then [0,4) of source 1.
3745 fn two_sources() -> Project {
3746 let mut p = three();
3747 let s = p.import(FILE2, 0);
3748 assert_eq!(s, 1);
3749 assert!(p.append_clip(s, 4));
3750 p
3751 }
3752
3753 #[test]
3754 fn import_dedups_and_appends() {
3755 let mut p = Project::single(FILE, 9);
3756 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
3757 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
3758 assert_eq!(p.import(FILE2, 0), 1);
3759 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
3760 // ...but the same file on another audio stream is another source: it is
3761 // what a clip names, and a clip plays exactly one stream.
3762 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
3763 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
3764 assert_eq!(p.sources()[2].audio_stream, 1);
3765 assert!(p.append_clip(2, 4), "a stream entry is placeable");
3766 assert!(p.undo());
3767 assert_eq!(p.sources().len(), 3);
3768 assert!(!p.append_clip(3, 5), "unknown source index");
3769 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
3770
3771 // Two spellings of one real file are one source: this is the case the
3772 // raw-path comparison above would get wrong.
3773 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
3774 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
3775 let mut p = Project::single(here, 9);
3776 assert_eq!(p.import(detour, 0), 0);
3777 assert_eq!(p.sources().len(), 1);
3778 }
3779
3780 #[test]
3781 fn append_clip_is_one_undo_step() {
3782 let mut p = two_sources();
3783 assert_eq!(p.timeline_frames(), 13);
3784 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
3785 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
3786 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
3787 assert!(p.undo());
3788 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
3789 assert_eq!(
3790 p.sources().len(),
3791 2,
3792 "the orphan source entry stays -- indexes are forever"
3793 );
3794 // ...and it is still usable, so a redo-by-hand costs no reimport.
3795 assert!(p.append_clip(1, 0));
3796 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
3797 }
3798
3799 #[test]
3800 fn edits_carry_the_source_along() {
3801 let mut p = two_sources();
3802 // A split inside the second source splits into two source-1 clips.
3803 assert!(p.split(11));
3804 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
3805 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
3806
3807 // A source-1 clip pasted into source-0 territory keeps its file, and so
3808 // does the source-0 half that got split off around it.
3809 let copied = p.clips()[4];
3810 assert!(p.paste(1, copied));
3811 assert_eq!(p.clips()[1].source, 1);
3812 assert_eq!(p.clips()[1].in_frame, 2);
3813 assert_eq!(p.clips()[2].source, 0);
3814 assert!(p.undo());
3815 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
3816 }
3817
3818 #[test]
3819 fn segments_from_names_the_source() {
3820 let p = two_sources();
3821 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
3822 assert_eq!(
3823 p.segments_from(4, FPS),
3824 vec![
3825 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
3826 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
3827 (Some(1), 0.0, 4.0 / 30.0),
3828 ]
3829 );
3830 // Mid-clip in source 1: only that source is left.
3831 assert_eq!(
3832 p.segments_from(10, FPS),
3833 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
3834 );
3835 assert!(p.segments_from(13, FPS).is_empty());
3836 // Segments still cover exactly the timeline across the join.
3837 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
3838 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
3839 }
3840
3841 #[test]
3842 fn segments_follow_deletes_and_fps() {
3843 let mut p = three();
3844 assert!(p.delete(0));
3845 // source seconds, not timeline: deleting the head does not shift them
3846 let segs = p.segments_from(0, 25.0);
3847 assert_eq!(
3848 segs,
3849 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
3850 );
3851 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
3852 assert!(
3853 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
3854 "segments must cover exactly the timeline: {played}"
3855 );
3856 }
3857
3858 #[test]
3859 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
3860 // Import a second file, undo it: source 1 is now an orphan.
3861 let mut p = two_sources();
3862 assert!(p.undo());
3863 let (sources, lanes, eq, color) = p.without_orphan_sources();
3864 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
3865 assert!(eq.is_empty(), "and a project with no equalizer writes none");
3866 assert!(color.is_empty(), "nor a colour it never graded with");
3867 assert_eq!(
3868 lanes,
3869 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
3870 "the clips are untouched"
3871 );
3872
3873 // Three sources where only the middle one is orphaned: the survivors
3874 // renumber, and the clips follow.
3875 let mut p = Project::single(FILE, 9);
3876 assert_eq!(p.import(FILE2, 0), 1);
3877 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
3878 assert!(p.append_clip(2, 4));
3879 let (sources, lanes, eq, color) = p.without_orphan_sources();
3880 assert_eq!(
3881 sources,
3882 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
3883 );
3884 assert_eq!(
3885 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
3886 [0, 1]
3887 );
3888 // ...and what comes out is loadable, with the same timeline.
3889 let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
3890 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
3891 assert_eq!(reloaded.sources().len(), 2);
3892 }
3893
3894 /// Taking a file out of the library: refused by name -- lanes and counts --
3895 /// while a clip still plays from it, and once nothing does, the entry goes
3896 /// and every clip that indexed past it is renumbered onto the short list.
3897 #[test]
3898 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
3899 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
3900 // plus a second stream of FILE as source 2 with a take of its own.
3901 let mut p = two_sources();
3902 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
3903 assert!(p.append_clip(2, 4));
3904
3905 let refusal = p
3906 .remove_source(1)
3907 .expect_err("a source with clips on it cannot go")
3908 .to_string();
3909 assert!(refusal.contains(FILE2), "names the file: {refusal}");
3910 assert!(
3911 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
3912 "names the lanes holding it: {refusal}"
3913 );
3914 assert!(refusal.contains("still plays"), "{refusal}");
3915 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
3916 assert_eq!(shape(&p)[0][3].source, 1);
3917
3918 // Delete FILE2's take -- the whole span, on every lane -- and the entry
3919 // is free to go. Source 2's clips become source 1's.
3920 assert!(p.delete_in(Lane::V1, 3));
3921 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
3922 p.remove_source(1).expect("nothing plays FILE2 any more");
3923 assert_eq!(
3924 p.sources(),
3925 [Source::new(FILE, 0), Source::new(FILE, 1)],
3926 "the middle entry is gone"
3927 );
3928 assert_eq!(
3929 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
3930 [0, 0, 0, 1],
3931 "the clips past it renumbered"
3932 );
3933 assert_eq!(
3934 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
3935 [0, 0, 0, 1],
3936 "on every lane"
3937 );
3938 // What is left is a project that still loads, which is the whole point
3939 // of renumbering rather than leaving a hole.
3940 let (sources, lanes, eq, color) = p.without_orphan_sources();
3941 Project::from_parts(sources, lanes, eq, color).expect("from_parts");
3942 }
3943
3944 /// The two edges of a removal: it retires the undo stack (the ponytail on
3945 /// [`Project::remove_source`]), and the last entry goes like any other
3946 /// once nothing plays it -- a project may name no file at all.
3947 #[test]
3948 fn remove_source_retires_undo_and_empties_the_library() {
3949 let mut p = two_sources();
3950 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
3951 assert!(!p.history.is_empty(), "there is something to undo");
3952 p.remove_source(1).expect("nothing plays FILE2");
3953 assert!(
3954 p.history.is_empty(),
3955 "a snapshot naming the removed source must not survive it"
3956 );
3957 assert!(!p.undo(), "and so there is nothing left to undo");
3958
3959 // The last file standing is held to the one rule every row is -- what
3960 // plays cannot go -- and to no other.
3961 assert_eq!(p.sources().len(), 1);
3962 let refusal = p
3963 .remove_source(0)
3964 .expect_err("its clips are still on the lanes")
3965 .to_string();
3966 assert!(refusal.contains("still plays"), "{refusal}");
3967 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
3968 while p.delete_in(Lane::V1, 0) {}
3969 p.remove_source(0)
3970 .expect("the last row goes like any other");
3971 assert!(
3972 p.sources().is_empty(),
3973 "a project may name no file at all: an empty library over an empty timeline"
3974 );
3975 assert_eq!(p.timeline_frames(), 0);
3976 assert!(
3977 p.remove_source(0).is_err(),
3978 "and an index that is not there is refused, not panicked on"
3979 );
3980 }
3981
3982 /// A clip's equalizer is the clip's: it survives every edit that copies a
3983 /// placement, and it comes back with an undo.
3984 #[test]
3985 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
3986 let mut p = three();
3987 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
3988 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
3989 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
3990 assert!(
3991 p.eq_of(Lane::V1, 0).is_none(),
3992 "one clip, not the lane above"
3993 );
3994
3995 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
3996 assert!(p.split(1));
3997 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
3998 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
3999 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
4000
4001 // A clipboard copy carries it -- onto another lane, at that.
4002 let copied = p.lane(Lane::A1)[1];
4003 assert!(p.place(Lane::V1, 20, copied));
4004 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
4005 assert!(p.undo());
4006 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
4007
4008 // ...and a change to one is one undo step, in both directions.
4009 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
4010 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
4011 assert!(p.undo());
4012 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
4013 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
4014 assert!(p.eq_of(Lane::A1, 0).is_none());
4015 assert!(p.undo());
4016 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
4017
4018 // Two refusals, neither of which costs an undo step.
4019 let mut nan = band_at(1);
4020 nan.bands[0].q = f32::INFINITY;
4021 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
4022 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
4023 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
4024 assert!(p.undo());
4025 assert_eq!(
4026 p.lane(Lane::A1).len(),
4027 3,
4028 "one step back is before the split"
4029 );
4030 assert!(p.undo());
4031 assert!(
4032 p.eq_of(Lane::A1, 0).is_none(),
4033 "and the next is before the setting: the refusals pushed none"
4034 );
4035 }
4036
4037 /// The table is append-only within a session, exactly as the sources are, so
4038 /// an undone setting is still in it -- and a save is where it goes.
4039 #[test]
4040 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
4041 let mut p = three();
4042 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
4043 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
4044 assert!(p.undo(), "back to the first setting");
4045 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
4046
4047 let (_, lanes, eq, _) = p.without_orphan_sources();
4048 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
4049 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
4050 assert_eq!(lanes[0].1[1].eq, None);
4051
4052 // One curve on three clips is one entry: settings that are equal share.
4053 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
4054 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
4055 let (_, lanes, eq, _) = p.without_orphan_sources();
4056 assert_eq!(eq.len(), 1, "equal settings share their entry");
4057 assert_eq!(lanes[1].1[2].eq, Some(0));
4058 reloads(&p, "an equalizer that outlived an undo");
4059 }
4060
4061 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
4062 /// grade is the clip's, through every edit that copies a placement.
4063 #[test]
4064 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
4065 let mut p = three();
4066 assert!(
4067 p.color_of(Lane::V1, 0).is_none(),
4068 "a fresh clip is ungraded"
4069 );
4070 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
4071 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
4072 assert!(
4073 p.color_of(Lane::A1, 0).is_none(),
4074 "one clip, not the lane below"
4075 );
4076 assert!(
4077 p.eq_of(Lane::V1, 0).is_none(),
4078 "and a grade is not an equalizer"
4079 );
4080
4081 // Cutting a graded clip must not grade half of it: both halves inherit.
4082 assert!(p.split(1));
4083 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
4084 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
4085 assert!(
4086 p.color_of(Lane::V1, 2).is_none(),
4087 "the clip after it is ungraded"
4088 );
4089
4090 // A clipboard copy carries it -- onto another lane, at that.
4091 let copied = p.lane(Lane::V1)[1];
4092 assert!(p.place(Lane::A1, 20, copied));
4093 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
4094 assert!(p.undo());
4095 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
4096
4097 // ...and a change to one is one undo step, in both directions.
4098 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
4099 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
4100 assert!(p.undo());
4101 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
4102 assert!(
4103 p.set_color(Lane::V1, 0, None),
4104 "and taking it off is an edit"
4105 );
4106 assert!(p.color_of(Lane::V1, 0).is_none());
4107 assert!(p.undo());
4108 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
4109
4110 // Two refusals, neither of which costs an undo step.
4111 let nan = ColorParams {
4112 contrast: f32::NAN,
4113 ..grade_at(1)
4114 };
4115 assert!(
4116 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
4117 "no clip there"
4118 );
4119 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
4120 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
4121 assert!(p.undo());
4122 assert_eq!(
4123 p.lane(Lane::V1).len(),
4124 3,
4125 "one step back is before the split"
4126 );
4127 assert!(p.undo());
4128 assert!(
4129 p.color_of(Lane::V1, 0).is_none(),
4130 "and the next is before the grade: the refusals pushed none"
4131 );
4132 }
4133
4134 /// A slider drag is one gesture: the press snapshots, every sample after it
4135 /// only regrades, and the single undo lands on what the clip was *before*
4136 /// the hand touched it -- not one step back down the drag.
4137 #[test]
4138 fn a_whole_colour_drag_undoes_in_one_step() {
4139 let mut p = three();
4140 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
4141 for n in 2..=8 {
4142 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
4143 }
4144 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
4145 assert!(p.undo());
4146 assert!(
4147 p.color_of(Lane::V1, 0).is_none(),
4148 "one undo is the whole gesture, back to ungraded"
4149 );
4150
4151 // The live write refuses what the snapshotting one refuses, and a
4152 // refusal still costs no history either way.
4153 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
4154 assert!(!p.set_color_live(
4155 Lane::V1,
4156 0,
4157 Some(ColorParams {
4158 contrast: f32::NAN,
4159 ..grade_at(1)
4160 })
4161 ));
4162 assert!(p.undo());
4163 assert_eq!(
4164 p.lane(Lane::V1).len(),
4165 2,
4166 "the next step back is the split before the drag: no sample pushed one"
4167 );
4168 }
4169
4170 /// The colour table is append-only within a session, exactly as the eq one
4171 /// is -- and a save is where an undone grade goes.
4172 #[test]
4173 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
4174 let mut p = three();
4175 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
4176 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
4177 assert!(p.undo(), "back to the first grade");
4178 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
4179
4180 let (_, lanes, _, color) = p.without_orphan_sources();
4181 assert_eq!(
4182 color,
4183 vec![grade_at(1)],
4184 "what nothing plays is not written"
4185 );
4186 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
4187 assert_eq!(lanes[0].1[1].color, None);
4188
4189 // One grade on three clips is one entry: settings that are equal share.
4190 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
4191 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
4192 let (_, lanes, _, color) = p.without_orphan_sources();
4193 assert_eq!(color.len(), 1, "equal grades share their entry");
4194 assert_eq!(lanes[1].1[2].color, Some(0));
4195 reloads(&p, "a colour that outlived an undo");
4196
4197 // An equalizer and a grade on one clip are two independent tables.
4198 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
4199 let (_, lanes, eq, color) = p.without_orphan_sources();
4200 assert_eq!((eq.len(), color.len()), (1, 1));
4201 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
4202 }
4203
4204 /// Not a claim about correctness but about cost: a clip is copied on every
4205 /// paste, every undo snapshot and every lane clone, so its size is worth
4206 /// knowing. The eq index fit the padding a `Copy` clip already had; the
4207 /// colour one did not, and the struct grew a word.
4208 #[test]
4209 fn a_clip_is_still_a_small_copy() {
4210 assert_eq!(
4211 std::mem::size_of::<Clip>(),
4212 40,
4213 "Clip changed size -- 32 before the colour index, 40 after"
4214 );
4215 }
4216
4217 #[test]
4218 fn from_parts_has_no_history_and_checks_the_invariants() {
4219 let (sources, lanes, eq, color) = three().without_orphan_sources();
4220 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
4221 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
4222 .expect("valid parts");
4223 assert_eq!(p.clips(), three().clips());
4224 assert!(!p.undo(), "a loaded project has nothing to undo");
4225 assert!(p.split(4), "...and is editable from there");
4226 assert!(p.undo());
4227
4228 // A lane may be empty, and so may every lane -- an emptied timeline is a
4229 // project. No lane at all is not one: there would be nothing to place on.
4230 assert!(
4231 Project::from_parts(
4232 sources.clone(),
4233 two(video.clone(), Vec::new()),
4234 Vec::new(),
4235 Vec::new(),
4236 )
4237 .is_ok()
4238 );
4239 assert!(
4240 Project::from_parts(
4241 sources.clone(),
4242 two(Vec::new(), Vec::new()),
4243 Vec::new(),
4244 Vec::new(),
4245 )
4246 .is_ok()
4247 );
4248 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
4249 let bad: [Vec<Clip>; 5] = [
4250 vec![clip(0, 0, 3, 1)], // source that is not there
4251 vec![clip(0, 3, 3, 0)], // empty clip
4252 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
4253 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
4254 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
4255 ];
4256 for clips in bad {
4257 assert!(
4258 Project::from_parts(
4259 sources.clone(),
4260 two(clips.clone(), Vec::new()),
4261 Vec::new(),
4262 Vec::new(),
4263 )
4264 .is_err(),
4265 "{clips:?}"
4266 );
4267 assert!(
4268 Project::from_parts(
4269 sources.clone(),
4270 two(video.clone(), clips.clone()),
4271 Vec::new(),
4272 Vec::new(),
4273 )
4274 .is_err()
4275 );
4276 // ...and on a third lane, which is checked by the same walk.
4277 assert!(
4278 Project::from_parts(
4279 sources.clone(),
4280 vec![
4281 (LaneKind::Video, video.clone()),
4282 (LaneKind::Audio, audio.clone()),
4283 (LaneKind::Video, clips),
4284 ],
4285 Vec::new(),
4286 Vec::new(),
4287 )
4288 .is_err()
4289 );
4290 }
4291 // An equalizer index no table entry answers, and a table entry the file
4292 // format could not have written, are refused at this door too.
4293 let eqd = |i: u16| {
4294 vec![Clip {
4295 eq: Some(i),
4296 ..video[0]
4297 }]
4298 };
4299 assert!(
4300 Project::from_parts(
4301 sources.clone(),
4302 two(eqd(0), Vec::new()),
4303 Vec::new(),
4304 Vec::new(),
4305 )
4306 .is_err()
4307 );
4308 let mut nan = band_at(1);
4309 nan.bands[0].freq_hz = f32::NAN;
4310 assert!(
4311 Project::from_parts(
4312 sources.clone(),
4313 two(eqd(0), Vec::new()),
4314 vec![nan],
4315 Vec::new(),
4316 )
4317 .is_err()
4318 );
4319 let loaded = Project::from_parts(
4320 sources.clone(),
4321 two(eqd(0), Vec::new()),
4322 vec![band_at(1)],
4323 Vec::new(),
4324 )
4325 .expect("an eq the table holds");
4326 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
4327
4328 // The same two refusals for a colour, at the same door.
4329 let graded = |i: u16| {
4330 vec![Clip {
4331 color: Some(i),
4332 fit: FitPolicy::default(),
4333 speed: Speed::NORMAL,
4334 ..video[0]
4335 }]
4336 };
4337 assert!(
4338 Project::from_parts(
4339 sources.clone(),
4340 two(graded(0), Vec::new()),
4341 Vec::new(),
4342 Vec::new(),
4343 )
4344 .is_err(),
4345 "a colour index no entry answers"
4346 );
4347 assert!(
4348 Project::from_parts(
4349 sources.clone(),
4350 two(graded(0), Vec::new()),
4351 Vec::new(),
4352 vec![ColorParams {
4353 tint: f32::NAN,
4354 ..grade_at(1)
4355 }],
4356 )
4357 .is_err(),
4358 "a value the file format could not have written"
4359 );
4360 let loaded = Project::from_parts(
4361 sources.clone(),
4362 two(graded(0), Vec::new()),
4363 Vec::new(),
4364 vec![grade_at(1)],
4365 )
4366 .expect("a colour the table holds");
4367 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
4368
4369 // Group ids survive a load, and the next split gets a fresh one.
4370 let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
4371 assert!(p.split(4));
4372 assert!(p.clips().iter().all(|c| c.link.is_some()));
4373 }
4374
4375 /// The grouping rules, at the untrusted door and after every edit that can
4376 /// touch a link. A link id is at most one clip per lane and, wherever it is
4377 /// carried, one span -- and no sequence of edits may produce otherwise,
4378 /// because what an edit produces is what a save writes and a load reads.
4379 ///
4380 /// Amended for the lane model: the two errors name their lane `V1`/`A1`
4381 /// rather than "video"/"audio", because with N lanes "the video lane" is no
4382 /// longer a lane. Same causes, same door, same claim.
4383 #[test]
4384 fn a_link_id_is_never_two_clips_of_one_lane() {
4385 let sources = vec![Source::new(FILE, 0)];
4386 let linked = |start, in_frame, out_frame, link| Clip {
4387 start,
4388 in_frame,
4389 out_frame,
4390 source: 0,
4391 link: Some(link),
4392 eq: None,
4393 color: None,
4394 fit: FitPolicy::default(),
4395 speed: Speed::NORMAL,
4396 };
4397
4398 // The door: named errors, one per cause.
4399 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
4400 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
4401 .expect_err("refused")
4402 .to_string()
4403 };
4404 assert!(
4405 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
4406 .contains("link 7 names two clips in the V1 lane"),
4407 "a duplicate id inside one lane is refused by name"
4408 );
4409 assert!(
4410 err(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)])
4411 .contains("link 2 covers [0, 5) in V1 and [0, 3) in A1"),
4412 "a pair that does not cover one span is refused by name"
4413 );
4414 // A one-sided link is *not* an error: it is what a lift leaves behind.
4415 let mut p = Project::single(FILE, 9);
4416 assert!(p.lift(Lane::A1, 0));
4417 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
4418 assert!(
4419 Project::from_parts(sources, lanes, eq, color).is_ok(),
4420 "a lifted lane's project has to load again"
4421 );
4422
4423 // The edits: nothing below may break either rule.
4424 let consistent = |p: &Project, what: &str| {
4425 assert!(
4426 links_are_consistent(&p.lanes).is_ok(),
4427 "{what}: {:?}",
4428 p.lanes
4429 );
4430 };
4431 let mut p = three();
4432 let copied = p.clips()[0];
4433 assert!(
4434 copied.link.is_some(),
4435 "the clipboard clip carries its group"
4436 );
4437 assert!(p.lift(Lane::V1, 0));
4438 assert!(p.place(Lane::V1, 0, copied));
4439 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
4440 assert_eq!(
4441 p.clips().iter().filter(|c| c.link == copied.link).count(),
4442 0,
4443 "a placement belongs to no group, so it cannot duplicate one"
4444 );
4445 consistent(&p, "lift + place twice");
4446 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
4447 consistent(&p, "place through a grouped clip");
4448 assert!(p.paste(6, copied), "a rippling paste through another");
4449 consistent(&p, "paste");
4450 assert!(p.split(2));
4451 consistent(&p, "split");
4452 assert!(p.ripple_delete(1, 3));
4453 consistent(&p, "ripple_delete");
4454 assert!(p.undo());
4455 consistent(&p, "undo");
4456 }
4457
4458 /// What an edit produces is what a save writes, so *every* state the public
4459 /// API can reach has to load again. The two the verifier panel found where
4460 /// it did not: a split and a regroup handed one group id to two clips that
4461 /// were not the same span, because the lanes had been edited apart.
4462 #[test]
4463 fn every_reachable_state_reloads() {
4464 let mut p = Project::single(FILE, 150);
4465 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
4466 assert!(p.split(10), "the lanes are cut apart at 10");
4467 reloads(&p, "place on one lane, then split");
4468
4469 let mut p = Project::single(FILE, 150);
4470 assert!(p.split(30));
4471 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
4472 assert!(p.regroup(30), "only the audio lane can rejoin");
4473 assert!(p.split(60));
4474 reloads(&p, "lift, regroup one lane, split");
4475
4476 // Two audio streams of one file, both placed: two source entries with
4477 // one path between them, which is the state a stream picked out of the
4478 // library reaches -- and the state a save has to write and read back.
4479 let mut p = Project::single(FILE, 150);
4480 let second = p.import(FILE, 1);
4481 assert_eq!(second, 1, "the same file on another stream is a new source");
4482 assert!(p.append_clip(second, 150));
4483 assert!(p.split(200));
4484 reloads(
4485 &p,
4486 "a second audio stream of the same file, placed and split",
4487 );
4488 let (sources, ..) = p.without_orphan_sources();
4489 assert_eq!(
4490 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
4491 [0, 1],
4492 "both entries survive the orphan prune: both are played"
4493 );
4494 }
4495
4496 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
4497 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
4498 /// is the stamp playback puts on a decoded source frame -- and the *last*
4499 /// source frame the pump is still holding at a timeline frame has to be
4500 /// exactly the one the export encoded there, at every rate. Anything else is
4501 /// A/V drift that grows with the clip, and no test of either side alone
4502 /// would see it.
4503 ///
4504 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
4505 /// is a better answer than the floor/floor this had: floor/floor put the
4506 /// preview a whole held frame off the export at slow rates.)
4507 #[test]
4508 fn speed_maps_both_ways() {
4509 for permille in (250..=4000).step_by(1) {
4510 let speed = Speed::from_permille(permille);
4511 assert_eq!(speed.permille(), permille, "no clamping in range");
4512 for d in 0..200u32 {
4513 let want = speed.source_at(d);
4514 // What the pump shows at `d` is the last frame whose stamp has
4515 // come due -- and it is `want`, the frame the export encodes
4516 // there. Slowed, that is the frame it is still holding; sped up,
4517 // it is the newest of the several that arrived.
4518 let held = (0..=want + 8)
4519 .filter(|&s| speed.timeline_at(s) <= d)
4520 .next_back();
4521 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
4522 }
4523 for n in 1..300u32 {
4524 // A footprint is never zero: a clip occupying no timeline frame
4525 // is a placement the lane invariants cannot hold.
4526 let frames = speed.frames(n);
4527 assert!(frames >= 1, "{speed} of {n} frames");
4528 // ...and its last timeline frame never reads past the clip.
4529 assert!(
4530 speed.source_at(frames - 1) < n,
4531 "{speed}: the last timeline frame of {n} reads past the clip"
4532 );
4533 // The trim inverse never overshoots the room it was given, and
4534 // answers for every room a footprint can be.
4535 let fit = speed.fit(frames).expect("a clip fits its own footprint");
4536 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
4537 // A room narrower than one source frame's own footprint holds
4538 // nothing, and says so rather than rounding something into it.
4539 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
4540 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
4541 }
4542 }
4543 // Real time is the identity map, byte for byte.
4544 for d in 0..1000 {
4545 assert_eq!(Speed::NORMAL.source_at(d), d);
4546 assert_eq!(Speed::NORMAL.timeline_at(d), d);
4547 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
4548 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
4549 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
4550 }
4551 // The one door: no zero, no reverse, nothing past the ends.
4552 assert_eq!(Speed::from_permille(0), Speed::MIN);
4553 assert_eq!(Speed::from_permille(249), Speed::MIN);
4554 assert_eq!(Speed::from_permille(4001), Speed::MAX);
4555 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
4556 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
4557 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
4558 }
4559
4560 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
4561 /// source frames per timeline frame and still starts at its own in-point,
4562 /// and a half-speed one shows every source frame twice.
4563 #[test]
4564 fn a_rate_maps_timeline_frames_onto_source_frames() {
4565 let mut p = Project::single(FILE, 40);
4566 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
4567 .expect("room enough");
4568 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
4569 assert_eq!(
4570 p.map(Lane::V1, 0),
4571 Some((0, 0)),
4572 "and it starts where it did"
4573 );
4574 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
4575 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
4576 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
4577 // The span a decoder is handed: as many source frames as it will read,
4578 // which is the last shown frame's own and not one more -- timeline frame
4579 // 19 shows source frame 38, so 39 frames are read and the 40th is a
4580 // picture nothing would display.
4581 let span = p.span_at(Lane::V1, 0).expect("a span");
4582 assert_eq!((span.len, span.source_len()), (20, 39));
4583 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
4584 // ...and the same clip the other way round.
4585 let mut p = Project::single(FILE, 40);
4586 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
4587 .expect("room enough");
4588 assert_eq!(p.timeline_frames(), 80);
4589 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
4590 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
4591 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
4592 assert_eq!(
4593 p.map(Lane::V1, 79),
4594 Some((0, 39)),
4595 "and the last timeline frame is still inside the source range"
4596 );
4597 }
4598
4599 /// A trim of a speeded clip is still a trim of its *source*, and the edge
4600 /// still stops at the wall: the room a rate leaves is measured in timeline
4601 /// frames and the range it commits in source ones.
4602 #[test]
4603 fn trimming_a_speeded_clip_stays_inside_its_room() {
4604 let mut p = Project::single(FILE, 40);
4605 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
4606 .expect("room enough");
4607 // A second clip butted against the first, so the wall is a real one.
4608 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
4609 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
4610 assert_eq!(room, (1, 20), "out to the neighbour and no further");
4611 assert!(
4612 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
4613 "clamped to the wall, which is where the edge already is"
4614 );
4615 let c = p.clips()[0];
4616 assert_eq!(c.end(), 20, "so nothing moved");
4617 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
4618 // ...and in: half the timeline frames is half the source range.
4619 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
4620 let c = p.clips()[0];
4621 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
4622 assert_eq!(c.end(), 10, "and ten timeline frames of them");
4623 assert!(sorted_disjoint(p.clips()));
4624 }
4625
4626 /// The frames a rate cannot address: at half speed each source frame is on
4627 /// screen twice, and the cut between the two showings is not a cut in the
4628 /// file. Refused, so the two halves always add up to the clip that was cut.
4629 #[test]
4630 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
4631 let mut p = Project::single(FILE, 10);
4632 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
4633 .expect("room enough");
4634 assert_eq!(p.timeline_frames(), 20);
4635 assert!(
4636 !p.split(3),
4637 "an odd frame is between two showings of one frame"
4638 );
4639 assert_eq!(p.clips().len(), 1, "and nothing was cut");
4640 assert!(p.split(4), "an even one is a frame boundary");
4641 let halves = p.clips().to_vec();
4642 assert_eq!(
4643 (halves[0].end(), halves[1].start, halves[1].end()),
4644 (4, 4, 20),
4645 "the halves meet, and still end where the clip did"
4646 );
4647 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
4648 assert!(p.regroup(4), "and the inverse puts it back");
4649 assert_eq!(p.clips().len(), 1);
4650 }
4651
4652 /// The same claim, swept: random op sequences off the public surface, the
4653 /// project reloaded after every one of them. A failure prints its seed, and
4654 /// the seed replays the whole sequence.
4655 #[test]
4656 fn random_edit_sequences_reload() {
4657 // Two thousand, not two hundred: the overlap a hole punched into a slow
4658 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
4659 // sequences, and a 200-seed sweep walked straight past it (it took a
4660 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
4661 // has no business being the narrow one.
4662 for seed in 0..2000u64 {
4663 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
4664 let mut next = move |n: u32| {
4665 // xorshift64*: no dependency, and the seed replays it exactly.
4666 rng ^= rng << 13;
4667 rng ^= rng >> 7;
4668 rng ^= rng << 17;
4669 (rng >> 33) as u32 % n
4670 };
4671 let mut p = Project::single(FILE, 40);
4672 for step in 0..24 {
4673 let frame = next(44);
4674 // A clipboard copy carries the group id of the take it came from
4675 // -- the input that made a placement duplicate an id -- and, one
4676 // time in three, a rate of its own: a *speeded clip placed over
4677 // a speeded clip* is the shape whose remainders have to be run
4678 // through `Speed::fit`, and it is not a shape the lanes hand out
4679 // on their own often enough to be sure of.
4680 let mut copied = *p
4681 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
4682 .get(next(4) as usize)
4683 .unwrap_or(&clip(0, 0, 5, 0));
4684 if next(3) == 0 {
4685 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
4686 }
4687 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
4688 let idx = next(4) as usize;
4689 let _ = match next(15) {
4690 // ...and a second `place`, so a punch lands inside a clip
4691 // far more often than one op in fourteen would put it there.
4692 14 => p.place(lane, frame, copied),
4693 0 => p.split(frame),
4694 1 => p.regroup(frame),
4695 2 => p.lift(lane, idx),
4696 3 => p.place(lane, frame, copied),
4697 4 => p.paste(frame, copied),
4698 5 => p.ripple_delete(frame, next(9)),
4699 6 => p.delete(idx),
4700 7 => p.undo(),
4701 // An equalizer put on and taken off in the mix: what a clip
4702 // carries has to reload with it, and the entries an undo
4703 // orphans must not come back out of the prune.
4704 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
4705 9 => p.set_eq(lane, idx, None),
4706 // ...and a colour grade in the same mix, for the same
4707 // reason: it rides on the clip and its orphans must go.
4708 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
4709 11 => p.set_color(lane, idx, None),
4710 // ...and a rate in with them, which is the one of the three
4711 // that moves *placements*: a clip that grew has to be
4712 // refused rather than overlap, and one that shrank leaves a
4713 // lane that still loads. Both are what `reloads` asks.
4714 12 => p
4715 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
4716 .is_ok(),
4717 _ => p.append_clip(0, 1 + next(9)),
4718 };
4719 reloads(&p, &format!("seed {seed}, step {step}"));
4720 }
4721 }
4722 }
4723
4724 /// The save/load round trip a project must survive: the parts a save writes,
4725 /// handed back to the constructor a load goes through -- every lane of them,
4726 /// and the reloaded timeline has to be the same lanes in the same order.
4727 fn reloads(p: &Project, what: &str) {
4728 let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
4729 match Project::from_parts(sources, lanes, eq, color) {
4730 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
4731 Ok(back) => {
4732 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
4733 // Placements, not whole clips: an orphan prune renumbers the
4734 // sources a clip names, which is the point of it.
4735 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
4736 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
4737 };
4738 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
4739 // The prune renumbers the eq table too, so what has to survive
4740 // is the settings themselves, clip by clip.
4741 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
4742 p.lanes()
4743 .into_iter()
4744 .map(|l| {
4745 (0..p.lane(l).len())
4746 .map(|i| p.eq_of(l, i).cloned())
4747 .collect()
4748 })
4749 .collect()
4750 };
4751 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
4752 // The colour table renumbers in the same prune, so the same
4753 // claim: the params a clip names, not the index it names them by.
4754 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
4755 p.lanes()
4756 .into_iter()
4757 .map(|l| {
4758 (0..p.lane(l).len())
4759 .map(|i| p.color_of(l, i).copied())
4760 .collect()
4761 })
4762 .collect()
4763 };
4764 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
4765 }
4766 }
4767 }
4768
4769 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
4770 /// -- each one sorted and disjoint, and one span per group id -- asserted
4771 /// directly, where the point is the invariant rather than the round trip.
4772 fn invariants_hold(p: &Project, what: &str) {
4773 for lane in p.lanes() {
4774 assert!(
4775 sorted_disjoint(p.lane(lane)),
4776 "{what}: {} is out of order or overlaps itself: {:?}",
4777 lane.label(),
4778 p.lane(lane)
4779 );
4780 }
4781 if let Err(e) = links_are_consistent(&p.lanes) {
4782 panic!("{what}: {e}\n{:?}", p.lanes);
4783 }
4784 }
4785
4786 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
4787 /// edited without any other lane hearing about it. A handle naming a lane
4788 /// that is not there reads as empty and refuses to mutate.
4789 #[test]
4790 fn a_third_lane_is_a_peer() {
4791 let mut p = three();
4792 assert_eq!(p.lane_count(LaneKind::Video), 1);
4793 assert_eq!(p.lane_count(LaneKind::Audio), 1);
4794 let v2 = p.add_lane(LaneKind::Video);
4795 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
4796 assert_eq!(v2.label(), "V2");
4797 assert_eq!(p.lane_count(LaneKind::Video), 2);
4798 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
4799 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
4800
4801 // A handle for a lane that is not there: empty, and no mutation takes.
4802 let v3 = Lane::new(LaneKind::Video, 2);
4803 assert!(p.lane(v3).is_empty());
4804 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
4805 assert!(!p.lift(v3, 0));
4806 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
4807
4808 // Placing on V2 moves nothing else, and the lane can outrun the rest.
4809 let before = shape(&p);
4810 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
4811 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
4812 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
4813 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
4814 assert_eq!(
4815 p.timeline_frames(),
4816 16,
4817 "the last lane to end sets the length"
4818 );
4819 assert_eq!(p.map(v2, 5), Some((0, 21)));
4820 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
4821 assert_eq!(
4822 p.span_at(v2, 0),
4823 Some(Span {
4824 start: 0,
4825 len: 4,
4826 from: None,
4827 speed: Speed::NORMAL
4828 })
4829 );
4830 // Every lane still covers the whole timeline, gaps included.
4831 for l in p.lanes() {
4832 let spans = p.spans_from(l, 0);
4833 assert_eq!(
4834 spans.iter().map(|s| s.len).sum::<u32>(),
4835 16,
4836 "{}",
4837 l.label()
4838 );
4839 }
4840 // ...and playback still reads V1 and A1, whatever else is there.
4841 assert_eq!(p.clips(), p.lane(Lane::V1));
4842 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
4843 let segments = p.segments_from(0, FPS);
4844 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
4845 assert_eq!(
4846 segments[3],
4847 (None, 0.0, 7.0 / FPS),
4848 "A1 keeps the clock counting over the picture V2 added"
4849 );
4850 invariants_hold(&p, "place on V2");
4851
4852 // A lift is that lane's business too, and the lane list undoes.
4853 assert!(p.lift(v2, 0));
4854 assert!(p.lane(v2).is_empty());
4855 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
4856 assert!(p.undo());
4857 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
4858 assert!(p.undo());
4859 assert!(p.lane(v2).is_empty(), "the placement came off V2");
4860 assert!(p.undo(), "and one more step takes the lane itself back");
4861 assert_eq!(p.lane_count(LaneKind::Video), 1);
4862 assert_eq!(shape(&p), shape(&three()));
4863 }
4864
4865 /// The add taken back: an empty lane comes off, a lane holding clips never
4866 /// does (and says which clips), the last lane of a kind never does, the
4867 /// lanes below the one that went move up an `ord`, and one undo puts it
4868 /// back where it stood.
4869 #[test]
4870 fn an_empty_lane_comes_off_again() {
4871 let mut p = three();
4872 let v2 = p.add_lane(LaneKind::Video);
4873 let v3 = p.add_lane(LaneKind::Video);
4874 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
4875 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
4876 let history = p.history.len();
4877
4878 // The last lane of its kind stays: `V1`/`A1` are where an import and a
4879 // paste land, and a project missing one would swallow half of a file
4880 // dropped on it.
4881 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
4882 assert_eq!(
4883 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
4884 "there is no V10 to remove"
4885 );
4886
4887 // A lane with clips on it refuses and names them: a track removal never
4888 // deletes a take.
4889 let refusal = why(p.remove_lane(v3));
4890 assert!(refusal.contains("V3 still holds"), "{refusal}");
4891 assert!(refusal.contains(FILE), "{refusal}");
4892 assert!(refusal.contains("at frame 0"), "{refusal}");
4893 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
4894 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
4895
4896 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
4897 // all.
4898 p.remove_lane(v2).expect("V2 is empty");
4899 assert_eq!(p.lane_count(LaneKind::Video), 2);
4900 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
4901 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
4902 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
4903 invariants_hold(&p, "remove V2");
4904
4905 // ...and one stroke puts the empty lane back above it.
4906 assert!(p.undo());
4907 assert_eq!(p.lane_count(LaneKind::Video), 3);
4908 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
4909 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
4910 }
4911
4912 /// The grouping rule across more than two lanes: a link id is one *span*,
4913 /// on however many lanes carry it -- not a video/audio pair and not a
4914 /// pairing by `ord`. So a split shares an id with every lane whose half
4915 /// lines up, and gives its own to every lane whose half does not.
4916 #[test]
4917 fn a_group_id_is_one_span_across_every_lane() {
4918 let mut p = Project::single(FILE, 9);
4919 let v2 = p.add_lane(LaneKind::Video);
4920 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "three lanes, one span");
4921 assert!(p.split(4));
4922 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
4923 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
4924 };
4925 let (left, right) = (side(&p, 0), side(&p, 1));
4926 assert!(
4927 left[0].is_some() && left.iter().all(|id| *id == left[0]),
4928 "one id for three left halves: {left:?}"
4929 );
4930 assert!(right.iter().all(|id| *id == right[0]), "{right:?}");
4931 assert_ne!(left[0], right[0], "the halves are no longer one take");
4932 invariants_hold(&p, "split across three lanes");
4933
4934 // V2 ends early: same start, so the left halves are one take; different
4935 // end, so the right halves cannot be.
4936 let mut p = Project::single(FILE, 9);
4937 let v2 = p.add_lane(LaneKind::Video);
4938 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
4939 assert!(p.split(3));
4940 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "same [0, 3)");
4941 assert_ne!(
4942 p.lane(Lane::V1)[1].link,
4943 p.lane(v2)[1].link,
4944 "[3,9) vs [3,6)"
4945 );
4946 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
4947 invariants_hold(&p, "split where one lane ends early");
4948
4949 // The inverse rejoins all three, and groups them the same way.
4950 assert!(p.regroup(3));
4951 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
4952 assert_ne!(
4953 p.lane(Lane::V1)[0].link,
4954 p.lane(v2)[0].link,
4955 "V2 rejoins into a span of its own"
4956 );
4957 invariants_hold(&p, "regroup across three lanes");
4958
4959 // ...and the rule is enforced, not merely produced: two video lanes
4960 // carrying one id over two spans is refused, by lane name.
4961 let linked = |out_frame, link| Clip {
4962 start: 0,
4963 in_frame: 0,
4964 out_frame,
4965 source: 0,
4966 link: Some(link),
4967 eq: None,
4968 color: None,
4969 fit: FitPolicy::default(),
4970 speed: Speed::NORMAL,
4971 };
4972 let lanes = vec![
4973 LaneData {
4974 kind: LaneKind::Video,
4975 clips: vec![linked(3, 4)],
4976 },
4977 LaneData {
4978 kind: LaneKind::Video,
4979 clips: vec![linked(5, 4)],
4980 },
4981 ];
4982 assert_eq!(
4983 links_are_consistent(&lanes).unwrap_err().to_string(),
4984 "link 4 covers [0, 3) in V1 and [0, 5) in V2"
4985 );
4986 }
4987
4988 /// A group is a set of clips over one span, at most one per lane: a picture
4989 /// may be grouped with sound in *any* audio lane -- there is no paired ord,
4990 /// and the lanes in between may be empty -- and the two ways to break that
4991 /// name the lane they broke it on. Lanes built by hand, because the rule is
4992 /// checked at the untrusted door and no edit can produce these.
4993 #[test]
4994 fn a_group_may_span_any_lane() {
4995 let lane = |kind, clips: Vec<Clip>| LaneData { kind, clips };
4996 let one = |start: u32, end: u32, link| Clip {
4997 start,
4998 in_frame: start,
4999 out_frame: end,
5000 source: 0,
5001 link: Some(link),
5002 eq: None,
5003 color: None,
5004 fit: FitPolicy::default(),
5005 speed: Speed::NORMAL,
5006 };
5007 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
5008 let kinds = [
5009 LaneKind::Video,
5010 LaneKind::Audio,
5011 LaneKind::Video,
5012 LaneKind::Audio,
5013 ];
5014 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
5015 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
5016 };
5017 let take = || vec![one(0, 4, 7)];
5018 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
5019 // The same take on V1 + A2 only, the lanes between it empty: legal, the
5020 // way a lifted half is legal.
5021 let across = build([take(), Vec::new(), Vec::new(), take()]);
5022 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
5023 // Disagreeing about the span is not, and the message names both lanes.
5024 let apart = build([take(), Vec::new(), Vec::new(), vec![one(0, 6, 7)]]);
5025 assert_eq!(
5026 links_are_consistent(&apart).unwrap_err().to_string(),
5027 "link 7 covers [0, 4) in V1 and [0, 6) in A2"
5028 );
5029 // ...and one id twice in one lane is still that lane's error, by name.
5030 let twice = build([
5031 Vec::new(),
5032 Vec::new(),
5033 vec![one(0, 4, 7), one(4, 8, 7)],
5034 Vec::new(),
5035 ]);
5036 assert_eq!(
5037 links_are_consistent(&twice).unwrap_err().to_string(),
5038 "link 7 names two clips in the V2 lane"
5039 );
5040 }
5041
5042 /// Every lane a save writes comes out, in display order and with its kind --
5043 /// an empty one included, since it is state a front-end shows -- and a
5044 /// two-lane project still writes exactly the parts it always did.
5045 #[test]
5046 fn a_save_writes_every_lane_it_has() {
5047 let mut p = three();
5048 let before = p.without_orphan_sources();
5049 assert_eq!(before.1.len(), 2, "V1 and A1");
5050 let v2 = p.add_lane(LaneKind::Video);
5051 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
5052 let a2 = p.add_lane(LaneKind::Audio);
5053 let (sources, lanes, eq, color) = p.without_orphan_sources();
5054 assert_eq!(
5055 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
5056 [
5057 LaneKind::Video,
5058 LaneKind::Audio,
5059 LaneKind::Video,
5060 LaneKind::Audio
5061 ],
5062 "display order, not video-then-audio"
5063 );
5064 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
5065 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
5066 // ...and all four load again as the same four.
5067 let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
5068 assert_eq!(back.lanes(), p.lanes());
5069 assert_eq!(back.lane(a2), p.lane(a2));
5070
5071 // Taking the lanes back leaves exactly what a two-lane save wrote.
5072 for _ in 0..3 {
5073 assert!(p.undo());
5074 }
5075 assert_eq!(
5076 p.without_orphan_sources(),
5077 before,
5078 "byte for byte the same parts a two-lane save always wrote"
5079 );
5080 }
5081
5082 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
5083 /// three lanes and grows more: every lane's own order and the one
5084 /// span-per-id rule after every op, *and* the reload the v4 format restored
5085 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
5086 /// project of any number of lanes.
5087 #[test]
5088 fn random_edit_sequences_keep_many_lanes_consistent() {
5089 for seed in 0..2000u64 {
5090 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
5091 let mut next = move |n: u32| {
5092 rng ^= rng << 13;
5093 rng ^= rng >> 7;
5094 rng ^= rng << 17;
5095 (rng >> 33) as u32 % n
5096 };
5097 let mut p = Project::single(FILE, 40);
5098 let v2 = p.add_lane(LaneKind::Video);
5099 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
5100 let lanes = [Lane::V1, Lane::A1, v2];
5101 for step in 0..24 {
5102 let frame = next(44);
5103 let copied = *p
5104 .lane(lanes[next(3) as usize])
5105 .get(next(4) as usize)
5106 .unwrap_or(&clip(0, 0, 5, 0));
5107 let lane = lanes[next(3) as usize];
5108 let idx = next(4) as usize;
5109 let _ = match next(13) {
5110 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
5111 11 => p.set_eq(lane, idx, None),
5112 // A rate, which on many lanes is the group rule as well:
5113 // every clip carrying the link moves together or none of
5114 // them does, and `invariants_hold` is what says so.
5115 12 => p
5116 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
5117 .is_ok(),
5118 0 => p.split(frame),
5119 1 => p.regroup(frame),
5120 2 => p.lift(lane, idx),
5121 3 => p.place(lane, frame, copied),
5122 4 => p.paste(frame, copied),
5123 5 => p.ripple_delete(frame, next(9)),
5124 6 => p.delete(idx),
5125 7 => p.undo(),
5126 8 => {
5127 p.add_lane(if next(2) == 0 {
5128 LaneKind::Video
5129 } else {
5130 LaneKind::Audio
5131 });
5132 true
5133 }
5134 _ => p.append_clip(0, 1 + next(9)),
5135 };
5136 invariants_hold(&p, &format!("seed {seed}, step {step}"));
5137 reloads(&p, &format!("seed {seed}, step {step}"));
5138 }
5139 }
5140 }
5141
5142 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
5143 /// there, `V1` shows again on either side of it, and a frame no video lane
5144 /// covers is a gap however many lanes there are.
5145 #[test]
5146 fn the_composite_is_the_topmost_lane_with_a_clip() {
5147 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
5148 let lanes = vec![
5149 // V1: the whole 30 frames of source 0.
5150 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
5151 // V2: source 1 over the middle third.
5152 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
5153 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
5154 ];
5155 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
5156 assert_eq!(
5157 p.composite_spans_from(0),
5158 vec![
5159 Span {
5160 start: 0,
5161 len: 10,
5162 from: Some((0, 0)),
5163 speed: Speed::NORMAL
5164 },
5165 Span {
5166 start: 10,
5167 len: 10,
5168 from: Some((1, 5)),
5169 speed: Speed::NORMAL
5170 },
5171 Span {
5172 start: 20,
5173 len: 10,
5174 from: Some((0, 20)),
5175 speed: Speed::NORMAL
5176 },
5177 ],
5178 "V2 takes over for its own span and hands V1 back"
5179 );
5180 // A mid-span ask resolves the same way, which is what a seek does.
5181 assert_eq!(
5182 p.composite_span_at(15),
5183 Some(Span {
5184 start: 15,
5185 len: 5,
5186 from: Some((1, 10)),
5187 speed: Speed::NORMAL
5188 })
5189 );
5190 assert_eq!(p.composite_span_at(30), None, "past the end");
5191
5192 // A hole in V1 under V2's clip: black between the two, and black after
5193 // both run out (the audio lane is still holding the timeline open).
5194 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
5195 let holed = vec![
5196 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
5197 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
5198 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
5199 ];
5200 let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts");
5201 assert_eq!(
5202 p.composite_spans_from(0),
5203 vec![
5204 Span {
5205 start: 0,
5206 len: 5,
5207 from: Some((0, 0)),
5208 speed: Speed::NORMAL
5209 },
5210 Span {
5211 start: 5,
5212 len: 5,
5213 from: None,
5214 speed: Speed::NORMAL
5215 },
5216 Span {
5217 start: 10,
5218 len: 10,
5219 from: Some((1, 0)),
5220 speed: Speed::NORMAL
5221 },
5222 Span {
5223 start: 20,
5224 len: 10,
5225 from: None,
5226 speed: Speed::NORMAL
5227 },
5228 ]
5229 );
5230
5231 // One video lane: the composite *is* that lane, span for span -- the
5232 // promise every existing two-lane project rests on.
5233 let p = Project::single(FILE, 30);
5234 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
5235 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
5236 }
5237
5238 /// Every audio lane holding something gets a play list, and only those.
5239 #[test]
5240 fn audio_segments_cover_every_lane_that_holds_something() {
5241 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
5242 let lanes = vec![
5243 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
5244 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
5245 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
5246 (LaneKind::Audio, Vec::new()),
5247 ];
5248 let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts");
5249 let lists = p.audio_segments_from(0, FPS);
5250 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
5251 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
5252 // A2 is a gap up to frame 15, then the whole of source 1.
5253 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
5254
5255 // No audio lane holds anything: one all-gap list, so such a timeline
5256 // still plays silence against a master clock.
5257 let p = Project::from_parts(
5258 vec![Source::new(FILE, 0)],
5259 vec![
5260 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
5261 (LaneKind::Audio, Vec::new()),
5262 ],
5263 vec![],
5264 vec![],
5265 )
5266 .expect("valid parts");
5267 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
5268 }
5269}