forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB65ea910Tahinli3 months ago308 commits

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