forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2b647eaTahinli3 months ago190 commits

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