forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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