forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB86e9455Tahinli3 months ago398 commits

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