forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

project.rs10278 lines, 448.8 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//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119);
120
121impl Speed {
122 /// Real time -- what every clip is until something says otherwise, and the
123 /// value every path in this engine short-circuits on.
124 pub const NORMAL: Speed = Speed(1000);
125 pub const MIN: Speed = Speed(250);
126 pub const MAX: Speed = Speed(4000);
127
128 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
129 /// unrepresentable rather than merely refused: nothing downstream divides
130 /// by a speed that could be nothing.
131 pub fn from_permille(permille: u16) -> Self {
132 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
133 }
134
135 pub fn permille(self) -> u16 {
136 self.0
137 }
138
139 pub fn is_normal(self) -> bool {
140 self == Self::NORMAL
141 }
142
143 /// As a multiplier, for the sound worker and for a label.
144 pub fn as_f64(self) -> f64 {
145 f64::from(self.0) / 1000.
146 }
147
148 /// How many *timeline* frames `source` source frames occupy at this rate --
149 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
150 /// clip that occupied no frames would be an empty placement, which the lane
151 /// invariant forbids and which nothing could ever click on again.
152 pub fn frames(self, source: u32) -> u32 {
153 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
154 n.clamp(1, u64::from(u32::MAX)) as u32
155 }
156
157 /// The mapping itself: which source frame of a clip the `offset`th timeline
158 /// frame of it plays. Floored, so the first timeline frame is the clip's own
159 /// in-point at every rate.
160 pub fn source_at(self, offset: u32) -> u32 {
161 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
162 }
163
164 /// Its inverse, for a decoder's frames on their way back out: which timeline
165 /// frame of the clip the `offset`th *source* frame of it lands on.
166 ///
167 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
168 /// decoded frame with this and shows the newest whose stamp has come due, so
169 /// what is on screen at timeline offset `d` is the last source frame with
170 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
171 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
172 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
173 /// the two the same way would put the preview a frame off the export at some
174 /// speeds and a whole held frame off at slow ones -- drift that no test of
175 /// either side alone would catch.
176 pub fn timeline_at(self, offset: u32) -> u32 {
177 (u64::from(offset) * 1000)
178 .div_ceil(u64::from(self.0))
179 .min(u64::from(u32::MAX)) as u32
180 }
181
182 /// The longest source range that still *fits* in `frames` timeline frames at
183 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
184 /// any room narrower than the four timeline frames one source frame occupies.
185 ///
186 /// What a trim commits and what a hole-punch leaves behind: rounding could
187 /// otherwise hand back a range wider than the room, and a clip that outgrew
188 /// its room would overlap its neighbour -- the one thing a lane may never do.
189 /// `None` is not an error, it is "no remainder": the caller drops that piece
190 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
191 /// is `frames` itself, so nothing about an unspeeded edit changes.
192 pub fn fit(self, frames: u32) -> Option<u32> {
193 if frames == 0 || self.frames(1) > frames {
194 return None;
195 }
196 let mut src = self.source_at(frames).max(1);
197 // At most a step or two: `frames` is monotone in `src` and the rounding
198 // above can only overshoot by one source frame's worth.
199 while src > 1 && self.frames(src) > frames {
200 src -= 1;
201 }
202 Some(src)
203 }
204
205 /// How many timeline frames `source` source frames of head (or tail) are
206 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
207 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
208 /// empty, but the room in front of one may well be.
209 pub fn room(self, source: u32) -> u32 {
210 match source {
211 0 => 0,
212 n => self.frames(n),
213 }
214 }
215
216 /// How many timeline frames from `offset` on show the **same** source frame:
217 /// one at real time and faster, more when the clip is slowed. What an export
218 /// encodes without decoding the same picture twice, and the count that makes
219 /// its frame walk exactly as long as the span.
220 pub fn repeats(self, offset: u32, len: u32) -> u32 {
221 let want = self.source_at(offset);
222 (offset..len)
223 .take_while(|&t| self.source_at(t) == want)
224 .count() as u32
225 }
226
227 /// Where in the source a cut `offset` timeline frames into a clip of `len`
228 /// source frames falls -- and `None` when this rate cannot address that
229 /// frame at all.
230 ///
231 /// At half speed a clip of ten source frames is twenty timeline frames long
232 /// and every source frame is on screen twice, so a cut between the two
233 /// showings of one frame is not a cut in the *file*: taking it would leave
234 /// two halves whose lengths no longer add up to the clip that was cut --
235 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
236 /// the model stays exact and the front-end can say why. At real time every
237 /// interior frame answers, which is the path a project without speeds is on.
238 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
239 let src = self.source_at(offset);
240 (src > 0
241 && src < len
242 && self.frames(src) == offset
243 && self.frames(len - src) == self.frames(len) - offset)
244 .then_some(src)
245 }
246}
247
248impl Default for Speed {
249 fn default() -> Self {
250 Self::NORMAL
251 }
252}
253
254impl std::fmt::Display for Speed {
255 /// `2.00x` -- what a card prints and what a clip box is marked with.
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{:.2}x", self.as_f64())
258 }
259}
260
261/// What a file's own frame rate is against the timeline's, as an exact
262/// rational: how many frames of the *file* one frame of the timeline is worth.
263///
264/// Every frame number in this module counts **timeline** frames -- a clip's
265/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
266/// timeline is as many frames long as the seconds it lasts, and every edit
267/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
268/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
269/// opens a worker with it and [`crate::export`] pulls pictures through it. The
270/// file's own numbering exists nowhere else.
271///
272/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
273/// export encodes at a timeline frame has to be the frame playback is holding
274/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
275/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
276///
277/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
278/// stays `800/1001` however far the timeline runs, where a rate rounded to
279/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
280/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
281///
282/// [`PlaybackSession`]: crate::PlaybackSession
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
284pub struct Rate {
285 /// Frames of the file...
286 source: u32,
287 /// ...per this many frames of the timeline it plays on. Never zero.
288 timeline: u32,
289}
290
291impl Rate {
292 /// A file shot at the timeline's own rate: every conversion below is the
293 /// identity, which is the path a single-rate project is on.
294 pub const REAL_TIME: Self = Self {
295 source: 1,
296 timeline: 1,
297 };
298
299 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
300 /// exactly.
301 ///
302 /// Both rates come out of a container as a division, so neither is ever the
303 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
304 /// already knows how to name one exactly -- it is the same pair the muxer
305 /// counts an export's frames in -- and this is that pair divided by that
306 /// pair, reduced. A rate no timescale can name is an `Err` in that
307 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
308 /// where a file carrying one is refused by name, beside the codec.
309 ///
310 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
311 /// timeline that had ever opened in this editor before mixed rates.
312 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
313 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
314 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
315 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
316 let num = u64::from(src_scale) * u64::from(tl_ticks);
317 let den = u64::from(src_ticks) * u64::from(tl_scale);
318 Ok(Self::reduced(num, den))
319 }
320
321 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
322 fn reduced(num: u64, den: u64) -> Self {
323 let g = gcd(num, den);
324 let (mut num, mut den) = (num / g, den / g);
325 // A ratio no pair of real frame rates produces, but the fields are `u32`
326 // so that every multiplication below fits a `u64` at any frame count.
327 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
328 (num, den) = (num.div_ceil(2), den.div_ceil(2));
329 }
330 Self {
331 source: num.max(1) as u32,
332 timeline: den.max(1) as u32,
333 }
334 }
335
336 /// The same file against a timeline that has itself been retimed: `self` is
337 /// its frames per frame of the old timeline and `k` is old frames per new
338 /// one, so this is its frames per frame of the *new* one -- exactly, without
339 /// going back through an `f64` fps that names neither rate
340 /// ([`crate::PlaybackSession::set_frame_rate`]).
341 pub fn then(self, k: Rate) -> Self {
342 Self::reduced(
343 u64::from(self.source) * u64::from(k.source),
344 u64::from(self.timeline) * u64::from(k.timeline),
345 )
346 }
347
348 pub fn is_real_time(self) -> bool {
349 self.source == self.timeline
350 }
351
352 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
353 /// is, given the timeline's, for a library row that names it.
354 pub fn as_f64(self) -> f64 {
355 f64::from(self.source) / f64::from(self.timeline)
356 }
357
358 /// Which frame of the file the `frame`th timeline-rate frame of it is:
359 /// floored, [`Speed::source_at`]'s half of the pair.
360 pub fn source_at(self, frame: u32) -> u32 {
361 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
362 .min(u64::from(u32::MAX)) as u32
363 }
364
365 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
366 /// timeline-rate frame that shows source frame `source_frame` -- which is
367 /// the stamp playback puts on a decoded picture, and, applied to a file's
368 /// frame *count*, how long that file is in timeline frames.
369 pub fn timeline_at(self, source_frame: u32) -> u32 {
370 (u64::from(source_frame) * u64::from(self.timeline))
371 .div_ceil(u64::from(self.source))
372 .min(u64::from(u32::MAX)) as u32
373 }
374}
375
376/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
377/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
378fn gcd(a: u64, b: u64) -> u64 {
379 match b {
380 0 => a.max(1),
381 b => gcd(b, a % b),
382 }
383}
384
385/// A half-open `[in_frame, out_frame)` range of frames of source
386/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
387/// Never empty.
388///
389/// Counted at the **timeline's** frame rate, not the file's: a source shot at
390/// another rate is converted at the decoder's door ([`Rate`]), so every edit
391/// here is frames of one clock.
392#[derive(Clone, Copy, PartialEq, Eq, Debug)]
393pub struct Clip {
394 /// Timeline frame the clip's first frame is shown at. Meaningless on a
395 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
396 /// with where the caller asked for.
397 pub start: u32,
398 pub in_frame: u32,
399 pub out_frame: u32,
400 /// Index into [`Project::sources`].
401 pub source: usize,
402 /// Group id: clips sharing one were split from the same take. `None` for a
403 /// clip that belongs to no group.
404 pub link: Option<u32>,
405 /// Index into the project's equalizer table
406 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
407 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
408 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
409 /// plain assignment. The table is append-only within a session, so an index
410 /// on a clipboard clip or inside an undo snapshot can never dangle.
411 pub eq: Option<u16>,
412 /// Index into the project's colour table
413 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
414 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
415 /// promises: `Copy`, append-only within a session, never dangling.
416 pub color: Option<u16>,
417 /// Index into the project's transform table
418 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
419 /// clip that plays at its fit policy's own placement. An index for
420 /// [`Clip::color`]'s reason and with the same promises.
421 pub transform: Option<u16>,
422 /// How this clip's picture meets a project canvas of another shape
423 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
424 /// two above: it is one byte with no parameters, so there is nothing for a
425 /// table to share, and a clip that is the project's own size never consults
426 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
427 /// where the aspect does not agree.
428 pub fit: FitPolicy,
429 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
430 /// eq and colour indexes: it is two bytes with nothing to share, and a table
431 /// would put a level of indirection between the mapping and the one number
432 /// every frame of it is divided by.
433 ///
434 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
435 /// the clip plays, so a trim and a split still address the file. What it
436 /// changes is how many *timeline* frames that range is spread over
437 /// ([`Clip::frames`]).
438 pub speed: Speed,
439 /// Timeline frames of ramp-up from silence at the clip's own start, inline
440 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
441 /// number with nothing to share, and every consumer (mixer, exporter) wants
442 /// it sitting right next to the frame range it shapes. Clamped to the
443 /// clip's own length by the setter -- never wider than the clip is long.
444 pub fade_in: u32,
445 /// Timeline frames of ramp-down to silence at the clip's own end. Same
446 /// promises as [`Clip::fade_in`].
447 pub fade_out: u32,
448 /// Timeline frames of cross-dissolve into the clip immediately after this
449 /// one on the same video lane, at this clip's own end -- `0` for a hard
450 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
451 /// reason, and clamped the same way by its setter
452 /// ([`Project::set_transition_out`]): never wider than this clip's own
453 /// length, nor than the successor it dissolves into. Meaningless -- and
454 /// left as whatever it was -- the moment the next clip stops abutting
455 /// this one; a reader that cares checks adjacency itself rather than
456 /// trusting this field alone, exactly as a stored fade is trusted only
457 /// because a clip's own length is checked beside it.
458 pub transition_out: u32,
459}
460
461impl Clip {
462 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
463 /// reads out of its file -- not how long it is on the timeline, which is
464 /// [`Clip::frames`] and differs the moment it is speeded.
465 pub fn len(&self) -> u32 {
466 self.out_frame - self.in_frame
467 }
468
469 /// Timeline frames it occupies: its source range at its own speed, never
470 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
471 /// what it overlaps, how wide its box is -- is asked of this and not of
472 /// [`Clip::len`].
473 pub fn frames(&self) -> u32 {
474 self.speed.frames(self.len())
475 }
476
477 /// One past the last timeline frame it covers.
478 pub fn end(&self) -> u32 {
479 self.start + self.frames()
480 }
481}
482
483/// A file the timeline plays from, and *which* of its audio streams it plays:
484/// a file carrying one track per language is several sources, one per stream,
485/// sharing a path. Two entries differing only in the stream are two sources --
486/// they are what a clip names, and a clip plays exactly one stream.
487///
488/// The path is always canonical ([`Source::new`]), so the same file reached by
489/// two paths is one source.
490#[derive(Clone, Debug, PartialEq, Eq)]
491pub struct Source {
492 pub path: PathBuf,
493 /// Position among the file's audio tracks in file order, the numbering
494 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
495 /// single track, and for a silent one.
496 pub audio_stream: usize,
497}
498
499impl Source {
500 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
501 Self {
502 path: canonical(path.as_ref()),
503 audio_stream,
504 }
505 }
506}
507
508/// What a lane carries, which is what a *gap* in it means: black frames on a
509/// video lane, silence on an audio one, nothing over the picture on a subtitle
510/// one.
511#[derive(Clone, Copy, PartialEq, Eq, Debug)]
512pub enum LaneKind {
513 Video,
514 Audio,
515 /// Words over the picture, placed and trimmed like everything else
516 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
517 /// so a caption is dragged, cut, rippled and undone by the machinery every
518 /// other clip already goes through.
519 ///
520 /// It carries no [`Clip`] at all, and that is what keeps the media paths
521 /// free of it: [`Project::lane`] hands back an empty slice, so every
522 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
523 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
524 /// check it already had, [`Project::composite_span_at`] and
525 /// [`Project::audio_lanes`] never look at it, and the three doors that
526 /// could still put a picture on one -- [`Project::from_parts`],
527 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
528 Subtitle,
529}
530
531/// Which lane an operation acts on: a kind plus a 0-based position among the
532/// lanes of that kind, so [`Lane::V1`] is the first video lane and
533/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
534///
535/// A handle, not the lane itself. It stays meaningful while lanes are added,
536/// and one naming a lane that is not there reads as an empty lane and refuses
537/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
538/// bounds check of its own.
539#[derive(Clone, Copy, PartialEq, Eq, Debug)]
540pub struct Lane {
541 pub kind: LaneKind,
542 pub ord: usize,
543}
544
545impl Lane {
546 /// The first video lane: what a decoder plays and what an export renders.
547 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
548 /// The first audio lane: what the audio worker plays.
549 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
550 /// The first subtitle lane -- the one a project has only once something
551 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
552 /// alone.
553 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
554
555 pub const fn new(kind: LaneKind, ord: usize) -> Self {
556 Self { kind, ord }
557 }
558
559 /// `V1`, `A2`: how a lane is written in a header column and named in an
560 /// error about it.
561 pub fn label(self) -> String {
562 let kind = match self.kind {
563 LaneKind::Video => 'V',
564 LaneKind::Audio => 'A',
565 LaneKind::Subtitle => 'S',
566 };
567 format!("{kind}{}", self.ord + 1)
568 }
569}
570
571/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
572/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
573/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
574/// frames. Never empty at either end.
575///
576/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
577/// actually has, and placed by the same one number: the window is in the
578/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
579/// placement is in timeline frames like everything else on a lane. So the lane
580/// invariant is the lane's ([`subs_sorted_disjoint`] is
581/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
582/// else, and only the two calls that change a *duration* -- a trim, and the
583/// mapping out -- ever need the timeline's rate.
584///
585/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
586/// paste and an undo snapshot are a plain assignment and can never dangle.
587#[derive(Clone, Copy, PartialEq, Eq, Debug)]
588pub struct SubClip {
589 /// Timeline frame its first frame is shown at.
590 pub start: u32,
591 /// How many timeline frames it covers; `>= 1`. Held rather than derived
592 /// from the window because a [`Project`] has no frame rate -- the rate
593 /// enters at the door of the two calls that need it -- and every placement
594 /// question (where it ends, what it overlaps) is asked in frames.
595 pub frames: u32,
596 /// Index into [`Project::subtitles`]: *which* track's words these are.
597 pub track: usize,
598 /// The half-open window of that track it shows, in microseconds from the
599 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
600 /// timed in, so no conversion stands between a cue and the window that
601 /// keeps it.
602 pub in_us: i64,
603 pub out_us: i64,
604 /// Group id: `Some` exactly when a hand put this caption in a group with
605 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
606 /// no group, and what a cut cuts apart loses the one it had
607 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
608 /// clip is what makes the caption move, trim and delete with it.
609 pub link: Option<u32>,
610}
611
612impl SubClip {
613 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
614 /// what every overlap question is asked of.
615 pub fn end(&self) -> u32 {
616 self.start + self.frames
617 }
618
619 /// How much of its track it shows, in microseconds; `>= 1` by the
620 /// never-empty invariant.
621 pub fn window_us(&self) -> i64 {
622 self.out_us - self.in_us
623 }
624
625 /// Where in its window the timeline frame `frame` falls, in microseconds --
626 /// the cut a split, a ripple and a trim all land on.
627 ///
628 /// By proportion and not by the timeline's rate: the window and the frame
629 /// count measure the same stretch of time, so the fraction of the frames
630 /// before `frame` is the fraction of the microseconds before it. That is
631 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
632 /// without either of them learning an fps.
633 fn window_at(&self, frame: u32) -> i64 {
634 let into = i64::from(frame.saturating_sub(self.start));
635 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
636 }
637}
638
639/// One lane: what it is and what it holds. A struct rather than a bare
640/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
641/// compositing mode, a name -- and it belongs next to the clips it applies to.
642#[derive(Clone, Debug)]
643struct LaneData {
644 kind: LaneKind,
645 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
646 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
647 /// ever seeing a subtitle: they all read this list.
648 clips: Vec<Clip>,
649 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
650 /// empty on a video or audio one. Beside the clips rather than an enum over
651 /// them so that everything a lane *is* -- its place in the stack, its
652 /// label, its undo snapshot, its removal -- stays one code path for all
653 /// three kinds.
654 subs: Vec<SubClip>,
655 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
656 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
657 /// makes it a different thing from a clip's equalizer: it moves everything
658 /// on the track by the same amount, cuts included. Meaningless on a video
659 /// lane, where it is kept at 0 and asked by nothing.
660 gain_db: f32,
661}
662
663impl LaneData {
664 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
665 Self {
666 kind,
667 clips,
668 subs: Vec::new(),
669 gain_db: 0.0,
670 }
671 }
672
673 /// The two lanes a project starts with: `V1` then `A1`, in display order.
674 /// One place, because a freshly opened file is exactly this pair.
675 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
676 vec![
677 LaneData::new(LaneKind::Video, video),
678 LaneData::new(LaneKind::Audio, audio),
679 ]
680 }
681}
682
683/// The placements one group id names, split by the two lists a lane holds:
684/// what a drag, a trim and a delete each have to walk, now that a group may
685/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
686/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
687/// -- so the pairs are `(lane storage index, index into that lane's list)`.
688#[derive(Default)]
689struct Members {
690 clips: Vec<(usize, usize)>,
691 subs: Vec<(usize, usize)>,
692}
693
694impl Members {
695 /// Whether the group is the one placement and no more: what a lift leaves
696 /// behind, and what every whole-group question answers "not one" for.
697 fn alone(&self) -> bool {
698 self.clips.len() + self.subs.len() < 2
699 }
700}
701
702/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
703#[derive(Clone, Copy, PartialEq, Eq, Debug)]
704pub enum Edge {
705 /// Its first timeline frame; moving it changes where in the source the clip
706 /// starts reading, so the picture behind the edge slides with it.
707 Start,
708 /// One past its last timeline frame; moving it only says how much of the
709 /// source to keep.
710 End,
711}
712
713/// What a lane holds over one stretch of the timeline: either a placed clip or
714/// a gap. Returned already trimmed to the position it was asked about, so a
715/// caller can hand `len` straight to a decoder (or to a black-frame generator).
716#[derive(Clone, Copy, PartialEq, Eq, Debug)]
717pub struct Span {
718 /// Timeline frame the span starts at.
719 pub start: u32,
720 /// Frames it covers; `>= 1`.
721 pub len: u32,
722 /// `(source index, first source frame)`, or `None` for a gap -- which the
723 /// engine renders as black frames and as silence.
724 pub from: Option<(usize, u32)>,
725 /// The rate the clip this came off plays at ([`Clip::speed`]);
726 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
727 /// timeline frames whatever it says -- the speed is how many *source* frames
728 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
729 /// come back to the timeline.
730 pub speed: Speed,
731}
732
733impl Span {
734 /// One past the last timeline frame it covers.
735 pub fn end(&self) -> u32 {
736 self.start + self.len
737 }
738
739 /// How many source frames it reads: what a decoder is asked for and how wide
740 /// an audio window is. `len` at real time, and the one arithmetic both the
741 /// picture and the sound go through, so they cannot disagree about where a
742 /// speeded clip ends.
743 pub fn source_len(&self) -> u32 {
744 match self.from {
745 // The last timeline frame's own source frame is the last one needed
746 // -- never one more, which at a slow rate would read a frame the
747 // next clip owns and at a fast one would decode a picture nothing
748 // shows.
749 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
750 None => self.len,
751 }
752 }
753
754 /// Where a source frame of this span lands on the timeline: the stamp
755 /// playback puts on a decoded frame, through the ceil half of the pair
756 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
757 /// frame, so a frame before it stamps at the span's start.
758 pub fn timeline_at(&self, source_frame: u32) -> u32 {
759 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
760 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
761 }
762}
763
764/// What one speeded audio segment asks of the worker: how many source frames to
765/// consume per output frame, and how many seconds of timeline it has to fill.
766/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
767/// resampling at all.
768#[derive(Clone, Copy, PartialEq, Debug)]
769pub struct Stretch {
770 /// Source frames per output frame -- the speed as a multiplier.
771 pub step: f64,
772 /// What the segment owes the timeline, which is what it is padded or
773 /// trimmed to.
774 pub timeline_secs: f64,
775}
776
777/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
778/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
779/// against where in the *clip* -- not the segment, which may start mid-clip
780/// on a seek -- this segment's first frame lands.
781#[derive(Clone, Copy, PartialEq, Eq, Debug)]
782pub struct Fade {
783 /// How many of the clip's own frames already played before this
784 /// segment's first frame: `0` unless playback started mid-clip.
785 pub elapsed: u32,
786 /// The clip's [`Clip::fade_in`].
787 pub fade_in: u32,
788 /// The clip's [`Clip::fade_out`].
789 pub fade_out: u32,
790 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
791 /// which this segment may only cover the tail.
792 pub total: u32,
793}
794
795impl Fade {
796 /// The gain at clip-relative frame `pos`, an equal-power curve on each
797 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
798 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
799 /// ramp, so a fade lands on silence at its very first (or very last)
800 /// frame and reaches unity smoothly rather than at a constant slope --
801 /// the same curve [`Project::crossfade`] relies on to keep two clips'
802 /// sum around one level through the join. Both ramps multiply where a
803 /// clip is short enough for them to overlap.
804 fn gain_at(self, pos: u32) -> f32 {
805 let mut g = 1.0f32;
806 if self.fade_in > 0 && pos < self.fade_in {
807 let t = pos as f32 / self.fade_in as f32;
808 g *= (t * std::f32::consts::FRAC_PI_2).sin();
809 }
810 if self.fade_out > 0 {
811 let out_start = self.total.saturating_sub(self.fade_out);
812 if pos >= out_start {
813 let remaining = self.total.saturating_sub(pos);
814 let t = remaining as f32 / self.fade_out as f32;
815 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
816 }
817 }
818 g
819 }
820
821 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
822 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
823 pub fn apply(self, frames: &mut [f32], channels: usize) {
824 for (i, block) in frames.chunks_mut(channels).enumerate() {
825 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
826 for s in block {
827 *s *= g;
828 }
829 }
830 }
831
832 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
833 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
834 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
835 /// position is in) but [`Self::apply`] multiplies *audio* frames --
836 /// `channels`-wide sample blocks at whatever rate the mix is running at,
837 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
838 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
839 /// few milliseconds into any clip, so a fade-out silenced the rest of the
840 /// clip outright and a fade-in finished before a listener's ear caught up
841 /// -- audible on nothing shorter than a clip a few fps-frames long, which
842 /// is why 338 green tests never once ran the two curves out of step.
843 /// `ratio` is `sample_rate / fps`, applied once where the audio session
844 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
845 pub fn scaled(self, ratio: f64) -> Fade {
846 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
847 Fade {
848 elapsed: conv(self.elapsed),
849 fade_in: conv(self.fade_in),
850 fade_out: conv(self.fade_out),
851 total: conv(self.total),
852 }
853 }
854}
855
856/// What a save writes and a load takes back: the sources, every lane in
857/// display order with its kind, and the equalizer and colour tables their clips
858/// index into -- [`Project::without_orphan_sources`] out,
859/// [`Project::from_parts`] in.
860pub type Parts = (
861 Vec<Source>,
862 Vec<(LaneKind, Vec<Clip>)>,
863 Vec<EqParams>,
864 Vec<ColorParams>,
865 Vec<TransformParams>,
866);
867
868/// How many undo steps a project keeps. One gesture is one step, so 100 is past
869/// any chain a person walks back by hand, and the oldest step is dropped rather
870/// than the history growing without end: a snapshot is the whole lane list, so
871/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
872/// that grows for as long as the session lasts.
873const HISTORY_CAP: usize = 100;
874
875/// One gap a close-all sweep left open, with the frame it still starts on and
876/// the same refusal a single [`Project::gap_take_scope`] close would have said.
877#[derive(Clone, Debug, PartialEq, Eq)]
878pub struct GapSkip {
879 pub start: u32,
880 pub reason: String,
881}
882
883/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
884/// skipped gaps are the take-safety refusals the sweep did not hide.
885#[derive(Clone, Debug, Default, PartialEq, Eq)]
886pub struct GapSweep {
887 pub closed: usize,
888 pub skipped: Vec<GapSkip>,
889}
890
891/// The edit list plus its undo history.
892#[derive(Clone, Debug)]
893pub struct Project {
894 /// Append-only: never popped, never reordered. See the module docs.
895 sources: Vec<Source>,
896 /// In display order, which is the order [`Lane::ord`] counts in: the nth
897 /// lane of a kind here is that kind's `ord` n. Never empty.
898 lanes: Vec<LaneData>,
899 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
900 eq: Vec<EqParams>,
901 /// The same, for [`Clip::color`].
902 color: Vec<ColorParams>,
903 /// The same, for [`Clip::transform`].
904 transform: Vec<TransformParams>,
905 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
906 /// whole lane list, so adding a lane undoes as well. Bounded by
907 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
908 history: Vec<Vec<LaneData>>,
909 /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by
910 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
911 /// the undone steps came from. Not saved to `.edith`, matching `history`.
912 redo: Vec<Vec<LaneData>>,
913 /// Never rolled back by an undo: an id retired by an undone split must not
914 /// come back and group two clips that were never together.
915 next_link: u32,
916 /// The subtitle tracks this timeline shows, in the order they were added.
917 /// Not in the lane list and not in the history snapshots, for the reason
918 /// the limiter is not: which subtitles a project carries is a setting on
919 /// it, and it is saved as a *reference* to the file the cues came out of
920 /// ([`crate::subtitle`]).
921 subtitles: Vec<SubtitleTrack>,
922 /// The master limiter every lane's sound is summed *through*
923 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
924 /// is what the history snapshots hold: it is a setting on the mix, like the
925 /// project's resolution is a setting on the picture, and neither is an undo
926 /// step.
927 limiter: Limiter,
928 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
929 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
930 /// the resolution, and not in the lane snapshots for the same reason.
931 tone: crate::tonemap::Preset,
932}
933
934impl Project {
935 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
936 /// grouped -- the state of a freshly opened video, where the timeline is the
937 /// source. `frame_count` of 0 would break the never-empty invariant, so it
938 /// is clamped to one frame.
939 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
940 let clip = Clip {
941 fade_in: 0,
942 fade_out: 0,
943 transition_out: 0,
944 start: 0,
945 in_frame: 0,
946 out_frame: frame_count.max(1),
947 source: 0,
948 link: Some(0),
949 eq: None,
950 color: None,
951 transform: None,
952 fit: FitPolicy::default(),
953 speed: Speed::NORMAL,
954 };
955 Self {
956 // A file is opened on its first audio stream: nothing has picked
957 // one yet, and every file with audio at all has that one.
958 sources: vec![Source::new(path, 0)],
959 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
960 eq: Vec::new(),
961 color: Vec::new(),
962 transform: Vec::new(),
963 history: Vec::new(),
964 redo: Vec::new(),
965 next_link: 1,
966 subtitles: Vec::new(),
967 limiter: Limiter::default(),
968 tone: crate::tonemap::Preset::default(),
969 }
970 }
971
972 /// A project rebuilt from a saved edit list -- the load half of
973 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
974 /// an `ord` is a lane's position among the lanes of that kind, exactly as
975 /// [`Project::lanes`] hands them back. History is *not* saved, so
976 /// [`Project::undo`] is `false` until the first edit of the new session.
977 /// This is the one door untrusted parts come in through, so every invariant
978 /// every other constructor keeps is checked here, by name and in release:
979 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
980 /// or a colour) that is not there, a clip whose end overflows, a lane that is
981 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
982 /// below.
983 ///
984 /// A project whose lanes are all *empty* is not among them: an emptied
985 /// timeline is a project like any other -- it plays black and silent, it
986 /// saves, and it loads back. What a project cannot be is laneless, because
987 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
988 /// handle indexes into.
989 pub fn from_parts(
990 sources: Vec<Source>,
991 lanes: Vec<(LaneKind, Vec<Clip>)>,
992 eq: Vec<EqParams>,
993 color: Vec<ColorParams>,
994 transform: Vec<TransformParams>,
995 ) -> crate::Result<Self> {
996 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
997 return Err(format!("eq {bad} holds a band that is not a finite number").into());
998 }
999 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
1000 return Err(format!("color {bad} holds a value that is not a finite number").into());
1001 }
1002 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
1003 return Err(format!("transform {bad} holds a value that is not a finite number").into());
1004 }
1005 if lanes.is_empty() {
1006 return Err("no lanes at all: that is not a project".into());
1007 }
1008 let lanes: Vec<LaneData> = lanes
1009 .into_iter()
1010 .map(|(kind, clips)| LaneData::new(kind, clips))
1011 .collect();
1012 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
1013 let name = lane.label();
1014 // A subtitle lane carries words and never a picture
1015 // ([`LaneKind::Subtitle`]); a file that puts one there names a
1016 // source on a lane that has nothing to play it with, and every
1017 // media path below would then read a clip off a lane it does not
1018 // know about.
1019 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
1020 return Err(format!(
1021 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
1022 data.clips.len()
1023 )
1024 .into());
1025 }
1026 for c in &data.clips {
1027 if c.out_frame <= c.in_frame {
1028 return Err(format!(
1029 "{name} clip at {} plays the empty range [{}, {})",
1030 c.start, c.in_frame, c.out_frame
1031 )
1032 .into());
1033 }
1034 if c.source >= sources.len() {
1035 return Err(format!(
1036 "{name} clip at {} names source {} of {}",
1037 c.start,
1038 c.source,
1039 sources.len()
1040 )
1041 .into());
1042 }
1043 if c.start.checked_add(c.frames()).is_none() {
1044 return Err(format!(
1045 "{name} clip at {} runs past the last frame there is",
1046 c.start
1047 )
1048 .into());
1049 }
1050 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1051 return Err(format!(
1052 "{name} clip at {} names eq {} of {}",
1053 c.start,
1054 c.eq.unwrap_or_default(),
1055 eq.len()
1056 )
1057 .into());
1058 }
1059 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1060 return Err(format!(
1061 "{name} clip at {} names color {} of {}",
1062 c.start,
1063 c.color.unwrap_or_default(),
1064 color.len()
1065 )
1066 .into());
1067 }
1068 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
1069 return Err(format!(
1070 "{name} clip at {} names transform {} of {}",
1071 c.start,
1072 c.transform.unwrap_or_default(),
1073 transform.len()
1074 )
1075 .into());
1076 }
1077 }
1078 if !sorted_disjoint(&data.clips) {
1079 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1080 }
1081 }
1082 links_are_consistent(&lanes)?;
1083 // The counter sits past every id the file names, on either of a lane's
1084 // lists: a v16 caption may carry the highest link there is, and a
1085 // re-issued id would silently group it with the next placement that
1086 // asks for one -- the loader refusing a save the editor just wrote.
1087 let next_link = lanes
1088 .iter()
1089 .flat_map(|l| {
1090 let clips = l.clips.iter().filter_map(|c| c.link);
1091 let subs = l.subs.iter().filter_map(|s| s.link);
1092 clips.chain(subs)
1093 })
1094 .max()
1095 // Saturating so a crafted file cannot make the counter wrap: at the
1096 // ceiling ids stop being fresh, which loses grouping, not memory.
1097 .map_or(0, |m| m.saturating_add(1));
1098 Ok(Self {
1099 sources: sources
1100 .iter()
1101 .map(|s| Source::new(&s.path, s.audio_stream))
1102 .collect(),
1103 lanes,
1104 eq,
1105 color,
1106 transform,
1107 history: Vec::new(),
1108 redo: Vec::new(),
1109 next_link,
1110 subtitles: Vec::new(),
1111 limiter: Limiter::default(),
1112 tone: crate::tonemap::Preset::default(),
1113 })
1114 }
1115
1116 /// The first video lane -- what an export renders and what a single-lane
1117 /// caller still means by "the clips".
1118 pub fn clips(&self) -> &[Clip] {
1119 self.lane(Lane::V1)
1120 }
1121
1122 /// The clips of `lane`, or nothing at all for a lane that is not there.
1123 pub fn lane(&self, lane: Lane) -> &[Clip] {
1124 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1125 }
1126
1127 /// Every lane's handle, in display order -- what a walk over "all lanes"
1128 /// iterates, and what a front-end lays out top to bottom.
1129 pub fn lanes(&self) -> Vec<Lane> {
1130 handles(&self.lanes)
1131 }
1132
1133 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1134 /// for every `ord` below it, and none at or above it.
1135 pub fn lane_count(&self, kind: LaneKind) -> usize {
1136 self.lanes.iter().filter(|l| l.kind == kind).count()
1137 }
1138
1139 /// Appends an empty lane of `kind` and hands back its handle. One undo
1140 /// step, because the lane list is state a front-end shows: an added lane
1141 /// that could not be taken back would be the one edit with no way out.
1142 /// Nothing plays differently until something is placed on it.
1143 ///
1144 /// An empty lane is a lane like any other -- so is a whole project of them
1145 /// ([`Project::from_parts`]); nothing plays until something is placed.
1146 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1147 self.snapshot();
1148 self.lanes.push(LaneData::new(kind, Vec::new()));
1149 Lane::new(kind, self.lane_count(kind) - 1)
1150 }
1151
1152 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1153 /// one undo step like it, which restores the lane where it stood.
1154 ///
1155 /// Refused, changing nothing, while the lane holds anything: the refusal
1156 /// names the clips (file and first frame), because a track removal that
1157 /// deleted takes with it would be the one edit nobody sees coming. Refused
1158 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1159 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1160 /// kind and *skips* a kind that is not there), so a project without one
1161 /// would swallow half of every file dropped on it, silently.
1162 ///
1163 /// The lanes below it move up one `ord`, so a handle a caller was holding
1164 /// (a selection, an open card) names the lane after it from here on -- the
1165 /// one thing a front-end owes this call.
1166 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1167 let Some(i) = self.index(lane) else {
1168 return Err(format!("there is no {} to remove", lane.label()).into());
1169 };
1170 // A subtitle lane is not in that rule: nothing lands on one by itself
1171 // -- a project starts without any and one is added when a caption is --
1172 // so the last of them comes off like any other empty track.
1173 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1174 return Err(format!(
1175 "{} is the only {} track: every import lands on it",
1176 lane.label(),
1177 match lane.kind {
1178 LaneKind::Video => "video",
1179 LaneKind::Audio => "audio",
1180 // Unreachable while the guard above lets the last subtitle
1181 // lane go, and its own word here so the sentence stays true
1182 // if that rule is ever relaxed.
1183 LaneKind::Subtitle => "subtitle",
1184 }
1185 )
1186 .into());
1187 }
1188 if !self.lanes[i].subs.is_empty() {
1189 // Three names and a count, exactly as the clips below get: the way
1190 // out of the refusal is the drag, so the words say so.
1191 let named: Vec<String> = self.lanes[i]
1192 .subs
1193 .iter()
1194 .take(3)
1195 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1196 .collect();
1197 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1198 0 => String::new(),
1199 n => format!(" and {n} more"),
1200 };
1201 return Err(format!(
1202 "{} still holds {}{rest}: delete those captions (or drag them to \
1203 another track) first",
1204 lane.label(),
1205 named.join(", ")
1206 )
1207 .into());
1208 }
1209 let clips = &self.lanes[i].clips;
1210 if !clips.is_empty() {
1211 // Three names and a count: a lane can hold forty clips and a
1212 // refusal nobody reads to the end says nothing at all.
1213 let named: Vec<String> = clips
1214 .iter()
1215 .take(3)
1216 .map(|c| {
1217 let name = self.sources.get(c.source).map_or_else(
1218 || format!("source {}", c.source),
1219 |s| s.path.display().to_string(),
1220 );
1221 format!("{name} at frame {}", c.start)
1222 })
1223 .collect();
1224 let rest = match clips.len().saturating_sub(named.len()) {
1225 0 => String::new(),
1226 n => format!(" and {n} more"),
1227 };
1228 return Err(format!(
1229 "{} still holds {}{rest}: delete those clips (or drag them to \
1230 another track) first",
1231 lane.label(),
1232 named.join(", ")
1233 )
1234 .into());
1235 }
1236 self.snapshot();
1237 self.lanes.remove(i);
1238 Ok(())
1239 }
1240
1241 /// Moves `lane` to display position `to` -- an index into
1242 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1243 /// the handle it answers to from now on. `None`, changing nothing and
1244 /// snapshotting nothing, for a lane that is not there, a position that is
1245 /// not, and a lane already standing in it.
1246 ///
1247 /// The whole track travels: its clips, its gain, its kind. Nothing is
1248 /// remapped, so no take changes lane and no group is broken -- this is the
1249 /// *order* of the lanes and nothing else, which is why one call is one undo
1250 /// step like an add or a removal.
1251 ///
1252 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1253 /// last video lane covering a frame, so moving one video lane past another
1254 /// changes which picture wins, in the preview and in an export alike. The
1255 /// audio lanes are summed and their sum does not care about order, so an
1256 /// audio track moved among the video ones is a rearrangement of the screen
1257 /// alone.
1258 ///
1259 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1260 /// position among the lanes of that kind), so a lane that crosses one of
1261 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1262 /// `V1`, clips and all -- while one that crosses only lanes of the other
1263 /// kind keeps its name. That is the returned handle: unchanged means every
1264 /// handle a caller holds still names the track it named before.
1265 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1266 let i = self.index(lane)?;
1267 if to >= self.lanes.len() || to == i {
1268 return None;
1269 }
1270 self.snapshot();
1271 let data = self.lanes.remove(i);
1272 self.lanes.insert(to, data);
1273 Some(handles(&self.lanes)[to])
1274 }
1275
1276 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1277 /// not there. The one place a handle becomes a position.
1278 fn index(&self, lane: Lane) -> Option<usize> {
1279 self.lanes
1280 .iter()
1281 .enumerate()
1282 .filter(|(_, l)| l.kind == lane.kind)
1283 .map(|(i, _)| i)
1284 .nth(lane.ord)
1285 }
1286
1287 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1288 let i = self.index(lane)?;
1289 Some(&mut self.lanes[i].clips)
1290 }
1291
1292 /// The files the clips index into, in import order; index 0 is the file the
1293 /// project was opened with.
1294 pub fn sources(&self) -> &[Source] {
1295 &self.sources
1296 }
1297
1298 /// The same list in the `(path, stream)` shape the audio engine indexes
1299 /// into -- [`crate::AudioSession::open_multi_streams`] and
1300 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1301 /// was placed with is the stream that plays *and* the stream that exports.
1302 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1303 self.sources
1304 .iter()
1305 .map(|s| (s.path.clone(), s.audio_stream))
1306 .collect()
1307 }
1308
1309 /// Index for `path` played on `audio_stream`, appending it if it is new.
1310 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1311 /// by two paths imports once and two streams of one file are two sources.
1312 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1313 /// no history: a source entry alone changes nothing playable.
1314 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1315 let source = Source::new(path, audio_stream);
1316 match self.sources.iter().position(|s| *s == source) {
1317 Some(idx) => idx,
1318 None => {
1319 self.sources.push(source);
1320 self.sources.len() - 1
1321 }
1322 }
1323 }
1324
1325 /// Append a whole-file clip of `source` to the end of every *media* lane,
1326 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1327 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1328 /// come in through [`Project::add_subtitles`], which is the palette.
1329 ///
1330 /// One history snapshot, so an import is one undo step, and undoing it
1331 /// leaves the (harmless) source entry behind, because indexes are forever.
1332 /// Refused for an unknown source index.
1333 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1334 if source >= self.sources.len() {
1335 return false;
1336 }
1337 self.snapshot();
1338 let start = self.timeline_frames();
1339 let clip = Clip {
1340 fade_in: 0,
1341 fade_out: 0,
1342 transition_out: 0,
1343 start,
1344 in_frame: 0,
1345 out_frame: frame_count.max(1),
1346 source,
1347 link: Some(self.new_link()),
1348 eq: None,
1349 color: None,
1350 transform: None,
1351 fit: FitPolicy::default(),
1352 speed: Speed::NORMAL,
1353 };
1354 for data in self
1355 .lanes
1356 .iter_mut()
1357 .filter(|l| l.kind != LaneKind::Subtitle)
1358 {
1359 data.clips.push(clip);
1360 }
1361 true
1362 }
1363
1364 /// Drops a source entry -- the file a library row *is* -- and renumbers
1365 /// every clip that indexed past it, which is why this is more than a
1366 /// `Vec::remove`.
1367 ///
1368 /// Refused, changing nothing, while any clip still plays from it: the
1369 /// refusal names the lanes and how many clips each holds, so a caller can
1370 /// say what has to be deleted first. The *last* entry goes like any other
1371 /// -- a project may name no file at all, which is an empty library over an
1372 /// empty timeline (nothing can play, since a clip would have refused the
1373 /// removal). What a front-end does with that is its own decision: `edith`'s
1374 /// window goes back to the empty state it launches in, and
1375 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1376 /// refuses to write a project that names nothing, because no such file
1377 /// could be opened again.
1378 ///
1379 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1380 /// source index of its own -- a clipboard, which is the one thing outside
1381 /// this type that does -- has to fix it up or drop it, or a paste plays a
1382 /// different file. [`PlaybackSession::remove_source`] hands back the index
1383 /// that went for exactly that.
1384 ///
1385 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1386 /// snapshot older than the removal can name the very source being removed
1387 /// (delete a file's clips, then remove the file) and restoring it would
1388 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1389 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1390 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1391 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1392 /// exists) currently rules out.
1393 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1394 let Some(source) = self.sources.get(idx) else {
1395 return Err(format!("there is no source {idx} to remove").into());
1396 };
1397 let name = source.path.display().to_string();
1398 let used: Vec<String> = handles(&self.lanes)
1399 .into_iter()
1400 .zip(&self.lanes)
1401 .filter_map(
1402 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1403 0 => None,
1404 1 => Some(format!("{} (1 clip)", lane.label())),
1405 n => Some(format!("{} ({n} clips)", lane.label())),
1406 },
1407 )
1408 .collect();
1409 if !used.is_empty() {
1410 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1411 }
1412 self.sources.remove(idx);
1413 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1414 if c.source > idx {
1415 c.source -= 1;
1416 }
1417 }
1418 self.history.clear();
1419 Ok(())
1420 }
1421
1422 /// The sources a clip actually names, with the clips reindexed onto them
1423 /// -- what a save writes. Indexes are forever *inside* a session (see
1424 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1425 /// entry behind; writing that orphan to a project file would let a file
1426 /// nothing plays refuse a future load. New indexes are assigned in order of
1427 /// first use -- lane by lane, in display order -- so the same project always
1428 /// emits the same bytes.
1429 ///
1430 /// Every lane comes out, in display order and with its kind: that is what a
1431 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1432 /// takes back.
1433 ///
1434 /// The equalizer and colour tables are pruned the same way and for the same
1435 /// reason: an undone [`set_eq`](Project::set_eq) or
1436 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1437 /// and this is the one moment they can go -- the indexes that survive it are
1438 /// only the ones a clip names.
1439 ///
1440 /// One exception, and it is the emptied timeline's: a project no clip plays
1441 /// from still keeps its first source, if it has one. A file is what a
1442 /// reopened project scaffolds itself from -- the frame rate is written
1443 /// nowhere else -- so a save that pruned the last of them would write a
1444 /// project that cannot be loaded back at all.
1445 ///
1446 /// What comes out is *not* ordered by anything a reader may assume: first
1447 /// use, lane by lane, means the entry at index 0 can be a still or a song
1448 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1449 /// picks its rate and its audio reference by what a source *is*, never by
1450 /// where it sits.
1451 pub fn without_orphan_sources(&self) -> Parts {
1452 let mut moved = vec![None; self.sources.len()];
1453 let mut sources = Vec::new();
1454 let mut moved_eq = vec![None; self.eq.len()];
1455 let mut eq = Vec::new();
1456 let mut moved_color = vec![None; self.color.len()];
1457 let mut color = Vec::new();
1458 let mut moved_transform = vec![None; self.transform.len()];
1459 let mut transform = Vec::new();
1460 let mut lanes = self.lanes.clone();
1461 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1462 let old = c.source;
1463 c.source = match moved[old] {
1464 Some(new) => new,
1465 None => {
1466 sources.push(self.sources[old].clone());
1467 moved[old] = Some(sources.len() - 1);
1468 sources.len() - 1
1469 }
1470 };
1471 if let Some(old) = c.eq.map(usize::from) {
1472 c.eq = Some(match moved_eq[old] {
1473 Some(new) => new,
1474 None => {
1475 eq.push(self.eq[old].clone());
1476 let new = (eq.len() - 1) as u16;
1477 moved_eq[old] = Some(new);
1478 new
1479 }
1480 });
1481 }
1482 if let Some(old) = c.color.map(usize::from) {
1483 c.color = Some(match moved_color[old] {
1484 Some(new) => new,
1485 None => {
1486 color.push(self.color[old]);
1487 let new = (color.len() - 1) as u16;
1488 moved_color[old] = Some(new);
1489 new
1490 }
1491 });
1492 }
1493 if let Some(old) = c.transform.map(usize::from) {
1494 c.transform = Some(match moved_transform[old] {
1495 Some(new) => new,
1496 None => {
1497 transform.push(self.transform[old]);
1498 let new = (transform.len() - 1) as u16;
1499 moved_transform[old] = Some(new);
1500 new
1501 }
1502 });
1503 }
1504 }
1505 if sources.is_empty() {
1506 sources.extend(self.sources.first().cloned());
1507 }
1508 (
1509 sources,
1510 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1511 // comes out for one is an empty list, and its *place* in the display
1512 // order is what a save writes it for. What is on it travels beside
1513 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1514 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1515 eq,
1516 color,
1517 transform,
1518 )
1519 }
1520
1521 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1522 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1523 /// track moves by it, which is what makes it a different control from a
1524 /// clip's equalizer (one frequency range of one take) and from the master
1525 /// volume (what this machine monitors at, which no file carries).
1526 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1527 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1528 }
1529
1530 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1531 /// One undo step like every other edit -- it is in the lane list, so an
1532 /// undo restores it with the rest. `false`, and no history, for a lane that
1533 /// is not there, for a value that is not finite, and for one already set.
1534 ///
1535 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1536 /// a value nobody reads: words have no loudness, so a slider that appeared
1537 /// to move one would be a control with no effect. (A video lane's gain is
1538 /// meaningless in the same way but is kept settable: it is the pair `A1`
1539 /// carries for a take, and mixing reads it off the audio lane alone.)
1540 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1541 let Some(i) = self.index(lane) else {
1542 return false;
1543 };
1544 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1545 return false;
1546 }
1547 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1548 if self.lanes[i].gain_db == db {
1549 return false;
1550 }
1551 self.snapshot();
1552 self.lanes[i].gain_db = db;
1553 true
1554 }
1555
1556 /// Every lane's volume in dB, in display order -- what a save writes,
1557 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1558 ///
1559 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1560 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1561 /// one): a save zips the two lists, so a lane that is in one and not the
1562 /// other would hand every track below it the volume of the track above.
1563 pub fn lane_gains(&self) -> Vec<f32> {
1564 self.lanes.iter().map(|l| l.gain_db).collect()
1565 }
1566
1567 /// What is placed on every lane, in display order and in step with
1568 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1569 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1570 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1571 ///
1572 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1573 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1574 /// clip's source there is no orphan to prune and no index to move.
1575 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1576 self.lanes.iter().map(|l| l.subs.clone()).collect()
1577 }
1578
1579 /// The placements a *load* puts back, one list per lane in display order --
1580 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1581 /// same reason. Called *after*
1582 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1583 /// names.
1584 ///
1585 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1586 /// like it, by name and in release, because it is the same untrusted file:
1587 /// a placement on a lane that is not a subtitle lane, an empty span or an
1588 /// empty window, a track the palette does not have, a span running past the
1589 /// last frame there is, and a lane that is out of order or overlaps itself
1590 /// ([`place_sub`] refuses every one of those on the live timeline).
1591 ///
1592 /// [`place_sub`]: Project::place_sub
1593 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1594 let names = handles(&self.lanes);
1595 let palette = self.subtitles.len();
1596 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1597 let name = lane.label();
1598 if list.is_empty() {
1599 continue;
1600 }
1601 if data.kind != LaneKind::Subtitle {
1602 return Err(format!(
1603 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1604 subtitle track",
1605 list.len()
1606 )
1607 .into());
1608 }
1609 for s in &list {
1610 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1611 return Err(format!(
1612 "{name} caption at {} is empty: {} frames of [{}, {})",
1613 s.start, s.frames, s.in_us, s.out_us
1614 )
1615 .into());
1616 }
1617 if s.track >= palette {
1618 return Err(format!(
1619 "{name} caption at {} names subtitle track {} of {palette}",
1620 s.start, s.track
1621 )
1622 .into());
1623 }
1624 if s.start.checked_add(s.frames).is_none() {
1625 return Err(format!(
1626 "{name} caption at {} runs past the last frame there is",
1627 s.start
1628 )
1629 .into());
1630 }
1631 }
1632 if !subs_sorted_disjoint(&list) {
1633 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1634 }
1635 data.subs = list;
1636 // The counter also has to clear the ids these captions carry: this
1637 // is the door a load's placements come through, *after*
1638 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1639 // a hand-grouped caption may carry the highest id in the file.
1640 self.next_link = self.next_link.max(
1641 data.subs
1642 .iter()
1643 .filter_map(|s| s.link)
1644 .max()
1645 .map_or(0, |m| m.saturating_add(1)),
1646 );
1647 }
1648 Ok(self)
1649 }
1650
1651 /// The mix settings a *load* puts back: lane volumes in display order (a
1652 /// short list leaves the rest at unity) and the master limiter, both
1653 /// clamped as their setters clamp them.
1654 ///
1655 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1656 /// setters push an undo step, and a project that arrives one undo away from
1657 /// a state it was never in is a project whose first ctrl+z is a surprise.
1658 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1659 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1660 if db.is_finite() {
1661 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1662 }
1663 }
1664 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1665 self
1666 }
1667
1668 /// The HDR rendition a *load* puts back -- the same door
1669 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1670 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1671 self.tone = preset;
1672 self
1673 }
1674
1675 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1676 /// project setting, not a clip's: one picture, one look
1677 /// ([`crate::tonemap::Preset`]).
1678 pub fn tone(&self) -> crate::tonemap::Preset {
1679 self.tone
1680 }
1681
1682 /// Sets it. `false` for the one already in force, which is what keeps a
1683 /// re-pick of the current rendition from costing a reseek.
1684 ///
1685 /// corner-cut: not an undo step, for the reason the limiter and the project
1686 /// resolution are not -- it is not in the lane list the history snapshots.
1687 /// Upgrade path is the same one: a history entry holding the project's own
1688 /// settings beside the lanes.
1689 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1690 if self.tone == preset {
1691 return false;
1692 }
1693 self.tone = preset;
1694 true
1695 }
1696
1697 /// The subtitle tracks a *load* puts back, in the order they were saved --
1698 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1699 /// the same reason.
1700 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1701 self.subtitles = tracks;
1702 self
1703 }
1704
1705 /// What this timeline shows over the picture, in the order they were added:
1706 /// what a front-end lists and what a save writes.
1707 pub fn subtitles(&self) -> &[SubtitleTrack] {
1708 &self.subtitles
1709 }
1710
1711 /// Adds a track, unless the very same one -- same file, same track number
1712 /// inside it -- is already on the list. `false` for that repeat: importing
1713 /// the same `.srt` twice is one subtitle track, not two identical ones.
1714 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1715 if self
1716 .subtitles
1717 .iter()
1718 .any(|t| t.path == track.path && t.track == track.track)
1719 {
1720 return false;
1721 }
1722 self.subtitles.push(track.clone());
1723 true
1724 }
1725
1726 /// Takes the track at `idx` off the list -- what a row's own remove goes
1727 /// through, so whatever an import added can be taken back out. Refused by
1728 /// name for a row this project does not have, rather than a silent no-op:
1729 /// a front-end holding a stale index has picked the wrong row and needs to
1730 /// hear it.
1731 ///
1732 /// Every index past `idx` moves down by one, as [`remove_source`](
1733 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1734 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1735 /// it, or it names a different track afterwards. The placements on the
1736 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1737 /// index into this very list, so every one past `idx` is walked down with
1738 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1739 /// for its clips, for its reason.
1740 ///
1741 /// Refused, changing nothing, while anything placed on a subtitle lane
1742 /// plays *this* row: the placement would have to be deleted or retargeted,
1743 /// and either one is an edit nobody asked for. The refusal names the lane
1744 /// and the frame it is at, up to three of them --
1745 /// [`remove_source`](Project::remove_source) refuses the same way for the
1746 /// same silent corruption.
1747 ///
1748 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1749 /// history snapshots hold the lane list and subtitles are not on it
1750 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1751 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1752 /// door, which reads the subtitles of a file and nothing else -- and not a
1753 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1754 /// entry holding the project's own settings beside the lanes. The history
1755 /// is *cleared* rather than kept, as a source removal clears it: the
1756 /// snapshots hold the indexes as they were before the reindex, so an undo
1757 /// into one would put every placement past `idx` on the wrong track.
1758 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1759 if idx >= self.subtitles.len() {
1760 return Err(format!("there is no subtitle track {idx} to remove").into());
1761 }
1762 let placed: Vec<String> = handles(&self.lanes)
1763 .into_iter()
1764 .zip(&self.lanes)
1765 .flat_map(|(lane, data)| {
1766 data.subs
1767 .iter()
1768 .filter(move |s| s.track == idx)
1769 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1770 })
1771 .take(3)
1772 .collect();
1773 if !placed.is_empty() {
1774 return Err(format!(
1775 "{} is on the timeline ({}): delete those clips first",
1776 self.track_name(idx),
1777 placed.join(", ")
1778 )
1779 .into());
1780 }
1781 self.subtitles.remove(idx);
1782 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1783 if s.track > idx {
1784 s.track -= 1;
1785 }
1786 }
1787 self.history.clear();
1788 Ok(())
1789 }
1790
1791 /// What a refusal calls a palette row: the name the panel shows, and the
1792 /// index alone for a row that is not there.
1793 fn track_name(&self, track: usize) -> String {
1794 self.subtitles
1795 .get(track)
1796 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1797 }
1798
1799 /// The subtitle lanes in display order -- what a front-end lays out and
1800 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1801 /// [`audio_lanes`](Project::audio_lanes).
1802 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1803 self.lanes()
1804 .into_iter()
1805 .filter(|l| l.kind == LaneKind::Subtitle)
1806 .collect()
1807 }
1808
1809 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1810 /// for a subtitle track, and empty for every other lane and for one that is
1811 /// not there.
1812 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1813 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1814 }
1815
1816 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1817 /// twin, with one deliberate difference: it **refuses** an overlap instead
1818 /// of overwriting what it lands on.
1819 ///
1820 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1821 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1822 /// carries is a *window of a track* and where the hand let go, and the
1823 /// second of those is the argument. So a caller builds the placement once
1824 /// (from the palette row it dragged) and drops it at as many frames as it
1825 /// likes without rewriting the field each time.
1826 ///
1827 /// A picture placed over a picture hides it and the hidden one is still
1828 /// there to drag back out; two captions in one frame are two lines nobody
1829 /// asked to stack, and the words that lost are gone from the screen with
1830 /// nothing to show for it. So the refusal names the placement in the way,
1831 /// and the caller picks another frame or another lane -- which is what a
1832 /// second subtitle lane is for.
1833 ///
1834 /// One undo step on success, and none on any refusal: an empty window or an
1835 /// empty span, a track the palette does not have
1836 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1837 /// subtitle lane, a span that would run past the last frame there is, and
1838 /// the overlap above.
1839 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1840 if lane.kind != LaneKind::Subtitle {
1841 return Err(format!(
1842 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1843 the others",
1844 lane.label()
1845 )
1846 .into());
1847 }
1848 let Some(i) = self.index(lane) else {
1849 return Err(format!("there is no {} to place on", lane.label()).into());
1850 };
1851 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1852 return Err(format!(
1853 "that placement is empty: {} frames of [{}, {})",
1854 sub.frames, sub.in_us, sub.out_us
1855 )
1856 .into());
1857 }
1858 if sub.track >= self.subtitles.len() {
1859 return Err(format!(
1860 "it names subtitle track {} of {}",
1861 sub.track,
1862 self.subtitles.len()
1863 )
1864 .into());
1865 }
1866 // The placement belongs to no group, for [`place`]'s reason: a caption
1867 // dragged out of the palette arrives alone, and grouping it with what
1868 // is under it is a hand's decision ([`Project::group_all`]).
1869 let sub = SubClip {
1870 start: at,
1871 link: None,
1872 ..sub
1873 };
1874 if at.checked_add(sub.frames).is_none() {
1875 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1876 }
1877 if let Some(other) = self.lanes[i]
1878 .subs
1879 .iter()
1880 .find(|o| o.end() > sub.start && o.start < sub.end())
1881 {
1882 return Err(format!(
1883 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1884 on another subtitle track",
1885 lane.label(),
1886 other.start,
1887 other.start,
1888 other.end()
1889 )
1890 .into());
1891 }
1892 self.snapshot();
1893 let subs = &mut self.lanes[i].subs;
1894 let idx = subs.partition_point(|o| o.start < sub.start);
1895 subs.insert(idx, sub);
1896 debug_assert!(subs_sorted_disjoint(subs));
1897 Ok(())
1898 }
1899
1900 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1901 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1902 /// refused an overlap where that one clamps to it, for
1903 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1904 /// still and no picture under it that a landing would hide, so "as far as
1905 /// it goes" would silently be a frame nobody named.
1906 ///
1907 /// A caption *in* a group drags the group: one delta for every member --
1908 /// its clips and its other captions -- clamped to the room each of them
1909 /// has, exactly as a clip's drag always has. That is the point of putting
1910 /// a caption in a group: the words go where the picture goes.
1911 ///
1912 /// The window travels untouched: a caption dragged later says the same
1913 /// words later, exactly as a clip dragged later plays the same pictures
1914 /// later.
1915 ///
1916 /// One undo step on success; nothing changed and no step on a refusal --
1917 /// an index that is not there, a lane that is not a subtitle lane or is not
1918 /// there, and (for a caption in no group) an overlap. A drop that changes
1919 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1920 /// up and put it back has done nothing wrong, and a front-end showing every
1921 /// `Err` would say so.
1922 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1923 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1924 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1925 };
1926 if to.kind != LaneKind::Subtitle {
1927 return Err(format!(
1928 "{} is not a subtitle track: a caption cannot play on it",
1929 to.label()
1930 )
1931 .into());
1932 }
1933 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1934 return Err(format!("there is no {} to move onto", to.label()).into());
1935 };
1936 if (here, start) == (dest, sub.start) {
1937 // A pick-up-put-back: the drag ended where it began, which is not a
1938 // mistake to name -- `Ok`, and no undo step, because nothing
1939 // changed. A refusal here would toast a hand that did nothing.
1940 return Ok(());
1941 }
1942 if start.checked_add(sub.frames).is_none() {
1943 return Err(
1944 format!("a placement at frame {start} runs past the last frame there is").into(),
1945 );
1946 }
1947 // A grouped caption carries its group, clamped to the room the whole
1948 // group has rather than refused ([`Project::move_room]) -- one drag, one
1949 // delta, one undo step.
1950 let members = self.group_of(from, idx).expect("the subtitle was found");
1951 if !members.alone() {
1952 if members
1953 .subs
1954 .iter()
1955 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1956 {
1957 return Err(format!(
1958 "a group is one caption per track: {} already carries this group",
1959 to.label()
1960 )
1961 .into());
1962 }
1963 let want = i64::from(start) - i64::from(sub.start);
1964 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1965 return Err(format!(
1966 "another placement already covers those frames on {}",
1967 to.label()
1968 )
1969 .into());
1970 };
1971 let delta = want.clamp(lo, hi);
1972 self.snapshot();
1973 for &(l, i) in &members.clips {
1974 let c = &mut self.lanes[l].clips[i];
1975 c.start = (i64::from(c.start) + delta) as u32;
1976 }
1977 for &(l, i) in &members.subs {
1978 let s = &mut self.lanes[l].subs[i];
1979 s.start = (i64::from(s.start) + delta) as u32;
1980 }
1981 let moved = self.lanes[here].subs.remove(idx);
1982 let subs = &mut self.lanes[dest].subs;
1983 let at = subs.partition_point(|o| o.start < moved.start);
1984 subs.insert(at, moved);
1985 debug_assert!(subs_sorted_disjoint(subs));
1986 debug_assert!(members
1987 .clips
1988 .iter()
1989 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1990 return Ok(());
1991 }
1992 let moved = SubClip { start, ..sub };
1993 if let Some(other) = self.lanes[dest]
1994 .subs
1995 .iter()
1996 .enumerate()
1997 .find(|&(j, o)| {
1998 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1999 })
2000 .map(|(_, o)| *o)
2001 {
2002 return Err(format!(
2003 "the {} subtitle at frame {} already covers [{}, {})",
2004 to.label(),
2005 other.start,
2006 other.start,
2007 other.end()
2008 )
2009 .into());
2010 }
2011 self.snapshot();
2012 self.lanes[here].subs.remove(idx);
2013 let subs = &mut self.lanes[dest].subs;
2014 let at = subs.partition_point(|o| o.start < moved.start);
2015 subs.insert(at, moved);
2016 debug_assert!(subs_sorted_disjoint(subs));
2017 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
2018 Ok(())
2019 }
2020
2021 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
2022 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
2023 /// pulling an edge past what is legal means "as far as it goes".
2024 ///
2025 /// The window follows the edge, in the seconds the frames are worth at
2026 /// `fps`: a head pulled in starts the caption later *in its track* (the
2027 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
2028 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
2029 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
2030 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
2031 /// needed here and nowhere else in this file, because a trim is the only
2032 /// edit that changes a *duration*.
2033 ///
2034 /// The walls: one frame always survives, an edge never crosses the
2035 /// neighbouring subtitle on its own lane, a head never walks back past the
2036 /// track's own start (`in_us` of 0), and a tail never runs past the last
2037 /// cue the track has -- which is the source length a media trim needs a
2038 /// caller's table for, and which this one can simply read.
2039 ///
2040 /// `Err`, with nothing changed and no undo step, for an index that is not
2041 /// there and an unusable `fps`. An edge that ends up where it already was
2042 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2043 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2044 /// reason: a drag that stops at a wall is not a mistake to report.
2045 pub fn trim_sub(
2046 &mut self,
2047 lane: Lane,
2048 idx: usize,
2049 edge: Edge,
2050 to: u32,
2051 fps: f64,
2052 ) -> crate::Result<()> {
2053 if !(fps.is_finite() && fps > 0.0) {
2054 return Err(format!("{fps} is not a frame rate to trim against").into());
2055 }
2056 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2057 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2058 };
2059 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2060 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2061 };
2062 let to = to.clamp(lo, hi);
2063 let at = match edge {
2064 Edge::Start => sub.start,
2065 Edge::End => sub.end(),
2066 };
2067 if to == at {
2068 // The edge is where it was asked to go -- either the hand did not
2069 // move it, or the clamp above stopped it at a wall it was already
2070 // standing against. Both are a drag that changed nothing: `Ok`, no
2071 // undo step, and no toast for a box that simply stopped moving.
2072 return Ok(());
2073 }
2074 self.snapshot();
2075 let members = self.group_of(lane, idx).expect("the subtitle was found");
2076 let i = self.index(lane).expect("the subtitle was found on it");
2077 let s = &mut self.lanes[i].subs[idx];
2078 match edge {
2079 // The words that stay are the words that were there, so the window
2080 // moves with the head -- a trim, not a slip.
2081 Edge::Start => {
2082 // Clamped to a window that is still a window: the walls above
2083 // are frames and the rounding between the two clocks is not
2084 // exact, and neither is a caller's hand-built placement.
2085 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2086 .clamp(0, s.out_us - 1);
2087 s.frames = s.end() - to;
2088 s.start = to;
2089 }
2090 Edge::End => {
2091 s.out_us =
2092 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2093 s.frames = to - s.start;
2094 }
2095 }
2096 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2097 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2098 // A caption in a group drags its group's edge with it, exactly as a
2099 // clip's trim does: one delta, each member clamped to its own room.
2100 // No source table to grow by, which only tightens how far a member may
2101 // follow -- never whether it may.
2102 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
2103 Ok(())
2104 }
2105
2106 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2107 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2108 /// drawing the box during a drag asks. `None` for an index that is not
2109 /// there.
2110 pub fn trim_sub_room(
2111 &self,
2112 lane: Lane,
2113 idx: usize,
2114 edge: Edge,
2115 fps: f64,
2116 ) -> Option<(u32, u32)> {
2117 let subs = self.sub_lane(lane);
2118 let s = *subs.get(idx)?;
2119 // How many timeline frames a stretch of the track is worth, which is
2120 // what turns its two walls -- its own start, and its last cue -- into
2121 // frames. A rate that is not a rate leaves the window where it is.
2122 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2123 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
2124 false => 0,
2125 };
2126 Some(match edge {
2127 Edge::Start => (
2128 s.start
2129 .saturating_sub(frames_of(s.in_us))
2130 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2131 s.end() - 1,
2132 ),
2133 Edge::End => {
2134 // Out to the end of the track it reads, and never over the
2135 // subtitle behind it. A track the palette no longer has (or one
2136 // with no cues at all) may not grow, exactly as a source with no
2137 // entry in a media trim's table may not.
2138 let track_end = self
2139 .subtitles
2140 .get(s.track)
2141 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2142 .unwrap_or(s.out_us);
2143 (
2144 s.start + 1,
2145 s.start
2146 .saturating_add(frames_of(track_end - s.in_us).max(1))
2147 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2148 )
2149 }
2150 })
2151 }
2152
2153 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2154 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2155 /// `false` for an index that is not there (which a lane that is not a
2156 /// subtitle lane always is).
2157 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2158 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2159 return false;
2160 };
2161 self.snapshot();
2162 self.lanes[i].subs.remove(idx);
2163 true
2164 }
2165
2166 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2167 /// window of its track, clipped to that window and shifted to where the
2168 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2169 /// carried through the picture's spans -- this is its twin for a track that
2170 /// is placed on a lane of its own, and it is what a preview draws and what
2171 /// an export of the lane would write.
2172 ///
2173 /// Cut, not stretched: a cue half inside the window keeps the half that is
2174 /// inside, and a cue wholly outside it is gone -- the same rule the media
2175 /// spans follow. `fps` is the timeline's rate, needed here because a
2176 /// placement's *position* is in frames while its words are in microseconds.
2177 ///
2178 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2179 /// of their cues, no file opened), which is how a front-end asks it.
2180 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2181 if !(fps.is_finite() && fps > 0.0) {
2182 return Vec::new();
2183 }
2184 let mut out = Vec::new();
2185 for s in self.sub_lane(lane) {
2186 let Some(track) = self.subtitles.get(s.track) else {
2187 // A placement whose track was taken off the palette
2188 // ([`Project::remove_subtitles`]) shows nothing rather than
2189 // showing another track's words.
2190 continue;
2191 };
2192 // Where the placement's own first microsecond lands on the
2193 // timeline, and how many microseconds of timeline one microsecond
2194 // of the window is worth: the placement's own proportion, which a
2195 // group's re-rate changes (the frames compress, the window does
2196 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2197 // every cue lands where it always did; at 2x the words cross the
2198 // screen in half the time, cue for cue.
2199 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2200 let onto = |t: i64| {
2201 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2202 };
2203 for cue in &track.cues {
2204 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2205 if b <= a {
2206 continue; // wholly outside the window this placement keeps
2207 }
2208 out.push(SubtitleCue {
2209 start_us: onto(a),
2210 end_us: onto(b),
2211 text: cue.text.clone(),
2212 image: cue.image.clone(),
2213 });
2214 }
2215 }
2216 // The placements come in timeline order, but two lanes' worth (or a
2217 // track whose cues a window reordered) do not.
2218 out.sort_by_key(|cue| cue.start_us);
2219 out
2220 }
2221
2222 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2223 /// lanes is multiplied by on its way into the mix: the same lanes in the
2224 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2225 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2226 /// the bit-exact path.
2227 pub fn audio_gains(&self) -> Vec<f32> {
2228 self.audio_lanes()
2229 .into_iter()
2230 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2231 .collect()
2232 }
2233
2234 /// The master limiter the mix is summed through. A project setting, not a
2235 /// clip's and not a lane's: there is one mix.
2236 pub fn limiter(&self) -> Limiter {
2237 self.limiter
2238 }
2239
2240 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2241 /// for a setting already in force.
2242 ///
2243 /// corner-cut: not an undo step, for the reason the project resolution is not
2244 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2245 /// lane list the history snapshots. Upgrade path is a history entry that
2246 /// holds the mix settings beside the lanes.
2247 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2248 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2249 if self.limiter == limiter {
2250 return false;
2251 }
2252 self.limiter = limiter;
2253 true
2254 }
2255
2256 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2257 /// plays flat (and for an index that is not there) -- what a feeder and an
2258 /// export ask before they build an [`crate::eq::EqState`].
2259 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2260 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2261 }
2262
2263 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2264 /// take them off. One undo step, like every other edit. `false` -- and no
2265 /// history -- for an index that is not there and for params holding a value
2266 /// that is not finite, which is the one thing the file format could not
2267 /// write and read back.
2268 ///
2269 /// Settings equal to ones already in the table share their entry, so a
2270 /// project that puts the same curve on twenty clips writes it once.
2271 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2272 if idx >= self.lane(lane).len() {
2273 return false;
2274 }
2275 let slot = match params {
2276 None => None,
2277 Some(params) => {
2278 if !finite(&params) {
2279 return false;
2280 }
2281 Some(match self.eq.iter().position(|p| *p == params) {
2282 Some(at) => at as u16,
2283 // corner-cut: the table is append-only within a session (see
2284 // the module docs) and `Clip::eq` is a u16, so the 65535th
2285 // *distinct* setting of one session is refused rather than
2286 // silently aliased. Upgrade path if a UI ever drags a slider
2287 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2288 // snapshot the table into the history and compact it here.
2289 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2290 None => {
2291 self.eq.push(params);
2292 (self.eq.len() - 1) as u16
2293 }
2294 })
2295 }
2296 };
2297 self.snapshot();
2298 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2299 true
2300 }
2301
2302 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2303 /// ungraded (and for an index that is not there) -- what the renderer and
2304 /// the export ask before they call [`crate::color::apply_yuv`].
2305 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2306 self.color
2307 .get(usize::from(self.lane(lane).get(idx)?.color?))
2308 }
2309
2310 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2311 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2312 /// (and no history) for an index that is not there or a value that is not
2313 /// finite, and equal settings share a table entry.
2314 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2315 self.write_color(lane, idx, params, true)
2316 }
2317
2318 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2319 /// one pointer drag, whose first write (a plain `set_color`) already took the
2320 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2321 /// not one per pixel -- and undoing it lands where the hand picked it up.
2322 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2323 self.write_color(lane, idx, params, false)
2324 }
2325
2326 fn write_color(
2327 &mut self,
2328 lane: Lane,
2329 idx: usize,
2330 params: Option<ColorParams>,
2331 snapshot: bool,
2332 ) -> bool {
2333 if idx >= self.lane(lane).len() {
2334 return false;
2335 }
2336 let slot = match params {
2337 None => None,
2338 Some(params) => {
2339 if !color_finite(&params) {
2340 return false;
2341 }
2342 Some(match self.color.iter().position(|p| *p == params) {
2343 Some(at) => at as u16,
2344 // corner-cut: the 65535th *distinct* grade of one session is
2345 // refused rather than silently aliased, exactly as `set_eq`
2346 // refuses the 65535th curve; same upgrade path.
2347 None if self.color.len() >= usize::from(u16::MAX) => return false,
2348 None => {
2349 self.color.push(params);
2350 (self.color.len() - 1) as u16
2351 }
2352 })
2353 }
2354 };
2355 if snapshot {
2356 self.snapshot();
2357 }
2358 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2359 true
2360 }
2361
2362 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2363 /// policy's own placement (and for an index that is not there) -- what the
2364 /// renderer and the export ask before they place its picture.
2365 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2366 self.transform
2367 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2368 }
2369
2370 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2371 /// step, `false` (and no history) for an index that is not there or a
2372 /// value that is not finite, and equal settings share a table entry.
2373 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2374 self.write_transform(lane, idx, params, true)
2375 }
2376
2377 /// [`set_transform`](Self::set_transform) without the undo step, for
2378 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2379 /// one drag on a position/scale/rotate/crop control are one undo, not one
2380 /// per pixel.
2381 pub fn set_transform_live(
2382 &mut self,
2383 lane: Lane,
2384 idx: usize,
2385 params: Option<TransformParams>,
2386 ) -> bool {
2387 self.write_transform(lane, idx, params, false)
2388 }
2389
2390 fn write_transform(
2391 &mut self,
2392 lane: Lane,
2393 idx: usize,
2394 params: Option<TransformParams>,
2395 snapshot: bool,
2396 ) -> bool {
2397 if idx >= self.lane(lane).len() {
2398 return false;
2399 }
2400 let slot = match params {
2401 None => None,
2402 Some(params) => {
2403 if !transform_finite(&params) {
2404 return false;
2405 }
2406 Some(match self.transform.iter().position(|p| *p == params) {
2407 Some(at) => at as u16,
2408 // corner-cut: the 65535th *distinct* transform of one
2409 // session is refused rather than silently aliased,
2410 // exactly as `write_color` refuses the 65535th grade;
2411 // same upgrade path.
2412 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2413 None => {
2414 self.transform.push(params);
2415 (self.transform.len() - 1) as u16
2416 }
2417 })
2418 }
2419 };
2420 if snapshot {
2421 self.snapshot();
2422 }
2423 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2424 true
2425 }
2426
2427 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2428 /// index that is not there, which is what every clip starts at anyway.
2429 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2430 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2431 }
2432
2433 /// Sets it, for the clip **and its whole group**: a link is one span on
2434 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2435 /// from its sound would be a group no save could load. One snapshot, so the
2436 /// group's change is one [`Project::undo`].
2437 ///
2438 /// The source range is untouched -- a speed says how many timeline frames
2439 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2440 /// split still address the file afterwards.
2441 ///
2442 /// Refused, changing nothing and costing no undo step, when the clip would
2443 /// grow into the one after it on its own lane: slowing a clip down makes it
2444 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2445 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2446 /// something a user can go and fix. Also for an index that is not there.
2447 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2448 self.write_speed(lane, idx, speed, true)
2449 }
2450
2451 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2452 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2453 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2454 /// not one per rate it passed through -- exactly as
2455 /// [`set_color_live`](Self::set_color_live) is for a slider.
2456 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2457 self.write_speed(lane, idx, speed, false)
2458 }
2459
2460 fn write_speed(
2461 &mut self,
2462 lane: Lane,
2463 idx: usize,
2464 speed: Speed,
2465 snapshot: bool,
2466 ) -> crate::Result<()> {
2467 let Some(members) = self.group_of(lane, idx) else {
2468 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2469 };
2470 let labels = handles(&self.lanes);
2471 // The clip the hand is holding is the group's clock: everything else
2472 // in the group, caption members included, re-times by the ratio its new
2473 // rate gives its own frames. The clips take the rate itself; a caption
2474 // has none, so it takes the *ratio* -- its span on the timeline
2475 // compresses or stretches about the held clip's head, while the words
2476 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2477 // timeline moves, the track does not).
2478 let Some(held) = self.lane(lane).get(idx).copied() else {
2479 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2480 };
2481 // The same per-member piece `speeded_playhead` builds for this op,
2482 // asked here instead of read there -- a caption's length comes from
2483 // the map's own ends (`end - start`), never `round(len * ratio)`
2484 // separately, which is what let the two answers drift apart by a
2485 // frame.
2486 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2487 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2488 let retimed = |s: SubClip| {
2489 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2490 let start = map.apply(s.start);
2491 let end = map.apply(s.end()).max(start.saturating_add(1));
2492 SubClip { start, frames: end - start, ..s }
2493 };
2494 for &(l, i) in &members.clips {
2495 let clips = &self.lanes[l].clips;
2496 let mut moved = clips[i];
2497 moved.speed = speed;
2498 if let Some(next) = clips.get(i + 1)
2499 && moved.end() > next.start
2500 {
2501 let name = labels[l].label();
2502 return Err(format!(
2503 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2504 move it along, or trim this one first",
2505 moved.end(),
2506 next.start
2507 )
2508 .into());
2509 }
2510 }
2511 // ...and the captions, against their own lanes' captions: a stretch
2512 // that runs one into its neighbour is refused for the clip arm's
2513 // reason -- a lane may not overlap itself -- and by name like it.
2514 let subs: Vec<(usize, usize, SubClip)> = members
2515 .subs
2516 .iter()
2517 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2518 .collect();
2519 for &(l, i, moved) in &subs {
2520 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2521 if j != i && moved.start < other.end() && other.start < moved.end() {
2522 return Err(format!(
2523 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2524 starts at {}: move it along, or trim this one first",
2525 labels[l].label(),
2526 self.lanes[l].subs[i].start,
2527 moved.end(),
2528 other.start
2529 )
2530 .into());
2531 }
2532 }
2533 }
2534 if snapshot {
2535 self.snapshot();
2536 }
2537 for (l, i) in members.clips {
2538 self.lanes[l].clips[i].speed = speed;
2539 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2540 }
2541 for (l, i, moved) in subs {
2542 self.lanes[l].subs[i] = moved;
2543 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2544 }
2545 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2546 Ok(())
2547 }
2548
2549 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2550 /// playhead standing at `at` -- read off the geometry **before** the
2551 /// write, because the old ends are gone after it. The question a card
2552 /// asks as its bar moves: the picture under the cursor has to stay the
2553 /// picture under the cursor, or the scene changes with the rate.
2554 ///
2555 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2556 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2557 /// a clip member keeps its own start and re-fits its length at the new
2558 /// rate -- its **old** rate against the new one, which is what the bar's
2559 /// live samples ask about as much as a first press does; a caption
2560 /// member scales about the held clip's start by the held clip's own
2561 /// proportion; and a playhead outside every member's old extent stays
2562 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2563 /// (or the room a stretch takes) absorbs the difference, not the
2564 /// playhead. `None` for an index that is not there.
2565 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2566 let members = self.group_of(lane, idx)?;
2567 let held = self.lane(lane).get(idx).copied()?;
2568 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2569 for &(l, i) in members.clips.iter().chain(&members.subs) {
2570 let (span, map) = match self
2571 .lanes[l]
2572 .clips
2573 .get(i)
2574 .filter(|_| members.clips.contains(&(l, i)))
2575 {
2576 // The clip's own span, re-fitted at its own old rate: one
2577 // piece of the map, anchored where the clip itself is. The
2578 // new length is the same *source* frames at the new rate --
2579 // len divided by it, never multiplied.
2580 Some(c) => (
2581 (c.start, c.start + c.frames()),
2582 TimelineMap::piece(
2583 (c.start, c.start + c.frames()),
2584 (
2585 c.start,
2586 c.start + (c.len() as f64 / new).round() as u32,
2587 ),
2588 ),
2589 ),
2590 // The caption's span, scaled about the held clip's head by
2591 // the held clip's proportion -- the offset the group keeps.
2592 None => {
2593 let s = self.lanes[l].subs.get(i)?;
2594 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2595 (
2596 (s.start, s.end()),
2597 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2598 )
2599 }
2600 };
2601 // The piece owns only its own old span: outside it the playhead
2602 // is another member's question, or nobody's.
2603 if (span.0..span.1).contains(&at) {
2604 return Some(map.apply(at));
2605 }
2606 }
2607 Some(at)
2608 }
2609
2610 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2611 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2612 /// every clip starts at anyway.
2613 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2614 self.lane(lane)
2615 .get(idx)
2616 .map_or(FitPolicy::default(), |c| c.fit)
2617 }
2618
2619 /// Sets it. One undo step like every other edit, and `false` (with no
2620 /// history) for an index that is not there. Unlike an eq or a grade there is
2621 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2622 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2623 if idx >= self.lane(lane).len() {
2624 return false;
2625 }
2626 self.snapshot();
2627 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2628 true
2629 }
2630
2631 /// Timeline frames of ramp-up from silence at the start of the clip at
2632 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2633 /// that has none.
2634 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2635 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2636 }
2637
2638 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2639 /// can shrink a clip's audible middle to nothing but never ask for more
2640 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2641 /// and `false` (no history) for an index that is not there.
2642 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2643 if idx >= self.lane(lane).len() {
2644 return false;
2645 }
2646 self.snapshot();
2647 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2648 clip.fade_in = frames.min(clip.frames());
2649 true
2650 }
2651
2652 /// Timeline frames of ramp-down to silence at the end of the clip at
2653 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2654 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2655 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2656 }
2657
2658 /// Sets it. Same promises as [`Project::set_fade_in`].
2659 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2660 if idx >= self.lane(lane).len() {
2661 return false;
2662 }
2663 self.snapshot();
2664 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2665 clip.fade_out = frames.min(clip.frames());
2666 true
2667 }
2668
2669 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2670 /// into its successor, at its own end. `0` for an index that is not
2671 /// there, same as a clip that has none.
2672 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2673 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2674 }
2675
2676 /// Sets it, clamped to the clip's own length and to how many frames its
2677 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2678 /// visible middle to nothing but never ask for more than the two clips
2679 /// between them have. `false` -- no history -- unless `lane` is video,
2680 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2681 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2682 /// them. One undo step like [`Project::set_fade_out`].
2683 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2684 if lane.kind != LaneKind::Video {
2685 return false;
2686 }
2687 let clips = self.lane(lane);
2688 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2689 return false;
2690 };
2691 if a.end() != b.start {
2692 return false;
2693 }
2694 let cap = a.frames().min(b.frames());
2695 self.snapshot();
2696 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2697 true
2698 }
2699
2700 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2701 /// after it, over `frames` timeline frames: sets `idx`'s
2702 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2703 /// each clamped to its own clip's length. `false` -- no history -- unless
2704 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2705 /// adjacent: the second's [`Clip::start`] is exactly the first's
2706 /// [`Clip::end`], no gap between them.
2707 ///
2708 /// This is the whole mechanism, not a stand-in for one: a *real*
2709 /// cross-fade -- both takes heard at once, blending -- is what two clips
2710 /// **overlapping** on separate lanes already get for free from the
2711 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2712 /// This call only shapes the edges of two clips already sitting
2713 /// end-to-end on *one* lane, so the join between them fades like one did.
2714 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2715 if lane.kind != LaneKind::Audio {
2716 return false;
2717 }
2718 let clips = self.lane(lane);
2719 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2720 return false;
2721 };
2722 if a.end() != b.start {
2723 return false;
2724 }
2725 self.snapshot();
2726 let clips = self.lane_mut(lane).expect("checked above");
2727 clips[idx].fade_out = frames.min(clips[idx].frames());
2728 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2729 true
2730 }
2731
2732 /// Every frame number on every lane rewritten onto a timeline counted at
2733 /// another rate: `k` is old timeline frames per new one, `counts` is how
2734 /// long each source is on the *new* timeline (indexed as
2735 /// [`Project::sources`] is), and the edit survives as the same seconds of
2736 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2737 /// the edit list, and the only thing that touches the frame numbers without
2738 /// being an edit anyone made.
2739 ///
2740 /// Every position -- a clip's start and its end alike -- goes through the
2741 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2742 /// stays a gap, and a take's picture and its sound land on the same frame on
2743 /// their two lanes: no lane can drift against another. A clip is then only
2744 /// ever made to *fit* the room its own start and end mapped to, never to
2745 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2746 /// below is the backstop for the one case that could: a slow clip so short
2747 /// that no source range fits its new room at all).
2748 ///
2749 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2750 /// onto the new grid, so a rate picked, unpicked and picked again is within
2751 /// a frame of where it started rather than back at it. Upgrade path is
2752 /// keeping the edit list at one reference rate and conforming on the way
2753 /// out, which every frame number in this module would then be measured in.
2754 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2755 for lane in &mut self.lanes {
2756 let mut cursor = 0;
2757 for clip in &mut lane.clips {
2758 let start = k.timeline_at(clip.start).max(cursor);
2759 // The room its own end mapped to -- never zero, since a clip is
2760 // never empty even on a grid too coarse to hold it.
2761 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2762 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2763 // Its footage, held inside the file's new length: a clip whose
2764 // out-point was the last frame of its source must not come out
2765 // of this naming a frame past the end -- that is a project that
2766 // would not open again ([`crate::PlaybackSession::open_project`]
2767 // refuses one by name).
2768 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2769 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2770 clip.start = start;
2771 clip.in_frame = in_frame;
2772 clip.out_frame = in_frame + len;
2773 cursor = clip.end();
2774 }
2775 // A subtitle's *window* is in microseconds and a rate change moves
2776 // no seconds, so only where it sits is remapped -- through the same
2777 // [`Rate::timeline_at`] every clip boundary goes through, so a
2778 // caption still starts on the frame its picture does.
2779 let mut cursor = 0;
2780 for sub in &mut lane.subs {
2781 let start = k.timeline_at(sub.start).max(cursor);
2782 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2783 sub.start = start;
2784 cursor = sub.end();
2785 }
2786 }
2787 }
2788
2789 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2790 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2791 ///
2792 /// A subtitle lane counts like any other: a caption placed past the last
2793 /// picture holds the timeline open under it, exactly as an `A2` running
2794 /// past `V1` does, rather than being silently clipped away by the length
2795 /// ([`crate::export::timeline_cues`] clips cues to this).
2796 pub fn timeline_frames(&self) -> u32 {
2797 self.lanes
2798 .iter()
2799 .filter_map(|l| match l.kind {
2800 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2801 _ => l.clips.last().map(Clip::end),
2802 })
2803 .max()
2804 .unwrap_or(0)
2805 }
2806
2807 /// The same, counting the *media* alone: where the last picture or sound
2808 /// runs out, with the captions over them ignored.
2809 ///
2810 /// What an export actually writes ends here -- the picture loop walks the
2811 /// composite spans and the file stops with them -- so this is the length a
2812 /// cue has to be inside of to be written at all (what
2813 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2814 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2815 /// thing is a picture or a sound, which is every timeline that has no
2816 /// caption hanging past the end of both.
2817 pub fn media_frames(&self) -> u32 {
2818 self.lanes
2819 .iter()
2820 .filter(|l| l.kind != LaneKind::Subtitle)
2821 .filter_map(|l| l.clips.last().map(Clip::end))
2822 .max()
2823 .unwrap_or(0)
2824 }
2825
2826 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2827 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2828 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2829 self.lane_spans(Lane::V1)
2830 }
2831
2832 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2833 // Timeline frames, not source ones: a box on a lane is as wide as the
2834 // clip is long *there*, which a speed halves or quadruples.
2835 self.lane(lane)
2836 .iter()
2837 .map(|c| (c.start, c.frames()))
2838 .collect()
2839 }
2840
2841 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2842 /// and past the end -- [`Project::span_at`] is the version that tells those
2843 /// two apart.
2844 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2845 let clips = self.lane(lane);
2846 let idx = at(clips, timeline_frame)?;
2847 Some((idx, source_frame(&clips[idx], timeline_frame)))
2848 }
2849
2850 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2851 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2852 self.map(Lane::V1, timeline_frame)
2853 }
2854
2855 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2856 /// it, or the gap running to the next clip (or to the end of the timeline,
2857 /// which is where a lane shorter than its neighbour keeps showing black).
2858 /// `None` at or past the end of the timeline, which is the only "nothing
2859 /// left" there is.
2860 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2861 let total = self.timeline_frames();
2862 if timeline_frame >= total {
2863 return None;
2864 }
2865 let clips = self.lane(lane);
2866 Some(match at(clips, timeline_frame) {
2867 Some(idx) => Span {
2868 start: timeline_frame,
2869 len: clips[idx].end() - timeline_frame,
2870 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2871 speed: clips[idx].speed,
2872 },
2873 None => Span {
2874 start: timeline_frame,
2875 speed: Speed::NORMAL,
2876 // The next placement, or the end of the timeline: a gap is
2877 // bounded by what comes after it, never by its own bookkeeping.
2878 len: clips
2879 .iter()
2880 .find(|c| c.start > timeline_frame)
2881 .map_or(total, |c| c.start)
2882 - timeline_frame,
2883 from: None,
2884 },
2885 })
2886 }
2887
2888 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2889 /// gaps included -- the whole play list, which is what an export walks.
2890 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2891 let mut out = Vec::new();
2892 let mut t = timeline_frame;
2893 while let Some(span) = self.span_at(lane, t) {
2894 t = span.end();
2895 out.push(span);
2896 }
2897 out
2898 }
2899
2900 /// What the *composite* shows from `timeline_frame` on -- the answer
2901 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2902 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2903 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2904 /// (the usual overlay convention). A frame no video lane covers is a gap,
2905 /// which is black however many lanes are above or below it.
2906 ///
2907 /// No blending, so exactly one lane is visible at a time and the composite
2908 /// is itself a span list -- which is why one decoder plays it, the same one
2909 /// a single-lane timeline uses, rather than N running at once.
2910 ///
2911 /// The span is cut short wherever a *higher* lane's clip starts, because
2912 /// from that frame on a different lane wins; that is what makes walking
2913 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2914 ///
2915 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2916 /// lanes would then be visible in one frame and the caller needs a decoder
2917 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2918 /// (this same walk, per lane) feeding N decoders.
2919 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2920 let total = self.timeline_frames();
2921 if timeline_frame >= total {
2922 return None;
2923 }
2924 let video = self.video_lanes();
2925 // The last covering lane is the winner; only the lanes above it can
2926 // interrupt what it shows.
2927 let winner = video
2928 .iter()
2929 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2930 let (from, speed, until) = match winner {
2931 Some(i) => {
2932 let clips = self.lane(video[i]);
2933 let idx = at(clips, timeline_frame).expect("just found above");
2934 (
2935 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2936 clips[idx].speed,
2937 clips[idx].end(),
2938 )
2939 }
2940 // Nothing covers it: black until something above the floor starts.
2941 None => (None, Speed::NORMAL, total),
2942 };
2943 let takeover = video[winner.map_or(0, |i| i + 1)..]
2944 .iter()
2945 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2946 .map(|c| c.start)
2947 .min();
2948 Some(Span {
2949 start: timeline_frame,
2950 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2951 from,
2952 speed,
2953 })
2954 }
2955
2956 /// The video lanes in display order, topmost last -- the order the composite
2957 /// rule counts in.
2958 fn video_lanes(&self) -> Vec<Lane> {
2959 self.lanes()
2960 .into_iter()
2961 .filter(|l| l.kind == LaneKind::Video)
2962 .collect()
2963 }
2964
2965 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2966 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2967 /// index on that lane. `None` over a gap and past the end. What a front-end
2968 /// asks to act on "the clip on screen" without re-deriving the rule.
2969 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2970 let video = self.video_lanes();
2971 let winner = video
2972 .iter()
2973 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2974 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2975 }
2976
2977 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2978 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2979 /// answers "the clip on screen"; this answers it per lane, which is what
2980 /// walking the lanes for something to select needs.
2981 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2982 at(self.lane(lane), timeline_frame)
2983 }
2984
2985 /// How the composite is graded at `timeline_frame`, so the picture playback
2986 /// converts and the one an export encodes are graded from one answer.
2987 /// `None` over a gap (black is black) and for a clip nobody has graded,
2988 /// which is the byte-identical path everywhere.
2989 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2990 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2991 self.color_of(lane, idx)
2992 }
2993
2994 /// [`composite_color_at`](Self::composite_color_at)'s twin for
2995 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
2996 /// policy's own placement.
2997 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
2998 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2999 self.transform_of(lane, idx)
3000 }
3001
3002 /// How the composite meets the project canvas at `timeline_frame`, so the
3003 /// picture playback composes and the one an export encodes are placed from
3004 /// one answer. `Fit` over a gap, where black is already the canvas.
3005 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
3006 self.composite_clip_at(timeline_frame)
3007 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
3008 }
3009
3010 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
3011 /// viewer sees from `timeline_frame` to the end, in order. What an export
3012 /// encodes and what playback walks at a clip boundary.
3013 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
3014 let mut out = Vec::new();
3015 let mut t = timeline_frame;
3016 while let Some(span) = self.composite_span_at(t) {
3017 t = span.end();
3018 out.push(span);
3019 }
3020 out
3021 }
3022
3023 /// Split every lane at `timeline_frame`, so that frame becomes the first
3024 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
3025 /// (`false`, no change) when no lane has a clip to split there -- at a
3026 /// placement's own start, in a gap, and past the end -- all of which would
3027 /// produce an empty clip or nothing at all.
3028 ///
3029 /// Lanes' halves share an id only where they are the *same* span: the lanes
3030 /// are edited apart, so the clip being cut here may start (or end)
3031 /// somewhere else on another lane, and a group id whose clips disagree
3032 /// about their span is not one take (see [`links_are_consistent`], which
3033 /// refuses to load one).
3034 ///
3035 /// Metadata only: no mapping changes, in any lane.
3036 pub fn split(&mut self, timeline_frame: u32) -> bool {
3037 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
3038 }
3039
3040 /// [`split`](Project::split), with the snapshot optional and the lanes
3041 /// named: a batch that has already taken a snapshot
3042 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3043 /// region and must still be one undo press, and a *scoped* batch must not
3044 /// cut a lane it was told to leave alone.
3045 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3046 let cut: Vec<Option<Clip>> = self
3047 .lanes
3048 .iter()
3049 .enumerate()
3050 .map(|(i, l)| {
3051 on.contains(&i)
3052 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3053 .flatten()
3054 })
3055 .collect();
3056 // The same question on the subtitle lanes, in their own arithmetic: a
3057 // razor cuts the captions with the picture, and a frame where only a
3058 // caption can be cut is still a cut.
3059 let cut_subs: Vec<bool> = self
3060 .lanes
3061 .iter()
3062 .enumerate()
3063 .map(|(i, l)| {
3064 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
3065 })
3066 .collect();
3067 // The links the captions carry, read before the room is opened below
3068 // -- `sub_open_room` takes the id off both halves, exactly as
3069 // `open_room` does for a clip, and the split hands the halves theirs
3070 // back afterwards.
3071 let sub_orig: Vec<Option<u32>> = self
3072 .lanes
3073 .iter()
3074 .zip(&cut_subs)
3075 .map(|(l, &cut)| {
3076 cut.then(|| {
3077 l.subs
3078 .iter()
3079 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3080 .and_then(|s| s.link)
3081 })
3082 .flatten()
3083 })
3084 .collect();
3085 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3086 return false;
3087 }
3088 if snapshot {
3089 self.snapshot();
3090 }
3091 for (data, _) in self
3092 .lanes
3093 .iter_mut()
3094 .zip(&cut_subs)
3095 .filter(|&(_, &cut)| cut)
3096 {
3097 // A split is room of no width: the halves keep their windows by
3098 // proportion and nothing moves.
3099 sub_open_room(&mut data.subs, timeline_frame, 0);
3100 debug_assert!(subs_sorted_disjoint(&data.subs));
3101 }
3102 // Each side is its own question, and the answer is the group the clip
3103 // already carried: the left half *keeps* its take's id -- the take the
3104 // frames before the cut still are -- and the right halves of one take
3105 // share one fresh id of their own, clips and captions alike. A lane
3106 // holding no group (a `place`ment, a caption nobody grouped) comes out
3107 // of the cut holding none, which is what it went in with. The captions'
3108 // own links were drawn above, before the room opened.
3109 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3110 let mut distinct: Vec<u32> = Vec::new();
3111 for id in orig.iter().chain(&sub_orig).flatten() {
3112 if !distinct.contains(id) {
3113 distinct.push(*id);
3114 }
3115 }
3116 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3117 let right_of =
3118 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
3119 for (l, data) in self.lanes.iter_mut().enumerate() {
3120 if !cut_subs[l] {
3121 continue;
3122 }
3123 // The pair the razor just made: they touch at the frame it cut.
3124 if let Some(idx) = data
3125 .subs
3126 .iter()
3127 .position(|s| s.end() == timeline_frame)
3128 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
3129 {
3130 data.subs[idx].link = sub_orig[l];
3131 data.subs[idx + 1].link = right_of(sub_orig[l]);
3132 }
3133 }
3134 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3135 // The lanes this call was not scoped to are not cut, whatever their
3136 // own clips would allow.
3137 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
3138 continue;
3139 };
3140 let mut tail = data.clips[idx];
3141 // Where the cut lands *in the file*, which is the clip's own rate
3142 // away from where it lands on the timeline. Both halves keep the
3143 // speed, and `splittable` has already refused any frame at which
3144 // the two would not add up to the one being cut.
3145 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3146 tail.start = timeline_frame;
3147 tail.link = right_of(orig[data_i]);
3148 // A split makes a new edge for each half, and a fade is a promise
3149 // about an edge: only the half that *kept* the original edge
3150 // keeps that fade, re-clamped to its own now-shorter length (a
3151 // cut inside the ramp shortens it, never leaves it pointing past
3152 // the clip it is on); the edge the cut itself made starts, or
3153 // ends, flat -- there was no silence there to ramp out of.
3154 tail.fade_in = 0;
3155 tail.fade_out = tail.fade_out.min(tail.frames());
3156 // A dissolve is a promise about the *end* edge, same as
3157 // `fade_out`: only the half that kept the clip's original end
3158 // (the tail) keeps it, re-clamped to its own now-shorter length;
3159 // the head's new end is the cut the razor just made, which starts
3160 // flat -- there was no successor to dissolve into there.
3161 tail.transition_out = tail.transition_out.min(tail.frames());
3162 data.clips[idx].out_frame = tail.in_frame;
3163 data.clips[idx].link = orig[data_i];
3164 data.clips[idx].fade_out = 0;
3165 data.clips[idx].transition_out = 0;
3166 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3167 data.clips.insert(idx + 1, tail);
3168 }
3169 true
3170 }
3171
3172 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3173 /// at `timeline_frame` in every lane and put the result back in one group.
3174 /// Only what a split could have produced is rejoined -- the two sides must
3175 /// touch on the timeline *and* be consecutive frames of the same source --
3176 /// so the clip list comes back exactly as it was and traversal with it.
3177 /// `false` when no lane has such a pair. The rejoined placement keeps the
3178 /// **left** half's id, which is the take the split left on it: rejoining a
3179 /// cut take puts the take back, id and all.
3180 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3181 // What each lane would end up covering, if it joins here at all.
3182 let joined: Vec<Option<(u32, u32)>> = self
3183 .lanes
3184 .iter()
3185 .map(|l| {
3186 joinable(&l.clips, timeline_frame)
3187 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3188 })
3189 .collect();
3190 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3191 let join_subs: Vec<Option<usize>> = self
3192 .lanes
3193 .iter()
3194 .map(|l| sub_joinable(&l.subs, timeline_frame))
3195 .collect();
3196 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3197 return false;
3198 }
3199 self.snapshot();
3200 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3201 if let Some(idx) = sub {
3202 data.subs[idx].frames += data.subs[idx + 1].frames;
3203 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3204 data.subs.remove(idx + 1);
3205 debug_assert!(subs_sorted_disjoint(&data.subs));
3206 }
3207 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3208 continue;
3209 };
3210 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3211 data.clips.remove(idx + 1);
3212 }
3213 true
3214 }
3215
3216 /// Take the placement at `idx` of `lane` out of its group: every clip and
3217 /// every caption carrying its id -- on however many lanes -- is handed an
3218 /// id of its own, so from here on each half moves, trims and is deleted
3219 /// alone. The music video whose sound is to be cut against its picture
3220 /// starts here, and so does the caption that has to come off the picture it
3221 /// was pinned to.
3222 ///
3223 /// An id of its own rather than none at all: a half no other lane is grouped
3224 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3225 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3226 /// as detached. `None` would instead say "was never part of a take", which
3227 /// is what a one-lane [`place`](Project::place) means.
3228 ///
3229 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3230 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3231 /// the group back. Refused (`false`, nothing changed) for an index that is
3232 /// not there, a placement in no group at all, and one whose group has no
3233 /// other half -- that one is already detached, and a refusal must not cost
3234 /// an undo step.
3235 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3236 let Some(members) = self.group_of(lane, idx) else {
3237 return false;
3238 };
3239 if members.alone() {
3240 return false;
3241 }
3242 let Some(id) = self
3243 .lane(lane)
3244 .get(idx)
3245 .and_then(|c| c.link)
3246 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3247 else {
3248 return false;
3249 };
3250 self.snapshot();
3251 // Drawn before the walk: `new_link` takes the whole project, and the
3252 // walk holds the lanes.
3253 let count = members.clips.len() + members.subs.len();
3254 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3255 for data in &mut self.lanes {
3256 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3257 c.link = fresh.pop();
3258 }
3259 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3260 s.link = fresh.pop();
3261 }
3262 }
3263 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3264 true
3265 }
3266
3267 /// Put two clips on two lanes into one group, so what moves one moves the
3268 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3269 /// how a picture is regrouped with sound it was never opened with. Whatever
3270 /// either of them was grouped with comes along: those clips cover this same
3271 /// span already, so the result is one group and not two overlapping ones.
3272 ///
3273 /// Same frames or nothing: a group id names **one span** on however many
3274 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3275 /// clips that do not cover the same frames cannot be one take, and the
3276 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3277 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3278 /// mean, not the rule.
3279 ///
3280 /// Metadata only, one snapshot. The error says what is wrong, because
3281 /// `false` would not: a bad index, one lane twice (a group is at most one
3282 /// clip per lane), spans that disagree, and a pair that is already one take
3283 /// -- nothing changes, and none of them costs an undo step.
3284 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3285 if a == b {
3286 return Err(format!(
3287 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3288 a.label()
3289 )
3290 .into());
3291 }
3292 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3293 p.lane(lane)
3294 .get(idx)
3295 .copied()
3296 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3297 };
3298 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3299 if (x.start, x.end()) != (y.start, y.end()) {
3300 return Err(format!(
3301 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3302 a.label(),
3303 x.start,
3304 x.end(),
3305 b.label(),
3306 y.start,
3307 y.end()
3308 )
3309 .into());
3310 }
3311 if x.link.is_some() && x.link == y.link {
3312 return Err("those two are one take already".into());
3313 }
3314 self.snapshot();
3315 let id = self.new_link();
3316 // Every clip either of them was grouped with, by the same rule: all of
3317 // them cover this span, so one id over the lot stays consistent.
3318 let old = [x.link, y.link];
3319 for data in &mut self.lanes {
3320 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3321 if old.contains(&c.link) {
3322 c.link = Some(id);
3323 }
3324 }
3325 }
3326 // And the two themselves, which a `place` may have left in no group.
3327 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3328 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3329 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3330 Ok(())
3331 }
3332
3333 /// Put every placement the picks name into one group -- the group a hand
3334 /// builds with ctrl-click and a menu: the picture, its sound and the
3335 /// caption over it, on as many lanes as the picks name. What any of them
3336 /// was already grouped with rides along (one group, not two sharing a
3337 /// member), and the members keep their own spans: a group is one id over
3338 /// one placement per lane, and the offsets between them are what the group
3339 /// preserves -- a drag, a trim and a delete all move the members *by the
3340 /// same distance*, not to the same frames.
3341 ///
3342 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3343 /// and the refusal says which lane -- and a pick that names nothing is
3344 /// refused with its own words. At least two picks, or there is nothing to
3345 /// group.
3346 ///
3347 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3348 /// apart again. None of the refusals changes anything or costs an undo
3349 /// step.
3350 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3351 if picks.len() < 2 {
3352 return Err("a group is two placements or more: pick another one first".into());
3353 }
3354 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3355 for &(lane, idx) in picks {
3356 if seen.contains(&lane) {
3357 return Err(format!(
3358 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3359 track",
3360 lane.label()
3361 )
3362 .into());
3363 }
3364 seen.push(lane);
3365 let there = if lane.kind == LaneKind::Subtitle {
3366 idx < self.sub_lane(lane).len()
3367 } else {
3368 idx < self.lane(lane).len()
3369 };
3370 if !there {
3371 let what = if lane.kind == LaneKind::Subtitle {
3372 "subtitle"
3373 } else {
3374 "clip"
3375 };
3376 return Err(
3377 format!("there is no {what} {idx} on {}", lane.label()).into()
3378 );
3379 }
3380 }
3381 let links: Vec<Option<u32>> = picks
3382 .iter()
3383 .map(|&(lane, idx)| {
3384 if lane.kind == LaneKind::Subtitle {
3385 self.sub_lane(lane)[idx].link
3386 } else {
3387 self.lane(lane)[idx].link
3388 }
3389 })
3390 .collect();
3391 // The picks are already one per lane (`seen`, above), but a pick's
3392 // *existing* group can carry a second member onto a lane another
3393 // pick (or another existing group in the merge) already occupies --
3394 // two captions on one sub lane, say, each grouped with a different
3395 // clip before this call. Merging both in would leave that lane with
3396 // two members of one id, which `links_are_consistent` may never see:
3397 // refused by name, before anything moves, rather than a group closed
3398 // broken.
3399 let labels = handles(&self.lanes);
3400 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3401 for (li, data) in self.lanes.iter().enumerate() {
3402 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3403 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3404 if n > 0 {
3405 per_lane.insert(li, n as u32);
3406 }
3407 }
3408 // A pick that carries no link of its own is invisible to the scan
3409 // above (there is no `Some` to match): it still claims its lane.
3410 for &(lane, _) in picks {
3411 let li = self.index(lane).expect("checked above");
3412 per_lane.entry(li).or_insert(0);
3413 if !self.lanes[li]
3414 .clips
3415 .iter()
3416 .any(|c| c.link.is_some() && links.contains(&c.link))
3417 && !self.lanes[li]
3418 .subs
3419 .iter()
3420 .any(|s| s.link.is_some() && links.contains(&s.link))
3421 {
3422 *per_lane.get_mut(&li).expect("just inserted") += 1;
3423 }
3424 }
3425 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3426 return Err(format!(
3427 "a group is one placement per lane: merging these groups would put two on {}",
3428 labels[li].label()
3429 )
3430 .into());
3431 }
3432 self.snapshot();
3433 let id = self.new_link();
3434 // Whatever any pick was grouped with comes along, for [`group`]'s
3435 // reason -- one id over the lot, not two groups sharing a member.
3436 for data in &mut self.lanes {
3437 for c in data.clips.iter_mut() {
3438 if c.link.is_some() && links.contains(&c.link) {
3439 c.link = Some(id);
3440 }
3441 }
3442 for s in data.subs.iter_mut() {
3443 if s.link.is_some() && links.contains(&s.link) {
3444 s.link = Some(id);
3445 }
3446 }
3447 }
3448 // And the picks themselves, which a `place` may have left in no group.
3449 // The lane seats are read before the walk, which holds the lanes.
3450 let seats: Vec<(usize, bool)> = picks
3451 .iter()
3452 .map(|&(lane, _)| {
3453 (
3454 self.index(lane).expect("checked above"),
3455 lane.kind == LaneKind::Subtitle,
3456 )
3457 })
3458 .collect();
3459 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3460 let _ = lane;
3461 if sub {
3462 self.lanes[at].subs[idx].link = Some(id);
3463 } else {
3464 self.lanes[at].clips[idx].link = Some(id);
3465 }
3466 }
3467 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3468 Ok(())
3469 }
3470
3471 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3472 /// lands on and leaving every other clip exactly where it is -- the
3473 /// per-lane paste. Anything already there is trimmed away (and split in two
3474 /// if `clip` lands inside it), which is what keeps the lane sorted and
3475 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3476 /// gap. Refused only for an empty `clip`.
3477 ///
3478 /// The placement belongs to no group: a clipboard clip carries the link id
3479 /// of the take it was copied from, and placing it twice -- or placing a copy
3480 /// back over the clip it came from -- would put that id on two clips of one
3481 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3482 /// `None` rather than a fresh id because a one-lane placement has nothing on
3483 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3484 /// become a group again.
3485 ///
3486 /// Refused for an empty `clip`, for a lane that is not there, and for a
3487 /// subtitle lane, which carries no picture and no sound
3488 /// ([`Project::place_sub`] is its door).
3489 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3490 if clip.out_frame <= clip.in_frame
3491 || lane.kind == LaneKind::Subtitle
3492 || self.index(lane).is_none()
3493 {
3494 return false;
3495 }
3496 self.snapshot();
3497 let clip = Clip {
3498 fade_in: 0,
3499 fade_out: 0,
3500 transition_out: 0,
3501 start: timeline_frame,
3502 link: None,
3503 ..clip
3504 };
3505 self.insert_over(lane, clip);
3506 true
3507 }
3508
3509 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3510 /// one grouped take -- what a picture let go over a further video track
3511 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3512 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3513 /// this half a file with sound landed on a layer silent, and the only way to
3514 /// hear it was to drop it a second time on an audio lane.
3515 ///
3516 /// Both halves overwrite what they land on and neither ripples, exactly as
3517 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3518 /// nothing under it moves. One history snapshot for the pair, the added lane
3519 /// included, so one [`Project::undo`] takes the whole placement back. The two
3520 /// carry one link, which is what makes them one take to a drag, a trim and a
3521 /// save.
3522 ///
3523 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3524 /// there or is not a video lane: sound placed alone is
3525 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3526 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3527 if clip.out_frame <= clip.in_frame
3528 || lane.kind != LaneKind::Video
3529 || self.index(lane).is_none()
3530 {
3531 return false;
3532 }
3533 self.snapshot();
3534 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3535 // an ord names a lane only while every ord below it does.
3536 while self.lane_count(LaneKind::Audio) <= lane.ord {
3537 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3538 }
3539 let clip = Clip {
3540 fade_in: 0,
3541 fade_out: 0,
3542 transition_out: 0,
3543 start: timeline_frame,
3544 link: Some(self.new_link()),
3545 ..clip
3546 };
3547 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3548 self.insert_over(half, clip);
3549 }
3550 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3551 true
3552 }
3553
3554 /// `clip` into `lane` at its own start, over whatever it lands on: the
3555 /// insert both placement doors make, which is what keeps a lane sorted and
3556 /// disjoint. The caller has checked that the lane is there.
3557 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3558 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3559 clear(clips, clip.start, clip.end());
3560 let idx = clips.partition_point(|c| c.start < clip.start);
3561 clips.insert(idx, clip);
3562 debug_assert!(sorted_disjoint(clips));
3563 }
3564
3565 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3566 /// frame `start`: the drag that rearranges takes, along a track and across
3567 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3568 /// was. `start` at the clip's own is the pure lane change.
3569 ///
3570 /// The whole group travels the same distance, each half on the lane it
3571 /// already sits on -- a link means "these cover one span on however many
3572 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3573 /// sound would be a group no save could load. Only the dragged half changes
3574 /// lane, and that is not a desync: a link names no lane at all.
3575 ///
3576 /// `start` is **clamped**, never refused, to the room the group has: no
3577 /// member crosses a neighbour on the lane it lands on, exactly as
3578 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3579 /// dragging past a neighbour means "as far as it goes", and butting up
3580 /// against the take next door is how clips are laid end to end. The
3581 /// tightest member's wall wins, so a sound half boxed in between two others
3582 /// holds its picture still.
3583 ///
3584 /// Refused, changing nothing and costing no undo step, for a lane that is
3585 /// not there, an index that is not there, a move across *kinds* (a picture
3586 /// cannot play on an audio lane, and the save it wrote would not open
3587 /// again), a head let go *inside* another clip or into a gap too narrow to
3588 /// hold this one -- a move that overwrote what it landed on would destroy a
3589 /// take the pointer never named, which is what [`place`](Project::place)
3590 /// may do and a drag may not -- a half let go onto the lane its own partner
3591 /// is on, and a drop that changes neither lane nor frame, which is a clip
3592 /// picked up and put back down, i.e. a click.
3593 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3594 self.move_selection(&[(from, idx)], from, idx, to, start)
3595 }
3596
3597 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
3598 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
3599 /// reads it) travels the same distance as the clip at `idx` of `from`,
3600 /// which alone changes lane, onto `to`. One clamp across the whole set
3601 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
3602 /// neighbour that boxes in *any* member narrows the delta every member
3603 /// moves by, and a member with no room at all (`lo > hi`) refuses the
3604 /// whole set rather than moving the rest and leaving that one behind.
3605 /// `move_clip` is this with a selection of one -- the dragged clip's own
3606 /// group and nothing else -- so a drag on a clip outside the selection is
3607 /// byte-identical to before this existed.
3608 pub fn move_selection(
3609 &mut self,
3610 picks: &[(Lane, usize)],
3611 from: Lane,
3612 idx: usize,
3613 to: Lane,
3614 start: u32,
3615 ) -> bool {
3616 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3617 return false;
3618 };
3619 if from.kind != to.kind {
3620 return false;
3621 }
3622 let held = self.index(from).expect("the clip was found on it");
3623 // Every pick's own group, unioned: the whole selection moves as one,
3624 // and a pick's link partners (not themselves picked) come along with
3625 // it exactly as a lone drag's do.
3626 let mut members = Members::default();
3627 for &(lane, i) in picks {
3628 let Some(group) = self.group_of(lane, i) else {
3629 continue;
3630 };
3631 for m in group.clips {
3632 if !members.clips.contains(&m) {
3633 members.clips.push(m);
3634 }
3635 }
3636 for m in group.subs {
3637 if !members.subs.contains(&m) {
3638 members.subs.push(m);
3639 }
3640 }
3641 }
3642 if !members.clips.contains(&(held, idx)) {
3643 members.clips.push((held, idx));
3644 }
3645 // The two halves of *the dragged clip's own* group would land on one
3646 // span of one lane, which is the one thing a link may never mean --
3647 // checked against that group alone, not the whole moving set: an
3648 // unlinked fellow pick already sitting on `dest` is no conflict at
3649 // all, since it travels by the same delta and `move_room` below
3650 // leaves it the room to. Refused rather than clamped: the partner
3651 // moves the same distance, so there is no room for it anywhere on
3652 // that lane.
3653 let own_group = self.group_of(from, idx).expect("the clip was found");
3654 if dest != held
3655 && own_group
3656 .clips
3657 .iter()
3658 .chain(&own_group.subs)
3659 .any(|&(l, _)| l == dest)
3660 {
3661 return false;
3662 }
3663 let want = i64::from(start) - i64::from(clip.start);
3664 // How far the group may travel, in timeline frames and signed: every
3665 // member -- the clips and any caption grouped with them -- narrows it
3666 // to the gap it is landing in, and what is left is what the pointer is
3667 // clamped to.
3668 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3669 return false;
3670 };
3671 if lo > hi {
3672 return false;
3673 }
3674 let delta = want.clamp(lo, hi);
3675 if delta == 0 && dest == held {
3676 return false;
3677 }
3678 self.snapshot();
3679 for &(l, i) in &members.clips {
3680 let c = &mut self.lanes[l].clips[i];
3681 // In range by the walls above, which are `u32` frames throughout.
3682 c.start = (i64::from(c.start) + delta) as u32;
3683 }
3684 for &(l, i) in &members.subs {
3685 let s = &mut self.lanes[l].subs[i];
3686 s.start = (i64::from(s.start) + delta) as u32;
3687 }
3688 if dest != held {
3689 let clip = self.lanes[held].clips.remove(idx);
3690 let clips = &mut self.lanes[dest].clips;
3691 let at = clips.partition_point(|c| c.start < clip.start);
3692 clips.insert(at, clip);
3693 }
3694 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3695 debug_assert!(members
3696 .clips
3697 .iter()
3698 .chain(&members.subs)
3699 .all(|&(l, _)| {
3700 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3701 }));
3702 true
3703 }
3704
3705 /// How far a group drag may travel, `(least, most)` in timeline frames and
3706 /// signed: every member narrows the range to the gap it is landing in --
3707 /// the clips against their lanes' clips and the captions against their
3708 /// lanes' captions -- and what is left is what the pointer is clamped to.
3709 /// `travelling` names the one member that changes lane, if any: the clip a
3710 /// hand is carrying onto another track, whose walls are read on the lane it
3711 /// is let go over at the frame the pointer named. `None` when a member has
3712 /// no gap to land in at all.
3713 fn move_room(
3714 &self,
3715 members: &Members,
3716 travelling: Option<(usize, usize, usize, u32)>,
3717 ) -> Option<(i64, i64)> {
3718 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3719 for &(l, i) in members.clips.iter().chain(&members.subs) {
3720 let sub = members.subs.contains(&(l, i));
3721 let (start, frames) = match self.lanes[l]
3722 .clips
3723 .get(i)
3724 .filter(|_| !sub)
3725 .map(|c| (c.start, c.frames()))
3726 {
3727 Some(pair) => pair,
3728 None => {
3729 let s = self.lanes[l].subs.get(i)?;
3730 (s.start, s.frames)
3731 }
3732 };
3733 let land = travelling
3734 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3735 .map_or(l, |(_, _, dest, _)| dest);
3736 // Which gap this member's walls are read off: its own place on the
3737 // lane it stays on, and the frame the pointer named on the lane it
3738 // is let go over. A clip's neighbours are the clips of the lane it
3739 // lands on and a caption's are its captions -- the two lists of one
3740 // lane never meet.
3741 let at = match travelling {
3742 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3743 _ => start,
3744 };
3745 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3746 let neighbours: Vec<(u32, u32)> = if sub {
3747 self.lanes[land]
3748 .subs
3749 .iter()
3750 .map(|s| (s.start, s.end()))
3751 .collect()
3752 } else {
3753 self.lanes[land]
3754 .clips
3755 .iter()
3756 .map(|c| (c.start, c.end()))
3757 .collect()
3758 };
3759 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3760 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3761 continue;
3762 }
3763 if *other_start <= at && at < *other_end {
3764 // A head let go inside another placement, which a clamp
3765 // has no answer for: the drop is refused.
3766 return None;
3767 }
3768 match other_end <= &at {
3769 true => wall_lo = wall_lo.max(*other_end),
3770 false => wall_hi = wall_hi.min(*other_start),
3771 }
3772 }
3773 if wall_hi - wall_lo < frames {
3774 return None;
3775 }
3776 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3777 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3778 }
3779 Some((lo, hi))
3780 }
3781
3782 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3783 /// the drag on a clip's end that makes it play more or less of its source.
3784 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3785 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3786 /// is room that was already empty. One snapshot, so a whole drag is one
3787 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3788 /// sample. Changes the timeline->source mapping: the caller must reseek.
3789 ///
3790 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3791 /// exactly what they played before, which is what makes this a trim and not
3792 /// a slip.
3793 ///
3794 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3795 /// legal means "as far as it goes", and stopping the box there is the
3796 /// affordance. The walls are: one frame of clip always survives, an edge
3797 /// never crosses the neighbouring clip on its own lane, an in-point never
3798 /// walks back past the source's first frame, and an out-point never runs
3799 /// past `source_frames[clip.source]` -- the caller's table of how long each
3800 /// source actually is ([`Project`] does not know, and a clip ending past its
3801 /// file's last frame is a save that will not open again; see
3802 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3803 /// there may not grow at all.
3804 ///
3805 /// Linked placements trim *together*, by one delta: every member's same
3806 /// edge moves the distance the dragged one did, clamped to the room its
3807 /// own walls leave -- offsets between the members of a hand-built group
3808 /// survive the trim, exactly as they survive a drag.
3809 ///
3810 /// `false`, changing nothing and costing no undo step, for an index that is
3811 /// not there and for an edge that is already where it was asked to go.
3812 pub fn trim(
3813 &mut self,
3814 lane: Lane,
3815 idx: usize,
3816 edge: Edge,
3817 to: u32,
3818 source_frames: &[u32],
3819 ) -> bool {
3820 let (Some((lo, hi)), Some(clip)) = (
3821 self.trim_room(lane, idx, edge, source_frames),
3822 self.lane(lane).get(idx).copied(),
3823 ) else {
3824 return false;
3825 };
3826 let to = to.clamp(lo, hi);
3827 let at = match edge {
3828 Edge::Start => clip.start,
3829 Edge::End => clip.end(),
3830 };
3831 if to == at {
3832 return false;
3833 }
3834 // Worked out before anything moves: at a slow rate a room can be too
3835 // narrow to hold even one source frame ([`Speed::fit`]), and the
3836 // dragged clip refusing to fit must refuse the whole gesture rather
3837 // than be given a range wider than its room -- which is the overlap
3838 // the lane invariant exists to forbid. The walls below leave that room,
3839 // so this is the backstop for a project that came in through another
3840 // door.
3841 let room = match edge {
3842 // The frames that stay play what they played, so what survives is
3843 // measured from the *end*.
3844 Edge::Start => clip.end() - to,
3845 Edge::End => to - clip.start,
3846 };
3847 let Some(keep) = clip.speed.fit(room) else {
3848 return false;
3849 };
3850 let members = self.group_of(lane, idx).expect("checked above");
3851 self.snapshot();
3852 let still = self.is_still(&clip);
3853 let held = self.index(lane).expect("checked above");
3854 let c = &mut self.lanes[held].clips[idx];
3855 match edge {
3856 // A still has no earlier frame to walk an in-point back to --
3857 // every frame of it is the same picture -- so its head grows
3858 // *forward*: the range it plays is however long the new room is,
3859 // anchored at the source's frame 0. Bounded by `lo`, which is where
3860 // the cap in `source_frames` is applied.
3861 Edge::Start if still => {
3862 c.in_frame = 0;
3863 c.out_frame = keep;
3864 c.start = to;
3865 }
3866 Edge::Start => {
3867 // Non-negative by `lo`, which is what keeps the in-point on the
3868 // source.
3869 c.in_frame = c.out_frame - keep.min(c.out_frame);
3870 c.start = to;
3871 }
3872 // Never wider than the room the edge was clamped to: see
3873 // [`Speed::fit`].
3874 Edge::End => c.out_frame = c.in_frame + keep,
3875 }
3876 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3877 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3878 true
3879 }
3880
3881 /// The rest of a group after one member's `edge` has moved by `delta`:
3882 /// every other member's same edge moves the same distance, clamped to the
3883 /// room its own walls leave -- a clip's against its lane and its source,
3884 /// a caption's against its own lane, its window following by the
3885 /// placement's own proportion. The undo step is the caller's: this is the
3886 // second half of one edit, not an edit of its own.
3887 fn follow_group(
3888 &mut self,
3889 members: &Members,
3890 dragged: &(usize, usize),
3891 edge: Edge,
3892 delta: i64,
3893 source_frames: &[u32],
3894 ) {
3895 for &(l, i) in &members.clips {
3896 if (l, i) == *dragged {
3897 continue;
3898 }
3899 let c = self.lanes[l].clips[i];
3900 let at = match edge {
3901 Edge::Start => c.start,
3902 Edge::End => c.end(),
3903 };
3904 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3905 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3906 if to == at {
3907 continue;
3908 }
3909 let room = match edge {
3910 Edge::Start => c.end() - to,
3911 Edge::End => to - c.start,
3912 };
3913 let Some(keep) = c.speed.fit(room) else {
3914 continue;
3915 };
3916 let still = self.is_still(&self.lanes[l].clips[i]);
3917 let c = &mut self.lanes[l].clips[i];
3918 match edge {
3919 Edge::Start if still => {
3920 c.in_frame = 0;
3921 c.out_frame = keep;
3922 c.start = to;
3923 }
3924 Edge::Start => {
3925 c.in_frame = c.out_frame - keep.min(c.out_frame);
3926 c.start = to;
3927 }
3928 Edge::End => c.out_frame = c.in_frame + keep,
3929 }
3930 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3931 }
3932 for &(l, i) in &members.subs {
3933 if (l, i) == *dragged {
3934 continue;
3935 }
3936 let s = self.lanes[l].subs[i];
3937 let at = match edge {
3938 Edge::Start => s.start,
3939 Edge::End => s.end(),
3940 };
3941 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3942 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3943 if to == at {
3944 continue;
3945 }
3946 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3947 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3948 }
3949 }
3950
3951 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3952 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3953 /// What a front-end drawing the box *during* a drag asks, so the live width
3954 /// is the width the release will commit and an edge stops under the pointer
3955 /// rather than snapping back. The **clip's own** walls: the rest of its
3956 /// group follows by the same delta within their own ([`follow_group`]), so
3957 /// what is drawn for the dragged edge is what its own clip will commit.
3958 /// `None` for an index that is not there.
3959 pub fn trim_room(
3960 &self,
3961 lane: Lane,
3962 idx: usize,
3963 edge: Edge,
3964 source_frames: &[u32],
3965 ) -> Option<(u32, u32)> {
3966 let l = self.index(lane)?;
3967 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3968 }
3969
3970 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3971 /// its lane's storage index: the one wall computation, asked for the clip
3972 /// itself and for each member a group trim carries.
3973 fn clip_room(
3974 &self,
3975 l: usize,
3976 i: usize,
3977 edge: Edge,
3978 source_frames: &[u32],
3979 ) -> (u32, u32) {
3980 let clips = &self.lanes[l].clips;
3981 let c = clips[i];
3982 let (lo, hi) = match edge {
3983 Edge::Start => (
3984 // Back to the source's own first frame -- as many *timeline*
3985 // frames as that head is worth at the clip's rate, which at
3986 // real time is the head itself -- and never over the clip in
3987 // front of it. Saturating because a clip may hold *more*
3988 // head than the timeline has room for -- a ripple delete
3989 // slides a clip back to frame 0 with its in-point wherever
3990 // the cut left it -- and frame 0 is the other wall.
3991 //
3992 // A still is measured from its *tail* instead: it has no
3993 // in-point worth the name (every frame the same picture), so
3994 // its head reaches exactly as far as its tail does -- out to
3995 // the length the caller's table gives it, whole. Measured
3996 // from the in-point it would have no head room at all, which
3997 // is a placed picture whose left edge cannot be dragged out.
3998 // No entry in the table means no growth, as it does at the
3999 // other end.
4000 if self.is_still(&c) {
4001 c.end().saturating_sub(
4002 c.speed
4003 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
4004 )
4005 } else {
4006 c.start.saturating_sub(c.speed.room(c.in_frame))
4007 }
4008 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
4009 // One *frame of clip* always survives, and at a rate below
4010 // real time one frame of clip is several frames of timeline
4011 // ([`Speed::room`]): an edge dragged closer than that would
4012 // ask for a range no source frame fits in. At real time this
4013 // is `end - 1`, unchanged.
4014 c.end() - c.speed.room(1),
4015 ),
4016 Edge::End => (
4017 // ...and the same wall from the other end: the shortest this
4018 // clip can be is the room one source frame of it takes.
4019 c.start + c.speed.room(1),
4020 // Out to whatever is left of the source -- again in timeline
4021 // frames, at this clip's rate -- and never over the clip
4022 // behind it.
4023 c.start
4024 .saturating_add(
4025 c.speed.room(
4026 source_frames
4027 .get(c.source)
4028 .copied()
4029 .unwrap_or(c.out_frame)
4030 .saturating_sub(c.in_frame),
4031 ),
4032 )
4033 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
4034 ),
4035 };
4036 // `hi.max(lo)`: for a clip the invariants hold for, the range always
4037 // contains the edge's own place, and a caller's wrong `source_frames`
4038 // must not become an empty range (or a panicking `clamp`) here.
4039 (lo, hi.max(lo))
4040 }
4041
4042 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
4043 /// every frame is the same picture, so which frame of it a clip's in-point
4044 /// names is not a question -- what [`Project::trim`] lets grow at either
4045 /// end. `false` for a source that is not there.
4046 fn is_still(&self, clip: &Clip) -> bool {
4047 self.sources
4048 .get(clip.source)
4049 .is_some_and(|s| crate::is_image(&s.path))
4050 }
4051
4052 /// The placements that move as one with the one at `idx` of `lane` --
4053 /// itself and whatever carries its link, on the media lanes and the
4054 /// subtitle ones alike. `None` for an index that is not there.
4055 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
4056 let sub = lane.kind == LaneKind::Subtitle;
4057 let link = if sub {
4058 self.sub_lane(lane).get(idx)?.link
4059 } else {
4060 self.lane(lane).get(idx)?.link
4061 };
4062 let mut members = Members::default();
4063 match link {
4064 Some(link) => {
4065 for (l, data) in self.lanes.iter().enumerate() {
4066 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
4067 members.clips.push((l, i));
4068 }
4069 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
4070 members.subs.push((l, i));
4071 }
4072 }
4073 }
4074 None => {
4075 let l = self.index(lane).expect("the placement was found on it");
4076 if sub {
4077 members.subs.push((l, idx));
4078 } else {
4079 members.clips.push((l, idx));
4080 }
4081 }
4082 }
4083 Some(members)
4084 }
4085
4086 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4087 /// new group, pushing everything from there on later by its length in
4088 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4089 /// the clip it lands in is split around it; past the end of the timeline it
4090 /// goes down where it was asked for, with black in front of it -- which is
4091 /// what a library row let go on the open bed means, and what the ghost under
4092 /// the pointer promised. A clipboard means "put it here", not "here and
4093 /// black in front", and clamps to the end at its own door
4094 /// ([`crate::PlaybackSession::paste_at`]).
4095 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4096 ///
4097 /// `V1` and `A1` and no other lane, because a take is one picture and one
4098 /// sound: copying it onto every lane there is would play the same audio
4099 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4100 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4101 /// video lane it is a clip that decodes to nothing, and a save carrying one
4102 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4103 /// `V1` only, for the mirror of that reason. The room is still opened on
4104 /// every media lane, or the lanes it was not inserted into would slide out
4105 /// of step with the ones it was -- and the subtitle lanes are left alone:
4106 /// the words keep their own clock, and a caption that should travel with a
4107 /// clip is what a group is for.
4108 ///
4109 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4110 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4111 /// an empty `clip` and for one naming a source that is not there (both of
4112 /// which the public fields let a caller build), and for a paste whose ripple
4113 /// would push a clip past the last frame there is -- nothing is changed by
4114 /// any of them.
4115 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4116 let Some(source) = self.sources.get(clip.source) else {
4117 return false;
4118 };
4119 if clip.out_frame <= clip.in_frame {
4120 return false;
4121 }
4122 let audio_only = crate::is_audio(&source.path);
4123 // ...and its mirror: a still is a picture and no sound, so a copy of one
4124 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4125 // worker tries to demux -- which silences the *whole session*, not just
4126 // that clip -- and a save the engine's own `open_project` then refuses.
4127 let picture_only = crate::is_image(&source.path);
4128 // The frame it was asked for and no other: a row let go on the empty
4129 // bed past the last clip lands *there*, under the ghost that promised
4130 // it, with black in front. Clamping to the end here made every drop on
4131 // open bed an append -- the clipboard's rule, applied to a hand that
4132 // had named a place.
4133 let at = timeline_frame;
4134 // The room it takes on the timeline, which its speed decides -- not the
4135 // source range it reads.
4136 let len = clip.frames();
4137 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4138 // hand-written file may hold a clip that ends at the very last frame
4139 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4140 // rather than wrapped there -- a wrapped start lands *behind* the clip
4141 // it belongs after, which is an overlap no save will read back.
4142 if at.checked_add(len).is_none()
4143 || self
4144 .lanes
4145 .iter()
4146 .flat_map(|l| &l.clips)
4147 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4148 {
4149 return false;
4150 }
4151 // ...and room *to open*: the paste splits whatever it lands inside of,
4152 // and a speeded clip can only be cut where its own rate has a source
4153 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4154 // of one, which is the overlap a lane may never hold. At real time every
4155 // frame answers, so this cannot refuse an unspeeded paste.
4156 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4157 if self
4158 .lanes
4159 .iter()
4160 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4161 {
4162 return false;
4163 }
4164 self.snapshot();
4165 let clip = Clip {
4166 fade_in: 0,
4167 fade_out: 0,
4168 transition_out: 0,
4169 start: at,
4170 link: Some(self.new_link()),
4171 ..clip
4172 };
4173 // Only lanes that can play the source: a file with no picture belongs on
4174 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4175 // it for an import. On a video lane it would decode to nothing, and the
4176 // save it wrote would not open again.
4177 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4178 (true, _) => &[LaneKind::Audio],
4179 (_, true) => &[LaneKind::Video],
4180 _ => &[LaneKind::Video, LaneKind::Audio],
4181 };
4182 let takes: Vec<usize> = kinds
4183 .iter()
4184 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4185 .collect();
4186 for (i, data) in self.lanes.iter_mut().enumerate() {
4187 open_room(&mut data.clips, at, len);
4188 // The subtitle lanes are NOT touched: a paste inserts media, and
4189 // the words keep their own clock. Opening room here used to split
4190 // a caption the paste landed inside and slide the rest behind it
4191 // -- "a caption that stayed put while the picture moved on no
4192 // longer says the same thing" -- but a caption pinned to nothing
4193 // (and a video arriving on a timeline of words alone) has no
4194 // picture to follow, and the split did to the words what no hand
4195 // asked for. A caption that should travel with a clip is what a
4196 // group is for, and a group moves as one.
4197 if takes.contains(&i) {
4198 let idx = data.clips.partition_point(|c| c.start < at);
4199 data.clips.insert(idx, clip);
4200 }
4201 debug_assert!(sorted_disjoint(&data.clips));
4202 debug_assert!(subs_sorted_disjoint(&data.subs));
4203 }
4204 true
4205 }
4206
4207 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
4208 /// `items` lands on the lane it names, its head moved by the offset every
4209 /// other item moves by too -- `at` less the earliest `start` among them,
4210 /// so the set's own gaps and lane assignment survive the trip from
4211 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
4212 /// way a lone clip's copy does.
4213 ///
4214 /// All-or-nothing, and **refused** rather than opening room or splitting
4215 /// a neighbour the way [`paste`](Project::paste) does for one clip:
4216 /// a set-paste never ripples the bed, so a landing that overlaps so much
4217 /// as one existing clip on its own lane refuses the whole set, changing
4218 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
4219 /// clamps instead of refusing, but a paste has no drag to clamp against,
4220 /// and a landing moved off the frame asked for is not what a paste means.
4221 /// `items` empty, naming a lane or a source that is not there, or a clip
4222 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
4223 ///
4224 /// Exactly one history snapshot for the whole set, so one
4225 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
4226 /// on every lane an item lands on: the caller must reseek.
4227 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
4228 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
4229 return false;
4230 };
4231 // Resolved once, up front, off the lanes as they stand now: a lane or
4232 // source that is not there, or a landing that would overlap a
4233 // neighbour, refuses the whole set before any of it is written.
4234 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
4235 for &(lane, clip) in items {
4236 let Some(li) = self.index(lane) else {
4237 return false;
4238 };
4239 if self.sources.get(clip.source).is_none() || clip.out_frame <= clip.in_frame {
4240 return false;
4241 }
4242 let delta = i64::from(clip.start) - i64::from(anchor);
4243 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
4244 return false;
4245 };
4246 let Some(end) = start.checked_add(clip.frames()) else {
4247 return false;
4248 };
4249 if self.lanes[li]
4250 .clips
4251 .iter()
4252 .any(|c| c.start < end && start < c.end())
4253 {
4254 return false;
4255 }
4256 landings.push((li, Clip { start, ..clip }));
4257 }
4258 self.snapshot();
4259 for (li, mut clip) in landings {
4260 clip.link = Some(self.new_link());
4261 clip.fade_in = 0;
4262 clip.fade_out = 0;
4263 clip.transition_out = 0;
4264 let clips = &mut self.lanes[li].clips;
4265 let idx = clips.partition_point(|c| c.start < clip.start);
4266 clips.insert(idx, clip);
4267 }
4268 true
4269 }
4270
4271 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4272 /// silence, and nothing else moves. Refused only for an out-of-range index
4273 /// (which a lane that is not there always is) -- lifting the last placement
4274 /// there is leaves an *empty* timeline, which is a state the project holds
4275 /// like any other and an undo brings back.
4276 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4277 if idx >= self.lane(lane).len() {
4278 return false;
4279 }
4280 self.snapshot();
4281 self.lane_mut(lane).expect("checked above").remove(idx);
4282 true
4283 }
4284
4285 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4286 /// the hole: everything after slides back by `len`. The rippling delete --
4287 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4288 /// empty range; a delete that leaves nothing behind empties the timeline,
4289 /// which is a state like any other and one undo away.
4290 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4291 if len == 0 {
4292 return false;
4293 }
4294 // Nothing reaches past `at`: there is nothing to cut and nothing to
4295 // slide back, and a delete that changes nothing must not cost an undo
4296 // step (see [`snapshot`](Project::snapshot)).
4297 if !self
4298 .lanes
4299 .iter()
4300 .flat_map(|l| &l.clips)
4301 .any(|c| c.end() > at)
4302 {
4303 return false;
4304 }
4305 self.snapshot();
4306 let on = all_lanes(&self.lanes);
4307 ripple(&mut self.lanes, &on, at, len);
4308 true
4309 }
4310
4311 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
4312 /// a right-click on empty bench space names before offering to close it.
4313 /// `None` when `frame` sits inside a placement, or past the last one: the
4314 /// open end of a lane is not a gap, since there is nothing after it to slide
4315 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
4316 /// the media [`Clip`] list they deliberately never hold.
4317 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
4318 let data = self.index(lane).map(|i| &self.lanes[i])?;
4319 match data.kind {
4320 LaneKind::Subtitle => gap(&data.subs, frame),
4321 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
4322 }
4323 }
4324
4325 /// How many bounded holes `lane` holds. The open end after the last
4326 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
4327 /// it would move nothing.
4328 pub fn gap_count(&self, lane: Lane) -> usize {
4329 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
4330 return 0;
4331 };
4332 match data.kind {
4333 LaneKind::Subtitle => gaps(&data.subs).len(),
4334 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
4335 }
4336 }
4337
4338 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4339 /// together to keep sync -- what a right-click on empty bench space asks
4340 /// before the menu offers to close it, and what widens
4341 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
4342 /// named to the whole take the gap might be half of.
4343 ///
4344 /// A clip bordering the gap on `lane` -- the one ending where it starts,
4345 /// the one starting where it ends -- carries a link when it is one take
4346 /// with a clip on another lane. That lane joins the scope only when the
4347 /// *exact same* stretch is empty there too (same start, same length): the
4348 /// ripple then removes nothing but silence, on every lane it touches, and
4349 /// both halves stay the length they always were. A link whose partner
4350 /// lane is not empty there -- a gap of a different length, or none at all
4351 /// -- is named back to the caller rather than silently widened past
4352 /// (which would cut real media out of a lane nothing asked to touch) or
4353 /// silently left out (which is the defect this closes: a per-lane ripple
4354 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
4355 /// to refuse it after the fact, on the very half this could have carried
4356 /// along).
4357 ///
4358 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
4359 /// partner clip sits on another lane -- the unlinked case, untouched.
4360 ///
4361 /// Subtitle lanes have no media take halves to inspect. A caption can be
4362 /// hand-grouped with clips, but it is not the imported A/V take this method
4363 /// widens for, so a subtitle gap stays scoped to its own lane; the later
4364 /// scoped cut still refuses an explicit group split.
4365 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4366 let Some(li) = self.index(lane) else {
4367 return Err("no track to work on".into());
4368 };
4369 let labels = handles(&self.lanes);
4370 let end = start + frames;
4371 let mut scope = vec![lane];
4372 for c in self.lanes[li]
4373 .clips
4374 .iter()
4375 .filter(|c| c.end() == start || c.start == end)
4376 {
4377 let Some(id) = c.link else { continue };
4378 for (j, data) in self.lanes.iter().enumerate() {
4379 if j == li {
4380 continue;
4381 }
4382 let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else {
4383 continue;
4384 };
4385 match gap(&data.clips, start) {
4386 Some((s, f)) if s == start && f == frames => {
4387 let other = labels[j];
4388 if !scope.contains(&other) {
4389 scope.push(other);
4390 }
4391 }
4392 _ => {
4393 return Err(format!(
4394 "the {} clip at frame {} is one take with the {} clip at frame {}: \
4395 closing this gap alone would pull the take out of sync -- close {}'s \
4396 gap there too, or detach them first",
4397 labels[li].label(),
4398 c.start,
4399 labels[j].label(),
4400 half.start,
4401 labels[j].label()
4402 )
4403 .into());
4404 }
4405 }
4406 }
4407 }
4408 Ok(scope)
4409 }
4410
4411 /// Close every bounded gap on `lane`, as one undo step, without making the
4412 /// lane's scope global. Media lanes use the same take-safety widening
4413 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
4414 /// halves ride along only when their matching lane is empty over that exact
4415 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
4416 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
4417 /// halves of an imported A/V take, so the media take-widening rule has
4418 /// nothing to add there.
4419 ///
4420 /// The walk is back-to-front. Closing a gap shifts everything after it, so
4421 /// later holes must be consumed while their measured starts are still true;
4422 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
4423 /// only before the first successful close, so an all-skipped sweep is not an
4424 /// undo step.
4425 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4426 let Some(i) = self.index(lane) else {
4427 return Err("no track to work on".into());
4428 };
4429 if self.lanes[i].kind == LaneKind::Subtitle {
4430 return Ok(self.close_all_subtitle_gaps_on_lane(i));
4431 }
4432 let mut report = GapSweep::default();
4433 let mut snapshot = false;
4434 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
4435 match self
4436 .gap_take_scope(lane, start, frames)
4437 .and_then(|scope| {
4438 let on = self.scoped(&scope)?;
4439 self.scope_holds_takes_whole(&on, start)?;
4440 Ok(on)
4441 }) {
4442 Ok(on) => {
4443 if !snapshot {
4444 self.snapshot();
4445 snapshot = true;
4446 }
4447 ripple(&mut self.lanes, &on, start, frames);
4448 report.closed += 1;
4449 }
4450 Err(e) => report.skipped.push(GapSkip {
4451 start,
4452 reason: e.to_string(),
4453 }),
4454 }
4455 }
4456 report.skipped.reverse();
4457 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4458 Ok(report)
4459 }
4460
4461 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
4462 /// take-scope widening: a caption is not one half of an A/V take. Explicit
4463 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
4464 /// so a grouped caption is refused rather than pulled away from its group.
4465 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
4466 let mut report = GapSweep::default();
4467 let mut snapshot = false;
4468 let on = [i];
4469 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
4470 match self.scope_holds_takes_whole(&on, start) {
4471 Ok(()) => {
4472 if !snapshot {
4473 self.snapshot();
4474 snapshot = true;
4475 }
4476 ripple(&mut self.lanes, &on, start, frames);
4477 report.closed += 1;
4478 }
4479 Err(e) => report.skipped.push(GapSkip {
4480 start,
4481 reason: e.to_string(),
4482 }),
4483 }
4484 }
4485 report.skipped.reverse();
4486 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4487 report
4488 }
4489
4490 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4491 /// out of the lanes in `scope` and close each hole, as one edit: the
4492 /// jumpcut a silence scan asks for ([`crate::silence`]).
4493 ///
4494 /// A lane that is not in `scope` **does not move**, which is the whole
4495 /// point of the parameter: the silences of a podcast track come out
4496 /// without the music track under it sliding. `scope` is an arbitrary set of
4497 /// lanes and not a kind or a range, so a caller with its own idea of what
4498 /// is selected (a take, a track, everything) says it in lanes and nothing
4499 /// here has to learn about selection.
4500 ///
4501 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4502 /// reason this exists rather than a caller's loop over
4503 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4504 /// undo press, not forty. Cut back to front, so a region's frames still
4505 /// mean what the caller measured while the ones before it are cut.
4506 ///
4507 /// The list is sorted and overlapping entries are merged before anything is
4508 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4509 /// other's frames. Refused, with no undo step, for an empty list, for a
4510 /// scope naming no lane that is there, and -- by name -- when the scope
4511 /// would take one half of a take with it
4512 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4513 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4514 let regions = tidy(regions);
4515 let on = self.scoped(scope)?;
4516 let Some(&(first, _)) = regions.first() else {
4517 return Err("nothing to cut".into());
4518 };
4519 self.scope_holds_takes_whole(&on, first)?;
4520 self.snapshot();
4521 for &(at, len) in regions.iter().rev() {
4522 ripple(&mut self.lanes, &on, at, len);
4523 }
4524 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4525 Ok(())
4526 }
4527
4528 /// The storage indices of `scope`, which is what every batch below walks.
4529 /// `Err` for a scope that names nothing there rather than a silent no-op:
4530 /// an edit asked for on a lane that is not there did not happen, and the
4531 /// caller has to hear so.
4532 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4533 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4534 match on.is_empty() {
4535 true => Err("no track to work on".into()),
4536 false => Ok(on),
4537 }
4538 }
4539
4540 /// The law a scoped ripple lives under: **a group travels as one**, so a
4541 /// batch that moves one half of a take and not the other would leave the
4542 /// halves disagreeing about where they stand -- an offset no hand asked
4543 /// for, and the reason the take's lanes have to be scoped together.
4544 ///
4545 /// Refused by name rather than widened silently. Widening would edit a
4546 /// track the user did not scope, which is exactly the surprise scoping
4547 /// exists to end; a front-end that wants the take is free to *say* the
4548 /// take's lanes, and to name them in what it tells the user afterwards.
4549 ///
4550 /// Only from `from` on: a take sitting entirely before the first cut does
4551 /// not move, so it is not this rule's business.
4552 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4553 let labels = handles(&self.lanes);
4554 // The halves of a group are on either of a lane's lists, and the
4555 // refusal names whichever sits outside the scope -- a clip like it
4556 // always has, and a caption now that a group may hold one.
4557 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4558 let Some(id) = link else {
4559 return Ok(());
4560 };
4561 for (j, data) in self.lanes.iter().enumerate() {
4562 if on.contains(&j) {
4563 continue;
4564 }
4565 let clip = data.clips.iter().find(|o| o.link == Some(id));
4566 let sub = data.subs.iter().find(|s| s.link == Some(id));
4567 if let Some(half) = clip {
4568 return Err(format!(
4569 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4570 moving one track of a take would pull it apart -- take the whole take, \
4571 or detach them first",
4572 labels[j].label(),
4573 half.start
4574 )
4575 .into());
4576 }
4577 if let Some(half) = sub {
4578 return Err(format!(
4579 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4580 moving one track of a take would pull it apart -- take the whole take, \
4581 or detach them first",
4582 labels[j].label(),
4583 half.start
4584 )
4585 .into());
4586 }
4587 }
4588 Ok(())
4589 };
4590 for &i in on {
4591 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4592 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4593 }
4594 // A caption before the first cut does not move, so it is not this
4595 // rule's business -- exactly the clip test's own line.
4596 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4597 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4598 }
4599 }
4600 Ok(())
4601 }
4602
4603 /// Play every one of `regions` at `speed` instead of cutting it: each is
4604 /// split out of whatever covers it, re-rated, and the room it no longer
4605 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4606 /// does not ripple, and a hole where a silence shrank is the one thing this
4607 /// must not leave. One snapshot for the lot, like
4608 /// [`cut_regions`](Project::cut_regions).
4609 ///
4610 /// The rate is **absolute**, not a multiplier on what is there: running it
4611 /// twice over the same stretch leaves it at `speed`, not at `speed`
4612 /// squared, so a second pass over an already-cut timeline changes nothing.
4613 ///
4614 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4615 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4616 ///
4617 /// Refused by name, with nothing changed and no undo step, when:
4618 ///
4619 /// * the scope would take one half of a take with it
4620 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4621 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4622 /// shrink by different amounts and the ripple would pull them apart,
4623 /// which is what cutting does not suffer and why delete mode has no such
4624 /// refusal;
4625 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4626 /// piece could not be split out exactly;
4627 /// * two lanes' pieces would end up different lengths, which is a group
4628 /// whose halves disagree about their span (the refusal
4629 /// [`write_speed`](Project::write_speed) already makes, in its words);
4630 /// * the region would grow rather than shrink, i.e. it already plays faster
4631 /// than `speed`.
4632 pub fn speed_regions(
4633 &mut self,
4634 regions: &[(u32, u32)],
4635 speed: Speed,
4636 scope: &[Lane],
4637 ) -> crate::Result<()> {
4638 let regions = tidy(regions);
4639 let on = self.scoped(scope)?;
4640 let Some(&(first, _)) = regions.first() else {
4641 return Err("nothing to speed up".into());
4642 };
4643 self.scope_holds_takes_whole(&on, first)?;
4644 let labels = handles(&self.lanes);
4645 // Before anything is touched, because this is the refusal a person can
4646 // act on: a clip that laps over the edge of a silence has to be trimmed
4647 // (or the silences cut instead), and saying so after a rollback would
4648 // be saying it about a timeline that already looks different.
4649 for &(at, len) in &regions {
4650 for &l in &on {
4651 for c in &self.lanes[l].clips {
4652 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4653 {
4654 return Err(format!(
4655 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4656 speeding it up would pull the lanes apart -- trim it first, or cut the \
4657 silences out instead",
4658 labels[l].label(),
4659 c.start,
4660 at + len
4661 )
4662 .into());
4663 }
4664 }
4665 }
4666 }
4667 // The rest is checked as it is built: a split's own arithmetic is what
4668 // says whether a rate can address an edge. So the snapshot is taken
4669 // first and *rolled back* on a refusal -- one undo either way, and a
4670 // refusal still costs no step (`undo` pops the one just pushed).
4671 self.snapshot();
4672 for &(at, len) in regions.iter().rev() {
4673 self.write_split(at, false, &on);
4674 self.write_split(at + len, false, &on);
4675 let mut room: Option<(Lane, u32)> = None;
4676 let mut refused = None;
4677 for &l in &on {
4678 let clips = &self.lanes[l].clips;
4679 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4680 if (c.start, c.end()) != (at, at + len) {
4681 // *Which* edge did not come off: a rate that cannot
4682 // address the end of the silence is not a rate that
4683 // cannot address its start, and naming the wrong frame
4684 // sends the user looking in the wrong place.
4685 let edge = match c.start == at {
4686 true => at + len,
4687 false => at,
4688 };
4689 refused = Some(format!(
4690 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4691 detach it, or put it back to 1.00x first",
4692 labels[l].label(),
4693 c.start,
4694 c.speed
4695 ));
4696 continue;
4697 }
4698 let after = speed.frames(c.len());
4699 match room {
4700 None => room = Some((labels[l], after)),
4701 Some((first, n)) if n != after => {
4702 refused = Some(format!(
4703 "at {speed} the {} half of the silence at frame {at} would cover \
4704 {after} frames and the {} half {n}: they are one take and a take \
4705 is one span -- detach them first",
4706 labels[l].label(),
4707 first.label()
4708 ));
4709 }
4710 Some(_) => {}
4711 }
4712 }
4713 }
4714 let shrunk = match (refused, room) {
4715 (Some(e), _) => {
4716 self.undo();
4717 return Err(e.into());
4718 }
4719 // A gap on every lane: nothing to re-rate, and nothing to close.
4720 (None, None) => continue,
4721 (None, Some((_, after))) => after,
4722 };
4723 // The region's new length, on every scoped lane alike.
4724 let after = shrunk;
4725 let Some(delta) = len.checked_sub(shrunk) else {
4726 self.undo();
4727 return Err(format!(
4728 "the silence at frame {at} already plays faster than {speed}: \
4729 at that rate it would be {shrunk} frames instead of {len}"
4730 )
4731 .into());
4732 };
4733 for &l in &on {
4734 for c in &mut self.lanes[l].clips {
4735 if c.start == at && c.end() == at + len {
4736 c.speed = speed;
4737 } else if c.start >= at + len {
4738 c.start -= delta;
4739 }
4740 }
4741 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4742 // The captions on a scoped lane travel with the region's time:
4743 // a piece inside it plays in `after` frames instead of `len`
4744 // -- same words on less timeline, its window untouched, for
4745 // [`write_speed`]'s reason -- and everything behind the region
4746 // slides up by what the region gave back.
4747 //
4748 // The pieces inside re-time by their *boundaries*, not each
4749 // on its own: rounding one piece's start and its neighbour's
4750 // start apart can land both on the same frame (two one-frame
4751 // cues of a thirty-frame region at 2x both want frame 15), so
4752 // the mapped boundaries are walked in order and forced apart
4753 // -- each piece at least one frame, none past the region's own
4754 // new end, where the first follower lands exactly. A rounding
4755 // artifact is clamped, not refused: nothing about the words
4756 // asked for an overlap.
4757 let share = f64::from(after) / f64::from(len).max(1.);
4758 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4759 let mut prev = at;
4760 let subs = &mut self.lanes[l].subs;
4761 for i in 0..subs.len() {
4762 let s = subs[i];
4763 if s.start >= at + len {
4764 subs[i].start = s.start - delta;
4765 } else if s.start >= at && s.end() <= at + len {
4766 let mut start = map(s.start).max(prev);
4767 let end = map(s.end()).max(start + 1).min(at + after);
4768 start = start.min(end - 1);
4769 subs[i].start = start;
4770 subs[i].frames = end - start;
4771 prev = end;
4772 }
4773 }
4774 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4775 }
4776 }
4777 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4778 Ok(())
4779 }
4780
4781 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4782 /// -- the whole-group delete a single-lane front-end means. `false` for a
4783 /// bad index. Changes the mapping: the caller must reseek.
4784 pub fn delete(&mut self, idx: usize) -> bool {
4785 self.delete_in(Lane::V1, idx)
4786 }
4787
4788 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4789 /// in no group (or a group of one, which is the same thing to a delete) is
4790 /// what it always was: its own span cut out of *every* lane, so the
4791 /// timeline closes up under it. A clip in a group takes the group with it,
4792 /// each member by its **own** span and on its **own** lane -- the members
4793 /// keep their offsets, so their spans may disagree, and the lanes may end
4794 /// up out of step with each other, which is inherent to a hand-built group
4795 /// and one undo away. Every member -- clips and captions alike -- goes by
4796 /// the same law: its own span out of its own lane, hole closed; a caption
4797 /// in no group keeps the lift that leaves a gap, which is its own door's
4798 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4799 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4800 /// index, and for a lane that is not there. Changes the mapping: the
4801 /// caller must reseek.
4802 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4803 let Some(members) = self.group_of(lane, idx) else {
4804 return false;
4805 };
4806 if !members.alone() {
4807 return self.delete_members(&members);
4808 }
4809 let Some(clip) = self.lane(lane).get(idx).copied() else {
4810 return false;
4811 };
4812 self.ripple_delete(clip.start, clip.frames())
4813 }
4814
4815 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4816 /// caption in no group lifts, exactly as its own key always made it
4817 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4818 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4819 /// span out of its own lane, hole closed, captions and clips alike.
4820 /// `false` for a bad index.
4821 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4822 let Some(members) = self.group_of(lane, idx) else {
4823 return false;
4824 };
4825 if !members.alone() {
4826 return self.delete_members(&members);
4827 }
4828 self.lift_sub(lane, idx)
4829 }
4830
4831 /// The one whole-group delete both doors land in: every member's own span
4832 /// cut out of its own lane and the hole closed there -- clips and
4833 /// captions by the same law -- and nothing else on another lane moves,
4834 /// which is what keeps one member's ripple from dragging another
4835 /// member's lane out from under it. One snapshot, one undo step.
4836 fn delete_members(&mut self, members: &Members) -> bool {
4837 self.snapshot();
4838 for &(l, i) in &members.clips {
4839 let c = self.lanes[l].clips[i];
4840 ripple(&mut self.lanes, &[l], c.start, c.frames());
4841 }
4842 // The captions go by the same law their clip siblings do -- the span
4843 // out of its own lane, the hole closed -- and not by the lift a
4844 // *lone* caption's delete is: deleted with its group, the words after
4845 // it slide up with everything else, or the lane the group emptied is
4846 // the one lane the delete left a hole in. `ripple` is the one
4847 // mechanism (it clears the span and shifts the rest, clips and
4848 // captions alike); a sub lane holds no clips, so its other list is
4849 // untouched.
4850 for &(l, i) in &members.subs {
4851 let s = self.lanes[l].subs[i];
4852 ripple(&mut self.lanes, &[l], s.start, s.frames);
4853 }
4854 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4855 true
4856 }
4857
4858 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4859 #[cfg(test)]
4860 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4861 self.lane(lane)
4862 }
4863
4864 /// How many undo steps are stacked: what the sweep asks so "one op, one
4865 /// snapshot" is a count and not a guess.
4866 #[cfg(test)]
4867 pub(crate) fn history_len(&self) -> usize {
4868 self.history.len()
4869 }
4870
4871 /// How many redo steps are stacked: what the sweep asks to check `undo`
4872 /// left a branch behind, and that a fresh edit clears it.
4873 #[cfg(test)]
4874 pub(crate) fn redo_len(&self) -> usize {
4875 self.redo.len()
4876 }
4877
4878 /// Every part of the project that an edit can change, as comparable
4879 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4880 #[cfg(test)]
4881 pub(crate) fn parts(&self) -> SweepParts {
4882 SweepParts(
4883 self.sources.len(),
4884 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4885 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4886 )
4887 }
4888
4889 /// Restore every lane from before the last successful edit -- the clips and
4890 /// the lane list both. `false` when there is nothing left to undo. Pushes
4891 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4892 /// forward again.
4893 pub fn undo(&mut self) -> bool {
4894 match self.history.pop() {
4895 Some(prev) => {
4896 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4897 true
4898 }
4899 None => false,
4900 }
4901 }
4902
4903 /// Restore every lane from before the last [`Project::undo`] -- the
4904 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4905 /// is nothing left to redo, which is also true after any fresh edit: a
4906 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4907 pub fn redo(&mut self) -> bool {
4908 match self.redo.pop() {
4909 Some(next) => {
4910 self.history.push(std::mem::replace(&mut self.lanes, next));
4911 true
4912 }
4913 None => false,
4914 }
4915 }
4916
4917 /// The project an export renders from: everything a render reads, with the
4918 /// undo history left behind. An export never walks the history back, and
4919 /// cloning it costs a copy of every lane list in the session -- this is
4920 /// taken on the UI thread, so it clones the lanes and the sources alone.
4921 pub fn export_snapshot(&self) -> Self {
4922 Self {
4923 sources: self.sources.clone(),
4924 lanes: self.lanes.clone(),
4925 eq: self.eq.clone(),
4926 color: self.color.clone(),
4927 transform: self.transform.clone(),
4928 history: Vec::new(),
4929 redo: Vec::new(),
4930 next_link: self.next_link,
4931 subtitles: self.subtitles.clone(),
4932 limiter: self.limiter,
4933 tone: self.tone,
4934 }
4935 }
4936
4937 /// Half-open `(source, start, end)` segments in *source* seconds, from
4938 /// `timeline_frame` to the end of the timeline -- the play list for the
4939 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4940 /// worker synthesises that many seconds of silence, which is what keeps the
4941 /// audio master clock counting across a hole instead of stalling on it.
4942 /// The first entry is partial when the position is mid-clip. Empty when the
4943 /// position is past the end or `fps` is not usable.
4944 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4945 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4946 }
4947
4948 /// [`segments_from`](Project::segments_from) for a named lane.
4949 pub fn lane_segments_from(
4950 &self,
4951 lane: Lane,
4952 timeline_frame: u32,
4953 fps: f64,
4954 ) -> Vec<(Option<usize>, f64, f64)> {
4955 if !(fps.is_finite() && fps > 0.0) {
4956 return Vec::new();
4957 }
4958 self.spans_from(lane, timeline_frame)
4959 .iter()
4960 .map(|span| match span.from {
4961 // A clip's window is in *source* seconds: where in the file it
4962 // reads from, which a delete before it never shifts. How many
4963 // source frames that is, is the span's own arithmetic -- at a
4964 // speed it is not the timeline length ([`Span::source_len`]).
4965 Some((source, in_frame)) => (
4966 Some(source),
4967 f64::from(in_frame) / fps,
4968 f64::from(in_frame + span.source_len()) / fps,
4969 ),
4970 // A gap has no file, so all it can say is how long it is.
4971 None => (None, 0.0, f64::from(span.len) / fps),
4972 })
4973 .collect()
4974 }
4975
4976 /// One play list per audio lane that *holds* something, in display order --
4977 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4978 /// what an export asks how many lanes it would have to mix.
4979 ///
4980 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4981 /// audio lane at all) still yields one all-gap list, so it plays silence
4982 /// against a master clock exactly as it did before there were lanes to
4983 /// count. Lanes with nothing on them are left out rather than mixed in as
4984 /// silence: they would cost a decode thread each and add zero.
4985 pub fn audio_segments_from(
4986 &self,
4987 timeline_frame: u32,
4988 fps: f64,
4989 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4990 self.audio_lanes()
4991 .into_iter()
4992 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4993 .collect()
4994 }
4995
4996 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4997 /// builds a play list for, in the same order. Public because everything
4998 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4999 /// which lane an mp4 export would copy -- has to read the very list the
5000 /// sound comes off, or the two answers drift apart (which is exactly how an
5001 /// `A2`-only project once exported silently, ledger).
5002 pub fn audio_lanes(&self) -> Vec<Lane> {
5003 let lanes: Vec<Lane> = self
5004 .lanes()
5005 .into_iter()
5006 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
5007 .collect();
5008 match lanes.is_empty() {
5009 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
5010 // no sound still plays silence against the master clock.
5011 true => vec![Lane::A1],
5012 false => lanes,
5013 }
5014 }
5015
5016 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
5017 /// segments plays at, and how long the timeline gives it: the same lanes in
5018 /// the same order, one entry per segment, `None` for a segment at real time
5019 /// -- which is every segment of a project nobody has speeded, and the path
5020 /// the audio worker leaves bit-identical.
5021 ///
5022 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
5023 /// the segment tuple is what every opener and a dozen tests speak, and a
5024 /// rate is not part of *which samples* a segment names.
5025 ///
5026 /// The seconds are what makes a resample exact: a segment's own window
5027 /// resolves to whole source frames, and dividing that by the rate would
5028 /// leave each clip a fraction of a frame short or long -- a drift that grows
5029 /// clip by clip. Told how much timeline it owes, the worker pads or trims
5030 /// the last few samples of each segment instead, so the sound stays locked
5031 /// to the picture however many speeded cuts it walks through.
5032 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
5033 self.audio_lanes()
5034 .into_iter()
5035 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
5036 .collect()
5037 }
5038
5039 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
5040 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5041 /// same walk, same `fps` refusal.
5042 pub fn lane_speeds_from(
5043 &self,
5044 lane: Lane,
5045 timeline_frame: u32,
5046 fps: f64,
5047 ) -> Vec<Option<Stretch>> {
5048 if !(fps.is_finite() && fps > 0.0) {
5049 return Vec::new();
5050 }
5051 self.spans_from(lane, timeline_frame)
5052 .iter()
5053 .map(|span| {
5054 (!span.speed.is_normal()).then(|| Stretch {
5055 step: span.speed.as_f64(),
5056 timeline_secs: f64::from(span.len) / fps,
5057 })
5058 })
5059 .collect()
5060 }
5061
5062 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
5063 /// segments plays through: the same lanes in the same order, one entry per
5064 /// segment, `None` where the segment is a gap or its clip plays flat.
5065 ///
5066 /// A parallel list rather than a fourth element of the segment tuple: that
5067 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
5068 /// and an effect is not part of *which samples* a segment names. A short
5069 /// list therefore means "flat from here on" rather than a length mismatch --
5070 /// see [`crate::AudioSession::open_mixed_streams_eq`].
5071 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
5072 self.audio_lanes()
5073 .into_iter()
5074 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
5075 .collect()
5076 }
5077
5078 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
5079 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5080 /// same walk, same `fps` refusal, so the two lists cannot come out different
5081 /// lengths.
5082 pub fn lane_eqs_from(
5083 &self,
5084 lane: Lane,
5085 timeline_frame: u32,
5086 fps: f64,
5087 ) -> Vec<Option<EqParams>> {
5088 if !(fps.is_finite() && fps > 0.0) {
5089 return Vec::new();
5090 }
5091 self.spans_from(lane, timeline_frame)
5092 .iter()
5093 // A span off a clip covers that clip's frames and no others, so its
5094 // own start names the clip -- the index a [`Span`] does not carry.
5095 .map(|span| {
5096 self.map(lane, span.start)
5097 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
5098 })
5099 .collect()
5100 }
5101
5102 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
5103 /// segments plays through: the same lanes in the same order, one entry per
5104 /// segment, `None` where the segment is a gap or its clip has neither a
5105 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
5106 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
5107 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
5108 self.audio_lanes()
5109 .into_iter()
5110 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
5111 .collect()
5112 }
5113
5114 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
5115 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
5116 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
5117 if !(fps.is_finite() && fps > 0.0) {
5118 return Vec::new();
5119 }
5120 self.spans_from(lane, timeline_frame)
5121 .iter()
5122 .map(|span| {
5123 let (idx, _) = self.map(lane, span.start)?;
5124 let clip = self.lane(lane).get(idx)?;
5125 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
5126 // `span.len` is the clip's own remaining frames from
5127 // `span.start` on -- shorter than `clip.frames()` only
5128 // when this is the first span of a seek mid-clip.
5129 elapsed: clip.frames().saturating_sub(span.len),
5130 fade_in: clip.fade_in,
5131 fade_out: clip.fade_out,
5132 total: clip.frames(),
5133 })
5134 })
5135 .collect()
5136 }
5137
5138 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
5139 /// it has decided it will succeed -- a refusal must not cost an undo step.
5140 /// Clears the redo stack: a fresh edit branches off from here, so whatever
5141 /// `undo` had left to redo is no longer where this edit leads back to.
5142 fn snapshot(&mut self) {
5143 if self.history.len() == HISTORY_CAP {
5144 self.history.remove(0);
5145 }
5146 self.history.push(self.lanes.clone());
5147 self.redo.clear();
5148 }
5149
5150 fn new_link(&mut self) -> u32 {
5151 let id = self.next_link;
5152 self.next_link = self.next_link.saturating_add(1);
5153 id
5154 }
5155
5156}
5157
5158/// The handle of every lane, in storage order -- the one definition of what
5159/// [`Lane::ord`] counts.
5160fn handles(lanes: &[LaneData]) -> Vec<Lane> {
5161 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
5162 lanes
5163 .iter()
5164 .map(|l| match l.kind {
5165 LaneKind::Video => {
5166 video += 1;
5167 Lane::new(LaneKind::Video, video - 1)
5168 }
5169 LaneKind::Audio => {
5170 audio += 1;
5171 Lane::new(LaneKind::Audio, audio - 1)
5172 }
5173 LaneKind::Subtitle => {
5174 subtitle += 1;
5175 Lane::new(LaneKind::Subtitle, subtitle - 1)
5176 }
5177 })
5178 .collect()
5179}
5180
5181/// The one law a caption re-time scales by: frame `f` moves about the held
5182/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
5183/// commits it, [`Project::speeded_playhead`] previews it -- both build their
5184/// [`TimelineMap`] piece from this single answer so the two cannot drift
5185/// apart by a frame the way they once did.
5186fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
5187 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
5188 .round()
5189 .clamp(0., f64::from(u32::MAX)) as u32
5190}
5191
5192/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
5193/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
5194/// a speed cannot be applied twice or forgotten in one of them.
5195fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
5196 // Clamped inside the clip's own range: rounding at a slow rate can put the
5197 // last timeline frame of a clip a frame past its out-point, and a source
5198 // frame outside the range is one the next clip owns.
5199 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
5200}
5201
5202/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
5203/// finder generic makes the subtitle path use the same bounded-hole rules as
5204/// media lanes without teaching the media-specific take logic about captions.
5205trait GapPlacement {
5206 fn start_frame(&self) -> u32;
5207 fn end_frame(&self) -> u32;
5208}
5209
5210impl GapPlacement for Clip {
5211 fn start_frame(&self) -> u32 {
5212 self.start
5213 }
5214
5215 fn end_frame(&self) -> u32 {
5216 self.end()
5217 }
5218}
5219
5220impl GapPlacement for SubClip {
5221 fn start_frame(&self) -> u32 {
5222 self.start
5223 }
5224
5225 fn end_frame(&self) -> u32 {
5226 self.end()
5227 }
5228}
5229
5230/// Index of the placement covering `frame`, or `None` for a gap or past the
5231/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
5232fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
5233 let idx = items.partition_point(|item| item.start_frame() <= frame).checked_sub(1)?;
5234 (frame < items[idx].end_frame()).then_some(idx)
5235}
5236
5237/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
5238/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
5239/// invariant like [`at`]: the first placement whose start is past `frame` is
5240/// the far wall, and the last one that ends at or before `frame` (or the
5241/// timeline's own head, `0`, when there is none) is the near one.
5242fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
5243 if at(items, frame).is_some() {
5244 return None;
5245 }
5246 let idx = items.partition_point(|item| item.start_frame() <= frame);
5247 let next = items.get(idx)?;
5248 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
5249 Some((start, next.start_frame() - start))
5250}
5251
5252/// Every bounded hole in `items`, left to right. The tail after the last
5253/// placement is deliberately absent: there is no later placement for a ripple
5254/// to bring back.
5255fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
5256 let mut out = Vec::new();
5257 let mut next = 0;
5258 for item in items {
5259 if item.start_frame() > next {
5260 out.push((next, item.start_frame() - next));
5261 }
5262 next = item.end_frame();
5263 }
5264 out
5265}
5266
5267/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
5268/// there would cut in two. A placement's own first frame is not inside it.
5269fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
5270 let idx = at(clips, frame)?;
5271 // ...and, on a speeded clip, one its rate can actually address
5272 // ([`Speed::split_at`]): a cut between two showings of one source frame
5273 // would leave halves that no longer add up to the clip that was cut.
5274 (frame > clips[idx].start)
5275 .then_some(idx)
5276 .filter(|&idx| split_source(&clips[idx], frame).is_some())
5277}
5278
5279/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
5280/// rate cannot address that frame.
5281fn split_source(c: &Clip, frame: u32) -> Option<u32> {
5282 c.speed
5283 .split_at(c.len(), frame - c.start)
5284 .map(|src| c.in_frame + src)
5285}
5286
5287/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
5288/// rejoin: they must touch there, and be consecutive frames of one source.
5289fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
5290 let idx = clips.iter().position(|c| c.end() == frame)?;
5291 let next = clips.get(idx + 1)?;
5292 let joined = clips[idx].len() + next.len();
5293 (next.start == frame
5294 && next.source == clips[idx].source
5295 && next.in_frame == clips[idx].out_frame
5296 // ...at one rate, and one that puts the rejoined clip back in exactly
5297 // the room the two took up: what a split could have produced, which is
5298 // all this undoes.
5299 && next.speed == clips[idx].speed
5300 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
5301 .then_some(idx)
5302}
5303
5304/// The lane invariant: sorted by `start`, no two placements overlapping, no
5305/// empty placement. Checked at every constructor and asserted after every
5306/// mutation -- the offset model is only tractable while it holds.
5307/// The one thing an equalizer setting may not be: a value the text format
5308/// cannot write and read back as itself. Checked wherever params come in, so
5309/// what an edit produces is always what a save writes and a load reads.
5310fn finite(params: &EqParams) -> bool {
5311 params
5312 .bands
5313 .iter()
5314 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
5315}
5316
5317/// The same for a colour grade: [`crate::color`] itself falls back to identity
5318/// on a non-finite value, but a value that cannot be written and read back as
5319/// itself has no business reaching the model.
5320fn color_finite(p: &ColorParams) -> bool {
5321 p.brightness.is_finite()
5322 && p.contrast.is_finite()
5323 && p.saturation.is_finite()
5324 && p.tint.is_finite()
5325}
5326
5327/// The same for a transform: [`crate::scale`] clamps a non-finite value to
5328/// identity at read time, but a value that cannot round-trip has no business
5329/// reaching the model.
5330fn transform_finite(p: &TransformParams) -> bool {
5331 p.pos_x.is_finite()
5332 && p.pos_y.is_finite()
5333 && p.scale.is_finite()
5334 && p.rotate.is_finite()
5335 && p.crop_l.is_finite()
5336 && p.crop_r.is_finite()
5337 && p.crop_t.is_finite()
5338 && p.crop_b.is_finite()
5339}
5340
5341fn sorted_disjoint(clips: &[Clip]) -> bool {
5342 clips.iter().all(|c| c.out_frame > c.in_frame)
5343 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
5344}
5345
5346/// The very same invariant on a subtitle lane, in that lane's own two units:
5347/// sorted by `start`, no two placements overlapping, no empty placement at
5348/// either end. Asserted after every mutation, exactly as its twin is.
5349fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
5350 subs.iter()
5351 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
5352 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
5353}
5354
5355/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
5356/// the one conversion between a lane's clock and a cue's, and `0` for a rate
5357/// that is not one (every caller of this has already refused such a rate).
5358fn us_of(frames: i64, fps: f64) -> i64 {
5359 match fps.is_finite() && fps > 0.0 {
5360 true => ((frames as f64) / fps * 1e6).round() as i64,
5361 false => 0,
5362 }
5363}
5364
5365/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5366/// dropping what is inside the hole, splitting what straddles it and trimming
5367/// what overlaps an edge. The windows follow the cut by proportion
5368/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5369fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5370 let mut out = Vec::with_capacity(subs.len() + 1);
5371 for s in subs.drain(..) {
5372 if s.end() <= start || s.start >= end {
5373 out.push(s);
5374 continue;
5375 }
5376 if s.start < start {
5377 out.push(SubClip {
5378 frames: start - s.start,
5379 out_us: s.window_at(start),
5380 // Both pieces lose the group id, for [`clear`]'s reason: one
5381 // id on two boxes of one lane is the one thing it may never
5382 // mean.
5383 link: None,
5384 ..s
5385 });
5386 }
5387 if s.end() > end {
5388 out.push(SubClip {
5389 start: end,
5390 frames: s.end() - end,
5391 in_us: s.window_at(end),
5392 link: None,
5393 ..s
5394 });
5395 }
5396 }
5397 *subs = out;
5398}
5399
5400/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5401/// `len`, splitting a placement that straddles `at` so the two halves end up on
5402/// either side of the hole. A `len` of 0 is that split alone, which is what a
5403/// [`Project::split`] over a subtitle lane is.
5404fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5405 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5406 let s = subs[idx];
5407 let cut = s.window_at(at);
5408 subs[idx] = SubClip {
5409 frames: at - s.start,
5410 out_us: cut,
5411 link: None,
5412 ..s
5413 };
5414 subs.insert(
5415 idx + 1,
5416 SubClip {
5417 start: at,
5418 frames: s.end() - at,
5419 in_us: cut,
5420 link: None,
5421 ..s
5422 },
5423 );
5424 }
5425 for s in subs.iter_mut().filter(|s| s.start >= at) {
5426 s.start += len;
5427 }
5428}
5429
5430/// [`joinable`] for a subtitle lane: the first of the two placements a
5431/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5432/// produced and nothing else -- they touch on the timeline, they read the same
5433/// track, and the second one's window carries on where the first's stopped.
5434fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5435 let idx = subs.iter().position(|s| s.end() == frame)?;
5436 let next = subs.get(idx + 1)?;
5437 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5438 .then_some(idx)
5439}
5440
5441/// How far one `edge` of the caption at `idx` may travel against its own lane's
5442/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5443/// rate, which a caption *following* a group's trim does not have to be exact
5444/// about -- its own walls, its own one surviving frame, and nothing that needs
5445/// a clock.
5446fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5447 let s = &subs[idx];
5448 match edge {
5449 Edge::Start => (
5450 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5451 s.end() - 1,
5452 ),
5453 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5454 }
5455}
5456
5457/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5458/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5459/// forwards and backwards. The caption a group's trim is carrying has no rate
5460/// of its own and needs none: what one frame of it is worth in microseconds is
5461/// the window it already shows over the frames it already takes.
5462fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5463 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5464 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5465 match edge {
5466 Edge::Start => {
5467 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5468 s.frames = s.end() - to;
5469 s.start = to;
5470 }
5471 Edge::End => {
5472 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5473 s.frames = to - s.start;
5474 }
5475 }
5476 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5477}
5478
5479/// The grouping invariant, checked in release at [`Project::from_parts`] and
5480/// asserted by the tests after every edit: a link id names **at most one**
5481/// placement per lane -- a clip on a media lane or a caption on a subtitle
5482/// one, whichever carries it. That is all "these move together" can mean now
5483/// that a group is assembled by hand: the members keep their own spans and
5484/// their own offsets, and what binds them is the id alone.
5485///
5486/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5487/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5488/// placements of one group may cover different frames -- the offset-preserving
5489/// group a hand builds with [`Project::group_all`], which a drag moves by one
5490/// delta rather than by one span.
5491///
5492/// A link no other lane carries is legal and is not an error: lifting one half
5493/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5494/// timeline has to load again.
5495/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5496/// asked by the sweep suite's universal law.
5497#[cfg(test)]
5498pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5499 links_are_consistent(&p.lanes)
5500}
5501
5502fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5503 let handles = handles(lanes);
5504 for (data, lane) in lanes.iter().zip(&handles) {
5505 for (i, c) in data.clips.iter().enumerate() {
5506 let Some(id) = c.link else { continue };
5507 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5508 return Err(
5509 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5510 );
5511 }
5512 }
5513 // ...and the same for the captions, in their own list on the same lane:
5514 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5515 // id could be doubled on.
5516 for (i, s) in data.subs.iter().enumerate() {
5517 let Some(id) = s.link else { continue };
5518 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5519 return Err(format!(
5520 "link {id} names two captions in the {} lane",
5521 lane.label()
5522 )
5523 .into());
5524 }
5525 }
5526 }
5527 Ok(())
5528}
5529
5530/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5531/// it go, one straddling it is split in two, one overlapping an edge is
5532/// trimmed. Source frames follow the trim, so what is left plays what it always
5533/// played. Leaves the lane sorted and disjoint.
5534///
5535/// A piece the hole cut is no longer the take its group id names -- and both
5536/// halves of a straddled placement carrying that id would be the same id twice
5537/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5538fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5539 let mut out = Vec::with_capacity(clips.len() + 1);
5540 for c in clips.drain(..) {
5541 // Disjoint from the hole: untouched.
5542 if c.end() <= start || c.start >= end {
5543 out.push(c);
5544 continue;
5545 }
5546 // The head that survives in front of the hole -- as much source as fits
5547 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5548 // which at real time is that room itself. Never *more*: a head that
5549 // outgrew its room would reach into the hole it is being cut out of,
5550 // which is exactly the overlap a slow clip punched at a frame its rate
5551 // cannot address used to leave (at 0.25x a single source frame is four
5552 // timeline frames, and three frames of room hold none of it). `None`
5553 // there means no remainder at all, and the piece simply goes.
5554 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5555 && c.start < start
5556 {
5557 out.push(Clip {
5558 fade_in: 0,
5559 fade_out: 0,
5560 transition_out: 0,
5561 out_frame: c.in_frame + keep.min(c.len()),
5562 link: None,
5563 ..c
5564 });
5565 }
5566 // ...and the tail behind it, which keeps reading up to where it would
5567 // have: measured from its out-point for the head's reason, so what it
5568 // occupies still ends where the whole clip did -- and dropped whole on
5569 // the same `None`.
5570 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5571 && c.end() > end
5572 {
5573 out.push(Clip {
5574 fade_in: 0,
5575 fade_out: 0,
5576 transition_out: 0,
5577 start: end,
5578 in_frame: c.out_frame - keep.min(c.len()),
5579 link: None,
5580 ..c
5581 });
5582 }
5583 }
5584 *clips = out;
5585}
5586
5587/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5588/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5589/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5590/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5591/// the caller.
5592fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5593 for &i in on {
5594 let clips = &mut lanes[i].clips;
5595 clear(clips, at, at + len);
5596 for c in clips.iter_mut().filter(|c| c.start >= at) {
5597 c.start -= len;
5598 }
5599 debug_assert!(sorted_disjoint(clips));
5600 // The subtitle lanes close the hole with everything else: a caption
5601 // left standing where the picture it belongs to was cut out is the
5602 // desync a lane model exists to make impossible.
5603 let subs = &mut lanes[i].subs;
5604 sub_clear(subs, at, at + len);
5605 for s in subs.iter_mut().filter(|s| s.start >= at) {
5606 s.start -= len;
5607 }
5608 debug_assert!(subs_sorted_disjoint(subs));
5609 }
5610}
5611
5612/// Every lane, as the index list the two above take: what "the whole timeline"
5613/// is spelled as, and the scope [`Project::ripple_delete`] and
5614/// [`Project::split`] have always had.
5615fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5616 (0..lanes.len()).collect()
5617}
5618
5619/// A caller's region list as a batch may use it: sorted by start, empty entries
5620/// dropped, and touching or overlapping entries merged into one.
5621///
5622/// Overlapping regions are the one thing a batch cannot take -- cutting the
5623/// second would cut frames the first already moved -- and a detector handing
5624/// back two that touch means one silence, not two cuts. Merged rather than
5625/// refused: this is arithmetic on a preview, not a user's mistake.
5626fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5627 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5628 sorted.sort_by_key(|&(at, _)| at);
5629 let mut out: Vec<(u32, u32)> = Vec::new();
5630 for (at, len) in sorted {
5631 let end = at.saturating_add(len);
5632 match out.last_mut() {
5633 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5634 _ => out.push((at, len)),
5635 }
5636 }
5637 out
5638}
5639
5640/// Slides everything from `at` on later by `len`, splitting a placement that
5641/// straddles `at` so the two halves end up on either side of the hole. The
5642/// insert half of a rippling paste. The two halves lose the group id for the
5643/// reason [`clear`] gives.
5644fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5645 if let Some(idx) = splittable(clips, at) {
5646 let mut tail = clips[idx];
5647 // The cut in *source* frames, at the clip's own rate. `splittable` has
5648 // already refused a frame the rate cannot address, which is why
5649 // [`Project::paste`] refuses one too rather than opening room inside a
5650 // clip that cannot be cut there.
5651 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5652 tail.start = at;
5653 tail.link = None;
5654 clips[idx].out_frame = tail.in_frame;
5655 clips[idx].link = None;
5656 clips.insert(idx + 1, tail);
5657 }
5658 for c in clips.iter_mut().filter(|c| c.start >= at) {
5659 c.start += len;
5660 }
5661}
5662
5663/// Absolute, symlink-resolved when the file is reachable; the path as given
5664/// when it is not -- an unreadable path still deserves an index, it simply
5665/// dedups by spelling.
5666pub(crate) fn canonical(path: &Path) -> PathBuf {
5667 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5668}
5669
5670#[cfg(test)]
5671mod tests {
5672 use super::*;
5673
5674 const FPS: f64 = 30.0;
5675 /// Never opened -- `Project` is pure data, so a path that does not exist is
5676 /// simply a path that dedups by spelling.
5677 const FILE: &str = "/nonexistent/a.mp4";
5678 const FILE2: &str = "/nonexistent/b.mp4";
5679
5680 /// A contiguous placement, group id ignored: what most assertions compare.
5681 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5682 Clip {
5683 fade_in: 0,
5684 fade_out: 0,
5685 transition_out: 0,
5686 start,
5687 in_frame,
5688 out_frame,
5689 source,
5690 link: None,
5691 eq: None,
5692 color: None,
5693 transform: None,
5694 fit: FitPolicy::default(),
5695 speed: Speed::NORMAL,
5696 }
5697 }
5698
5699 /// A caption placement for pure timeline tests: the track window is the
5700 /// same duration as the placement, so assertions can stay in frames.
5701 fn caption(start: u32, frames: u32) -> SubClip {
5702 SubClip {
5703 start,
5704 frames,
5705 track: 0,
5706 in_us: 0,
5707 out_us: i64::from(frames) * 1_000_000,
5708 link: None,
5709 }
5710 }
5711
5712 /// A subtitle palette row for tests that place captions on lanes.
5713 fn subtitle_track() -> SubtitleTrack {
5714 SubtitleTrack {
5715 path: FILE.into(),
5716 track: None,
5717 language: "eng".into(),
5718 name: String::new(),
5719 label: "eng".into(),
5720 cues: Vec::new(),
5721 bitmap: false,
5722 refused: None,
5723 }
5724 }
5725
5726 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5727 /// apart -- which is what makes the table's dedup and its prune visible.
5728 fn band_at(n: u32) -> EqParams {
5729 EqParams {
5730 bands: vec![crate::eq::Band {
5731 freq_hz: 1000.0,
5732 gain_db: f64::from(n) as f32 * 1.5,
5733 q: 0.707,
5734 kind: crate::eq::BandKind::Peak,
5735 }],
5736 }
5737 }
5738
5739 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5740 /// for the colour table.
5741 fn grade_at(n: u32) -> ColorParams {
5742 ColorParams {
5743 brightness: f64::from(n) as f32 * 0.05,
5744 ..Default::default()
5745 }
5746 }
5747
5748 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5749 /// twin for the transform table.
5750 fn transform_at(n: u32) -> TransformParams {
5751 TransformParams {
5752 pos_x: f64::from(n) as f32 * 0.05,
5753 ..Default::default()
5754 }
5755 }
5756
5757 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5758 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5759 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5760 }
5761
5762 /// Every lane with its group ids blanked, for comparing shape.
5763 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5764 p.lanes()
5765 .into_iter()
5766 .map(|l| {
5767 p.lane(l)
5768 .iter()
5769 .map(|c| Clip { link: None, ..*c })
5770 .collect()
5771 })
5772 .collect()
5773 }
5774
5775 /// The *source frame* every timeline frame reads, per lane -- the traversal
5776 /// a player performs. Deliberately not the clip index: a split changes which
5777 /// clip a frame belongs to, and nothing else.
5778 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5779 (0..p.timeline_frames() + 2)
5780 .map(|f| {
5781 p.lanes()
5782 .into_iter()
5783 .map(|l| p.map(l, f).map(|(_, source)| source))
5784 .collect()
5785 })
5786 .collect()
5787 }
5788
5789 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5790 /// fixture. Built through `split` so the constructor path is exercised too.
5791 fn three() -> Project {
5792 let mut p = Project::single(FILE, 9);
5793 assert!(p.split(3));
5794 assert!(p.split(5));
5795 assert_eq!(
5796 shape(&p),
5797 [
5798 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5799 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5800 ]
5801 );
5802 p
5803 }
5804
5805 #[test]
5806 fn single_is_the_whole_file_on_both_lanes() {
5807 let p = Project::single(FILE, 150);
5808 assert_eq!(p.clips().len(), 1);
5809 assert_eq!(p.lane(Lane::A1).len(), 1);
5810 assert_eq!(p.timeline_frames(), 150);
5811 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5812 // grouped: video and audio carry the same link
5813 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5814 assert!(p.clips()[0].link.is_some());
5815 // degenerate mapping: timeline == source
5816 assert_eq!(p.map_timeline(0), Some((0, 0)));
5817 assert_eq!(p.map_timeline(149), Some((0, 149)));
5818 assert_eq!(p.map_timeline(150), None);
5819 // never-empty invariant survives a bogus frame count
5820 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5821 }
5822
5823 #[test]
5824 fn split_cuts_every_lane_and_regroups_it_back() {
5825 let mut p = Project::single(FILE, 9);
5826 let before = traversal(&p);
5827 let before_shape = shape(&p);
5828
5829 assert!(p.split(4));
5830 for l in p.lanes() {
5831 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5832 }
5833 // The two sides are two groups, one per side, matching across the lanes.
5834 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5835 assert_eq!(v[0].link, a[0].link);
5836 assert_eq!(v[1].link, a[1].link);
5837 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5838 // A split changes no mapping, in either lane.
5839 assert_eq!(traversal(&p), before, "a split moves nothing");
5840
5841 assert!(p.regroup(4), "the inverse rejoins them");
5842 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5843 assert_eq!(traversal(&p), before);
5844 assert_eq!(
5845 p.lane(Lane::V1)[0].link,
5846 p.lane(Lane::A1)[0].link,
5847 "and the rejoined clip is one group again"
5848 );
5849 }
5850
5851 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
5852 /// the very first frame of a fade-in, unity at its last, equal-power
5853 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
5854 /// at all.
5855 #[test]
5856 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
5857 let f = Fade {
5858 elapsed: 0,
5859 fade_in: 10,
5860 fade_out: 10,
5861 total: 40,
5862 };
5863 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
5864 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
5865 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
5866 assert!(
5867 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
5868 "equal-power midpoint is sin(pi/4)"
5869 );
5870 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
5871 // The fade-out is the same curve, mirrored, counting down from the
5872 // clip's end: unity at the frame the ramp starts, the same
5873 // equal-power midpoint, and -- since `total` itself is one past the
5874 // clip's last valid frame -- the very last frame is one step short of
5875 // the silence a fade-in's own frame `0` lands on exactly.
5876 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
5877 assert!(
5878 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
5879 "the fade-out's own equal-power midpoint"
5880 );
5881 assert!(
5882 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
5883 "one step short of silence at the clip's last playable frame"
5884 );
5885 }
5886
5887 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
5888 /// not adjacent, and otherwise sets the shared edge's fades and nothing
5889 /// else.
5890 #[test]
5891 fn crossfade_only_joins_adjacent_audio_clips() {
5892 let mut p = Project::single(FILE, 20);
5893 assert!(p.split(10));
5894 assert!(
5895 !p.crossfade(Lane::V1, 0, 5),
5896 "video is not an audio lane"
5897 );
5898 assert!(
5899 !p.crossfade(Lane::A1, 1, 5),
5900 "there is no clip after idx 1"
5901 );
5902 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
5903 let a = p.lane(Lane::A1);
5904 assert_eq!(a[0].fade_out, 5);
5905 assert_eq!(a[1].fade_in, 5);
5906 assert_eq!(a[0].fade_in, 0);
5907 assert_eq!(a[1].fade_out, 0);
5908
5909 // A gap between two clips is not adjacency, even on an audio lane.
5910 let mut p2 = Project::single(FILE, 1);
5911 let a2 = p2.add_lane(LaneKind::Audio);
5912 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
5913 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5914 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
5915 }
5916
5917 /// The rule [`Project::write_split`] follows for the edge the razor makes:
5918 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
5919 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
5920 /// mirror image.
5921 #[test]
5922 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
5923 let mut p = Project::single(FILE, 20);
5924 assert!(p.set_fade_in(Lane::V1, 0, 15));
5925 assert!(p.set_fade_out(Lane::V1, 0, 15));
5926 assert!(p.split(5));
5927 let v = p.lane(Lane::V1);
5928 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
5929 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
5930 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
5931 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
5932 }
5933
5934 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
5935 /// no successor, and two clips that do not touch, and otherwise clamps
5936 /// the dissolve to the shorter of the two clips it spans.
5937 #[test]
5938 fn set_transition_out_only_dissolves_adjacent_video_clips() {
5939 let mut p = Project::single(FILE, 20);
5940 assert!(p.split(15), "a short 5-frame tail to clamp against");
5941 assert!(
5942 !p.set_transition_out(Lane::A1, 0, 5),
5943 "audio is not a video lane"
5944 );
5945 assert!(
5946 !p.set_transition_out(Lane::V1, 1, 5),
5947 "there is no clip after idx 1"
5948 );
5949 assert!(
5950 p.set_transition_out(Lane::V1, 0, 100),
5951 "the two halves are adjacent"
5952 );
5953 assert_eq!(
5954 p.transition_out_of(Lane::V1, 0),
5955 5,
5956 "clamped to the shorter neighbour's 5 frames"
5957 );
5958
5959 // A gap between two clips is not adjacency, even on the video lane.
5960 let mut p2 = Project::single(FILE, 1);
5961 let v2 = p2.add_lane(LaneKind::Video);
5962 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
5963 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5964 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
5965 }
5966
5967 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
5968 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
5969 /// only the half that kept the clip's original *end* keeps the dissolve,
5970 /// re-clamped to its own now-shorter length; the head the cut just made
5971 /// has no successor to dissolve into and starts flat.
5972 #[test]
5973 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
5974 let mut p = Project::single(FILE, 20);
5975 assert!(
5976 !p.set_transition_out(Lane::V1, 0, 0),
5977 "one clip on the lane, no successor to dissolve into yet"
5978 );
5979 // Give the clip a dissolve by hand, then cut it in two.
5980 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
5981 assert!(p.split(5));
5982 let v = p.lane(Lane::V1);
5983 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
5984 assert_eq!(
5985 v[1].transition_out, 15,
5986 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
5987 );
5988 }
5989
5990 /// The music video's own path: the take comes apart into halves that carry
5991 /// ids of their own, one undo puts it back, and two clips over the same
5992 /// frames become one take again by hand.
5993 #[test]
5994 fn a_take_comes_apart_and_goes_back_together() {
5995 let mut p = Project::single(FILE, 9);
5996 let one = p.clips()[0].link.expect("a fresh project is one take");
5997 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5998
5999 // A third lane in the same group -- and the merge case with it: a
6000 // placement is in no group, and grouping it in leaves *one* group.
6001 let v2 = p.add_lane(LaneKind::Video);
6002 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6003 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
6004 p.group(Lane::V1, 0, v2, 0)
6005 .expect("the same frames, one lane over");
6006 let id = p.clips()[0].link.expect("still a group");
6007 assert!(
6008 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6009 "one id over the three, not two groups sharing a span"
6010 );
6011 links_are_consistent(&p.lanes).expect("one id, one span");
6012
6013 // Detached by the sound: every half of the group, not only the two.
6014 assert!(p.ungroup(Lane::A1, 0));
6015 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
6016 assert!(
6017 ids.iter().all(Option::is_some),
6018 "a half keeps an id of its own"
6019 );
6020 assert!(
6021 ids.iter()
6022 .enumerate()
6023 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
6024 "and no two halves are the same group any more: {ids:?}"
6025 );
6026 links_are_consistent(&p.lanes).expect("a lone id is legal");
6027
6028 // One snapshot for the whole detach.
6029 assert!(p.undo());
6030 assert!(
6031 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6032 "one undo puts the whole group back"
6033 );
6034
6035 // And back together by hand: the two the pointer named, and only them.
6036 assert!(p.ungroup(Lane::V1, 0));
6037 p.group(Lane::V1, 0, Lane::A1, 0)
6038 .expect("both cover [0, 9)");
6039 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
6040 assert_ne!(
6041 p.lane(v2)[0].link,
6042 p.lane(Lane::V1)[0].link,
6043 "the third half stayed detached"
6044 );
6045 links_are_consistent(&p.lanes).expect("one id, one span");
6046 }
6047
6048 /// What a group may not be, and what a detach has nothing to take apart --
6049 /// none of which may cost an undo step.
6050 #[test]
6051 fn a_group_is_one_span_and_one_clip_per_lane() {
6052 let mut p = three();
6053 let before = shape(&p);
6054 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
6055
6056 assert!(
6057 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
6058 "two clips of one lane are never one take"
6059 );
6060 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
6061 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
6062 assert!(
6063 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
6064 "{spans}"
6065 );
6066 assert!(
6067 spans.contains("trim them to matching bounds first"),
6068 "{spans}"
6069 );
6070 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
6071
6072 // A half nothing else is grouped with is already detached, a placement
6073 // is in no group at all, and an index that is not there has nothing to
6074 // detach either.
6075 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
6076 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
6077 assert!(p.lift(Lane::A1, 0));
6078 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
6079 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
6080
6081 // Two undos, one per edit: not one of the refusals pushed a snapshot.
6082 assert!(p.undo());
6083 assert!(p.undo());
6084 assert_eq!(shape(&p), before);
6085 }
6086
6087 /// Where a re-rate puts a playhead: the scene under the cursor stays the
6088 /// scene under the cursor, measured the way a viewer would -- the source
6089 /// frame playing at the playhead is the same frame after the write, at
6090 /// every playhead position the re-rate can catch one.
6091 #[test]
6092 fn a_re_rate_keeps_the_frame_under_the_playhead() {
6093 let caption = |start: u32, frames: u32| SubClip {
6094 start,
6095 frames,
6096 track: 0,
6097 in_us: 0,
6098 out_us: i64::from(frames) * 1_000_000,
6099 link: None,
6100 };
6101 let track = || SubtitleTrack {
6102 path: FILE.into(),
6103 track: None,
6104 language: "eng".into(),
6105 name: String::new(),
6106 label: "eng".into(),
6107 cues: Vec::new(),
6108 bitmap: false,
6109 refused: None,
6110 };
6111 // A group of a 300-frame clip and a caption offset 30 frames into it.
6112 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
6113 let s1 = p.add_lane(LaneKind::Subtitle);
6114 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
6115 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6116
6117 // The frame playing at `at`: which clip, and which source frame of it.
6118 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
6119 p.span_at(Lane::V1, at)
6120 .and_then(|s| s.from.map(|(source, from)| (source, from)))
6121 };
6122
6123 // Inside the held clip: the source frame under the playhead is the
6124 // same one after the re-rate, at 2x and at half speed both.
6125 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
6126 let at = 120;
6127 let before = playing(&p, at).expect("a clip under the playhead");
6128 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
6129 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
6130 .expect("room for it");
6131 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
6132 assert_eq!(before, after, "{what}: the same source frame plays");
6133 // ...and the write itself is untouched by the question.
6134 assert!(p.undo(), "{what}: one step back");
6135 }
6136
6137 // Past the group -- the clip ends at 300 and the caption at 270, so
6138 // from 300 on nothing is re-timed under the playhead: unmoved.
6139 for at in [300u32, 301, 1_000] {
6140 assert_eq!(
6141 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
6142 Some(at),
6143 "at {at}: outside every member, unmoved"
6144 );
6145 }
6146 // The boundary is exact: the held clip's own last frame (299) maps
6147 // to its new one (149 -- the last frame inside [0, 150), where the
6148 // shrunken clip's last source frame plays), and its first stays put.
6149 assert_eq!(
6150 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
6151 Some(149)
6152 );
6153 assert_eq!(
6154 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
6155 Some(0)
6156 );
6157 // A spot the caption shares with the clip maps by the clip (it is
6158 // what is *playing* there): the held clip's own proportion, which on
6159 // this fixture is also its head.
6160 assert_eq!(
6161 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
6162 Some(45),
6163 "the clip under the caption owns the spot"
6164 );
6165 }
6166
6167 /// A playhead inside another clip member of the group: that member keeps
6168 /// its own head, so the mapping is by its proportion and not the held
6169 /// clip's -- and the frame under the cursor is still the frame that was.
6170 #[test]
6171 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
6172 let mut p = Project::single(FILE, 300);
6173 // A second clip, grouped with the first but starting 300 later: the
6174 // head the group shares and its own differ by exactly that.
6175 let v2 = p.add_lane(LaneKind::Video);
6176 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
6177 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
6178 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
6179
6180 let at = 450; // inside the second member, 150 past its head
6181 let before = p.span_at(v2, at).and_then(|s| s.from);
6182 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
6183 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6184 .expect("room for it");
6185 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
6186 assert_eq!(before, after, "the second member's own frame plays");
6187 // ...and the mapping itself: 150 past its head halves, the head stays.
6188 assert_eq!(mapped, Some(375));
6189 }
6190
6191 /// The link counter a load seeds sits past every id the file names,
6192 /// captions included: a hand-grouped caption may carry the highest id there
6193 /// is, and a counter that read the clips alone would hand it to the next
6194 /// group that asked -- silently grouping the caption with clips it never
6195 /// met.
6196 #[test]
6197 fn the_link_counter_sits_past_a_caption_only_id() {
6198 let track = || SubtitleTrack {
6199 path: FILE.into(),
6200 track: None,
6201 language: "eng".into(),
6202 name: String::new(),
6203 label: "eng".into(),
6204 cues: Vec::new(),
6205 bitmap: false,
6206 refused: None,
6207 };
6208 let mut p = Project::single(FILE, 9);
6209 p.add_lane(LaneKind::Subtitle);
6210 let caption = SubClip {
6211 start: 0,
6212 frames: 6,
6213 track: 0,
6214 in_us: 0,
6215 out_us: 6_000_000,
6216 // The highest id in the file, and only a caption carries it.
6217 link: Some(1),
6218 };
6219 let mut p = p
6220 .with_subtitles(vec![track()])
6221 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
6222 .expect("a caption may carry the file's highest id");
6223
6224 // A new group on lanes the caption is not on mints the next id -- which
6225 // must not be the caption's.
6226 let v2 = p.add_lane(LaneKind::Video);
6227 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6228 p.group_all(&[(Lane::V1, 0), (v2, 0)])
6229 .expect("the clips group");
6230 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
6231 assert_ne!(
6232 minted,
6233 1,
6234 "the caption's id is not re-issued to clips"
6235 );
6236 assert_eq!(
6237 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
6238 Some(1),
6239 "the caption keeps its own group"
6240 );
6241 assert!(links_are_consistent(&p.lanes).is_ok());
6242 }
6243
6244 /// A rate re-times the caption members of the group by the ratio it gives
6245 /// the held clip: the span on the timeline compresses about the held clip's
6246 /// head, the words' own window untouched -- and one undo puts it back.
6247 #[test]
6248 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
6249 let caption = |start: u32, frames: u32| SubClip {
6250 start,
6251 frames,
6252 track: 0,
6253 in_us: 0,
6254 out_us: i64::from(frames) * 1_000_000,
6255 link: None,
6256 };
6257 let track = || SubtitleTrack {
6258 path: FILE.into(),
6259 track: None,
6260 language: "eng".into(),
6261 name: String::new(),
6262 label: "eng".into(),
6263 cues: Vec::new(),
6264 bitmap: false,
6265 refused: None,
6266 };
6267 let grouped = || {
6268 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6269 let s1 = p.add_lane(LaneKind::Subtitle);
6270 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6271 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6272 (p, s1)
6273 };
6274
6275 // An aligned take, doubled: the caption plays in half the frames.
6276 let (mut p, s1) = grouped();
6277 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6278 .expect("room for it");
6279 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
6280 let s = p.sub_lane(s1)[0];
6281 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
6282 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
6283 assert!(links_are_consistent(&p.lanes).is_ok());
6284 assert!(p.undo());
6285 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
6286
6287 // An offset group, slowed to half: the caption's *offset from the held
6288 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
6289 // 0.5x, and still ends where the clip does.
6290 let (mut p, s1) = grouped();
6291 p.lift_sub(s1, 0);
6292 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
6293 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6294 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
6295 .expect("room for it");
6296 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
6297 let s = p.sub_lane(s1)[0];
6298 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
6299 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
6300
6301 // A stretch that runs the caption into its neighbour is refused, by
6302 // lane and frame, and costs no undo step.
6303 let (mut p, s1) = grouped();
6304 p.lift_sub(s1, 0);
6305 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6306 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
6307 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6308 let history = p.history.len();
6309 let err = p
6310 .set_speed(Lane::V1, 0, Speed::from_permille(500))
6311 .unwrap_err()
6312 .to_string();
6313 assert!(
6314 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
6315 "{err}"
6316 );
6317 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
6318 }
6319
6320 /// The silence scan's speed-up re-times the captions on a scoped lane with
6321 /// everything else: the piece inside the region plays in the region's new
6322 /// frames, and what sits behind the region slides up with the clips.
6323 #[test]
6324 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
6325 let caption = |start: u32, frames: u32| SubClip {
6326 start,
6327 frames,
6328 track: 0,
6329 in_us: 0,
6330 out_us: i64::from(frames) * 1_000_000,
6331 link: None,
6332 };
6333 let track = || SubtitleTrack {
6334 path: FILE.into(),
6335 track: None,
6336 language: "eng".into(),
6337 name: String::new(),
6338 label: "eng".into(),
6339 cues: Vec::new(),
6340 bitmap: false,
6341 refused: None,
6342 };
6343 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6344 let s1 = p.add_lane(LaneKind::Subtitle);
6345 // Words over the region [30, 60) and words behind it.
6346 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6347 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
6348
6349 // The region [30, 60) plays at 4x: 30 frames become 8, everything
6350 // behind slides up 22.
6351 // The scope is what the card's Take row says, caption lane included.
6352 p.speed_regions(
6353 &[(30, 30)],
6354 Speed::from_permille(4000),
6355 &[Lane::V1, Lane::A1, s1],
6356 )
6357 .expect("the region speeds up");
6358 let subs = p.sub_lane(s1);
6359 assert_eq!(
6360 (subs[0].start, subs[0].frames),
6361 (30, 8),
6362 "the piece inside plays in the region's new frames"
6363 );
6364 assert_eq!(
6365 (subs[1].start, subs[1].frames),
6366 (38, 30),
6367 "the piece behind slides up by what the region gave back"
6368 );
6369 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
6370 }
6371
6372 /// [`Project::speeded_playhead`]'s caption arm fires only when the
6373 /// playhead is inside a caption member and outside every clip member --
6374 /// a shape every other fixture avoids by keeping its caption inside the
6375 /// held clip. Here the caption overhangs the clip's tail, and the
6376 /// playhead standing in that overhang is answered by the caption's own
6377 /// piece: it scales about the held clip's head by the held clip's own
6378 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
6379 #[test]
6380 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
6381 let caption = |start: u32, frames: u32| SubClip {
6382 start,
6383 frames,
6384 track: 0,
6385 in_us: 0,
6386 out_us: i64::from(frames) * 1_000_000,
6387 link: None,
6388 };
6389 let track = || SubtitleTrack {
6390 path: FILE.into(),
6391 track: None,
6392 language: "eng".into(),
6393 name: String::new(),
6394 label: "eng".into(),
6395 cues: Vec::new(),
6396 bitmap: false,
6397 refused: None,
6398 };
6399 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6400 let s1 = p.add_lane(LaneKind::Subtitle);
6401 // The caption spans [80, 100) -- ten frames past the clip's own end
6402 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6403 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6404 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6405 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6406 // no clip member's old span reaches, is the caption's own question:
6407 // half of 95 is 47.5, rounded to 48.
6408 assert_eq!(
6409 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6410 Some(48),
6411 "the overhang frame answers through the caption's own piece"
6412 );
6413 }
6414
6415 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6416 /// map ([`map`]'s architecture law): a caption's landed span comes from
6417 /// the map's own ends, and the playhead standing at the caption's own
6418 /// last frame before the write has to land exactly where the write put
6419 /// it -- across clip lengths and rates that round differently, and an
6420 /// odd-length caption straddling the clip's own tail edge, the corner
6421 /// where `write_speed` used to answer a frame short.
6422 #[test]
6423 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6424 let caption = |start: u32, frames: u32| SubClip {
6425 start,
6426 frames,
6427 track: 0,
6428 in_us: 0,
6429 out_us: i64::from(frames) * 1_000_000,
6430 link: None,
6431 };
6432 let track = || SubtitleTrack {
6433 path: FILE.into(),
6434 track: None,
6435 language: "eng".into(),
6436 name: String::new(),
6437 label: "eng".into(),
6438 cues: Vec::new(),
6439 bitmap: false,
6440 refused: None,
6441 };
6442 for &len in &[90u32, 91, 177, 300, 301] {
6443 for &permille in &[500u16, 2000, 2500, 3000] {
6444 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6445 let s1 = p.add_lane(LaneKind::Subtitle);
6446 // An odd-length caption straddling the clip's tail edge: its
6447 // own last frame lands past the held clip.
6448 let c_start = len.saturating_sub(3);
6449 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6450 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6451 let speed = Speed::from_permille(permille);
6452 let last = c_start + 7 - 1;
6453 let mapped = p
6454 .speeded_playhead(Lane::V1, 0, speed, last)
6455 .expect("the caption is there");
6456 if p.set_speed(Lane::V1, 0, speed).is_err() {
6457 continue; // a refusal changes nothing: not this law's cell
6458 }
6459 let landed = p.sub_lane(s1)[0];
6460 if permille >= 1000 {
6461 // A speed-up compresses the timeline: many old frames
6462 // share one new frame, so the caption's own last old
6463 // frame lands flush with the write's own boundary --
6464 // the exact law [`write_speed`]'s worked drift-fix case
6465 // is stated against.
6466 assert_eq!(
6467 mapped,
6468 landed.end() - 1,
6469 "len {len} permille {permille}: the playhead at the caption's own \
6470 last frame lands where the write actually put it"
6471 );
6472 } else {
6473 // A slow-down expands it: one old frame becomes several
6474 // new ones, and `apply` answers where that frame's own
6475 // block *starts*, not where the caption's last new
6476 // frame (the end of that same block) sits -- a
6477 // one-frame gap inherent to the piece's own semantics,
6478 // not a drift between the two callers. Both still have
6479 // to agree the answer sits inside the caption the write
6480 // actually landed.
6481 assert!(
6482 (landed.start..landed.end()).contains(&mapped),
6483 "len {len} permille {permille}: the playhead lands inside the \
6484 caption the write actually put ({landed:?}), got {mapped}"
6485 );
6486 }
6487 }
6488 }
6489 }
6490
6491 /// A grouped caption's cues re-time with its clip: the placement's window
6492 /// crossed the timeline at its own proportion before any rate, and a
6493 /// re-rate changes that proportion (the frames compress, the window does
6494 /// not). A cue eight seconds into a window played at 2x crosses the screen
6495 /// four seconds in -- and at unity every cue lands exactly where it always
6496 /// did, byte for byte.
6497 #[test]
6498 fn a_grouped_captions_cues_re_time_with_its_clip() {
6499 let track = SubtitleTrack {
6500 path: FILE.into(),
6501 track: None,
6502 language: "eng".into(),
6503 name: String::new(),
6504 label: "eng".into(),
6505 cues: vec![crate::subtitle::Cue {
6506 start_us: 8_000_000,
6507 end_us: 9_000_000,
6508 text: "late line".into(),
6509 image: None,
6510 }],
6511 bitmap: false,
6512 refused: None,
6513 };
6514 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6515 let s1 = p.add_lane(LaneKind::Subtitle);
6516 // Ten seconds of the track over ten seconds of timeline: unity.
6517 p.place_sub(
6518 s1,
6519 0,
6520 SubClip {
6521 start: 0,
6522 frames: 300,
6523 track: 0,
6524 in_us: 0,
6525 out_us: 10_000_000,
6526 link: None,
6527 },
6528 )
6529 .expect("placed");
6530
6531 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6532 let unity = p.sub_lane_cues(s1, FPS);
6533 assert_eq!(
6534 unity
6535 .iter()
6536 .map(|c| (c.start_us, c.end_us, &*c.text))
6537 .collect::<Vec<_>>(),
6538 [(8_000_000, 9_000_000, "late line")],
6539 "a unity placement maps exactly as it always did"
6540 );
6541
6542 // Grouped with the clip and re-rated to 2x: the same window now crosses
6543 // in half the time, so the cue at 8s of it lands 4s in.
6544 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6545 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6546 .expect("room for it");
6547 let re_timed = p.sub_lane_cues(s1, FPS);
6548 assert_eq!(
6549 re_timed
6550 .iter()
6551 .map(|c| (c.start_us, c.end_us))
6552 .collect::<Vec<_>>(),
6553 [(4_000_000, 4_500_000)],
6554 "the cue crosses with the clip's new rate"
6555 );
6556 }
6557
6558 /// A video arriving on a timeline of words mutates none of them: the
6559 /// import's rippling insert used to open room on the subtitle lanes too,
6560 /// splitting a caption it landed inside and sliding the rest behind the
6561 /// video -- the hand asked for an add, and got a cut it never made. The
6562 /// words keep their own clock; co-travel is what a group is for.
6563 #[test]
6564 fn an_arriving_clip_never_touches_the_captions() {
6565 let caption = |start: u32, frames: u32| SubClip {
6566 start,
6567 frames,
6568 track: 0,
6569 in_us: i64::from(start) * 1_000_000 / 30,
6570 out_us: i64::from(start + frames) * 1_000_000 / 30,
6571 link: None,
6572 };
6573 let track = || SubtitleTrack {
6574 path: FILE.into(),
6575 track: None,
6576 language: "eng".into(),
6577 name: String::new(),
6578 label: "eng".into(),
6579 cues: Vec::new(),
6580 bitmap: false,
6581 refused: None,
6582 };
6583 // A timeline of words alone: 60 frames of caption, no media clips.
6584 let mut p = Project::single(FILE, 60)
6585 .with_subtitles(vec![track()]);
6586 for l in [Lane::V1, Lane::A1] {
6587 while !p.lane(l).is_empty() {
6588 p.lift(l, 0);
6589 }
6590 }
6591 let s1 = p.add_lane(LaneKind::Subtitle);
6592 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6593 let before = p.sub_lane(s1).to_vec();
6594
6595 // The video lands BEFORE the caption's span: nothing moves.
6596 let vid = clip(0, 0, 30, 0);
6597 assert!(p.paste(0, vid), "the video goes down at the head");
6598 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6599
6600 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6601 // byte the placement the hand made.
6602 assert!(p.paste(15, vid), "a second video lands inside the caption");
6603 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6604 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6605 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6606 assert!(links_are_consistent(&p.lanes).is_ok());
6607 }
6608
6609 /// The region's caption pieces re-time by mapped boundaries forced apart:
6610 /// rounding start and length independently can land two cues on one frame,
6611 /// and the artifact is clamped -- one frame each, in order, none past the
6612 /// region's new end -- never an overlap on the lane.
6613 #[test]
6614 fn a_regions_caption_pieces_never_round_onto_one_another() {
6615 let caption = |start: u32, frames: u32| SubClip {
6616 start,
6617 frames,
6618 track: 0,
6619 in_us: 0,
6620 out_us: i64::from(frames) * 1_000_000,
6621 link: None,
6622 };
6623 let track = |n| SubtitleTrack {
6624 path: FILE.into(),
6625 track: None,
6626 language: "eng".into(),
6627 name: String::new(),
6628 label: format!("eng{n}"),
6629 cues: Vec::new(),
6630 bitmap: false,
6631 refused: None,
6632 };
6633 // Three lanes, one repro shape each: adjacent one-frame cues, a
6634 // three-frame pair, and the region's last cue against the first
6635 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6636 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6637 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6638 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6639 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6640 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6641 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6642 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6643 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6644
6645 let mut scope = vec![Lane::V1, Lane::A1];
6646 scope.extend(lanes.iter().copied());
6647 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6648 .expect("the region speeds up");
6649 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6650 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6651 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6652 };
6653 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6654 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6655 // and the walk pushes the second to where the first ends.
6656 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6657 // The last cue of the region ends exactly where the region now does
6658 // (frame 15), and the caption behind it lands on that same frame:
6659 // touching, never overlapping.
6660 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6661 for &lane in &lanes {
6662 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6663 }
6664 }
6665
6666 /// The scope law names a caption half too: a scoped cut that would move one
6667 // track of a group whose caption sits outside the scope is refused.
6668 #[test]
6669 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6670 let caption = |start: u32, frames: u32| SubClip {
6671 start,
6672 frames,
6673 track: 0,
6674 in_us: 0,
6675 out_us: i64::from(frames) * 1_000_000,
6676 link: None,
6677 };
6678 let track = || SubtitleTrack {
6679 path: FILE.into(),
6680 track: None,
6681 language: "eng".into(),
6682 name: String::new(),
6683 label: "eng".into(),
6684 cues: Vec::new(),
6685 bitmap: false,
6686 refused: None,
6687 };
6688 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6689 let s1 = p.add_lane(LaneKind::Subtitle);
6690 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6691 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6692
6693 // The subtitle lane is not in the scope, so the group's caption half
6694 // sits outside it: refused, in the law's own words.
6695 let err = p
6696 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6697 .unwrap_err()
6698 .to_string();
6699 assert!(
6700 err.contains("is one take with the S1 caption at frame 0"),
6701 "{err}"
6702 );
6703
6704 // ...and with the caption's lane in the scope, the cut carries it:
6705 // the words over the hole go, and the words behind slide up.
6706 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6707 .expect("the whole group is in the scope");
6708 let subs = p.sub_lane(s1);
6709 assert_eq!(
6710 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6711 [(0, 10), (10, 75)],
6712 "the caption is cut and shifted with the clips"
6713 );
6714 }
6715
6716 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6717 /// mates riding along, the offsets kept, the refusals in words.
6718 #[test]
6719 fn a_hand_built_group_holds_clips_and_a_caption() {
6720 let caption = |start: u32, frames: u32| SubClip {
6721 start,
6722 frames,
6723 track: 0,
6724 in_us: 0,
6725 out_us: i64::from(frames) * 1_000_000,
6726 link: None,
6727 };
6728 let track = || SubtitleTrack {
6729 path: FILE.into(),
6730 track: None,
6731 language: "eng".into(),
6732 name: String::new(),
6733 label: "eng".into(),
6734 cues: Vec::new(),
6735 bitmap: false,
6736 refused: None,
6737 };
6738 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6739 let v2 = p.add_lane(LaneKind::Video);
6740 let s1 = p.add_lane(LaneKind::Subtitle);
6741 // A layer at its own offset, and a caption over the head of the take.
6742 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6743 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6744
6745 // Too few, one lane twice, and an index that is not there: words, no
6746 // snapshot.
6747 let history = p.history.len();
6748 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6749 assert!(p
6750 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6751 .unwrap_err()
6752 .to_string()
6753 .contains("V1 is picked twice"));
6754 assert!(p
6755 .group_all(&[(Lane::V1, 0), (s1, 9)])
6756 .unwrap_err()
6757 .to_string()
6758 .contains("no subtitle 9"));
6759 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6760
6761 // The group: the picture, the layer, and the caption -- and the sound
6762 // the picture was already grouped with comes along unasked.
6763 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6764 .expect("three picks, three lanes");
6765 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6766 for lane in [Lane::V1, Lane::A1, v2] {
6767 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6768 }
6769 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6770 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6771 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6772 assert!(links_are_consistent(&p.lanes).is_ok());
6773 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6774
6775 // ...and one undo takes it apart again.
6776 assert!(p.undo());
6777 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
6778
6779 // Detach names a caption like it names a clip: every member an id of
6780 // its own, which is never `None` (see `ungroup`).
6781 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
6782 assert!(p.ungroup(s1, 0));
6783 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
6784 assert!(loose_sub.is_some() && loose_clip.is_some());
6785 assert_ne!(loose_sub, loose_clip);
6786 assert!(links_are_consistent(&p.lanes).is_ok());
6787 }
6788
6789 /// Two captions on one sub lane, each already grouped with a *different*
6790 /// clip: `group_all` over both those clips would merge the two existing
6791 /// groups into one id and leave both captions on `s1` carrying it --
6792 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
6793 /// group closes. Refused by name, and nothing moves.
6794 #[test]
6795 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
6796 let caption = |start: u32, frames: u32| SubClip {
6797 start,
6798 frames,
6799 track: 0,
6800 in_us: 0,
6801 out_us: i64::from(frames) * 1_000_000,
6802 link: None,
6803 };
6804 let track = || SubtitleTrack {
6805 path: FILE.into(),
6806 track: None,
6807 language: "eng".into(),
6808 name: String::new(),
6809 label: "eng".into(),
6810 cues: Vec::new(),
6811 bitmap: false,
6812 refused: None,
6813 };
6814 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6815 let v2 = p.add_lane(LaneKind::Video);
6816 let s1 = p.add_lane(LaneKind::Subtitle);
6817 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
6818 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
6819 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6820 // V1 grouped with the first caption, v2 with the second -- two
6821 // separate groups, each already one member per lane.
6822 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6823 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
6824 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
6825
6826 let history = p.history.len();
6827 let err = p
6828 .group_all(&[(Lane::V1, 0), (v2, 0)])
6829 .unwrap_err()
6830 .to_string();
6831 assert!(err.contains("one placement per lane"), "{err}");
6832 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
6833 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
6834 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
6835 assert!(links_are_consistent(&p.lanes).is_ok());
6836 }
6837
6838 /// A split hands the caption of a group the same ids it hands the clips:
6839 /// the left halves keep the group, the right halves share a fresh one.
6840 #[test]
6841 fn a_split_cuts_a_grouped_caption_with_its_clips() {
6842 let caption = |start: u32, frames: u32| SubClip {
6843 start,
6844 frames,
6845 track: 0,
6846 in_us: 0,
6847 out_us: i64::from(frames) * 1_000_000,
6848 link: None,
6849 };
6850 let track = || SubtitleTrack {
6851 path: FILE.into(),
6852 track: None,
6853 language: "eng".into(),
6854 name: String::new(),
6855 label: "eng".into(),
6856 cues: Vec::new(),
6857 bitmap: false,
6858 refused: None,
6859 };
6860 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6861 let s1 = p.add_lane(LaneKind::Subtitle);
6862 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
6863 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6864 let take = p.lane(Lane::V1)[0].link.expect("the group id");
6865
6866 assert!(p.split(4));
6867 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6868 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6869 assert_eq!(left.frames, 4);
6870 assert_eq!(
6871 right.link,
6872 p.lane(Lane::V1)[1].link,
6873 "the caption's tail shares the clips' fresh id"
6874 );
6875 assert_ne!(right.link, Some(take));
6876 assert!(links_are_consistent(&p.lanes).is_ok());
6877
6878 // Regroup at the seam restores the take, caption included.
6879 assert!(p.regroup(4));
6880 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6881 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6882 }
6883
6884 /// Deleting a member of a hand-built group takes the group: every
6885 /// member's own span out of its own lane, hole closed -- the lanes may
6886 /// end up out of step, which is what one undo restores together.
6887 #[test]
6888 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6889 let caption = |start: u32, frames: u32| SubClip {
6890 start,
6891 frames,
6892 track: 0,
6893 in_us: 0,
6894 out_us: i64::from(frames) * 1_000_000,
6895 link: None,
6896 };
6897 let track = || SubtitleTrack {
6898 path: FILE.into(),
6899 track: None,
6900 language: "eng".into(),
6901 name: String::new(),
6902 label: "eng".into(),
6903 cues: Vec::new(),
6904 bitmap: false,
6905 refused: None,
6906 };
6907 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6908 let s1 = p.add_lane(LaneKind::Subtitle);
6909 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6910 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6911 // A neighbour on a lane the group does not touch.
6912 let v2 = p.add_lane(LaneKind::Video);
6913 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6914
6915 // By the picture or by the caption, the same whole-group delete.
6916 assert!(p.delete_sub_in(s1, 0));
6917 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6918 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6919 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6920 assert!(links_are_consistent(&p.lanes).is_ok());
6921 assert!(p.undo(), "one step puts the group back");
6922 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6923 }
6924
6925 /// The delete law, one statement for every anchor: a caption deleted
6926 /// WITH its group ripples its lane exactly as its clip siblings do --
6927 /// the hole closes and what follows slides up -- while a caption lifted
6928 /// alone leaves its gap, as it always has. And the delete of a grouped
6929 /// clip takes the group from whichever member was clicked.
6930 #[test]
6931 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
6932 let caption = |start: u32, frames: u32| SubClip {
6933 start,
6934 frames,
6935 track: 0,
6936 in_us: 0,
6937 out_us: i64::from(frames) * 1_000_000,
6938 link: None,
6939 };
6940 let track = || SubtitleTrack {
6941 path: FILE.into(),
6942 track: None,
6943 language: "eng".into(),
6944 name: String::new(),
6945 label: "eng".into(),
6946 cues: Vec::new(),
6947 bitmap: false,
6948 refused: None,
6949 };
6950 // V+A+S grouped, with a second caption BEHIND the group's caption:
6951 // closing the hole is what the second caption's position says.
6952 let group = || {
6953 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6954 let s1 = p.add_lane(LaneKind::Subtitle);
6955 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6956 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6957 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6958 (p, s1)
6959 };
6960
6961 // Deleted by the picture: all three lanes close.
6962 let (mut p, s1) = group();
6963 assert!(p.delete_in(Lane::V1, 0));
6964 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6965 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6966 assert_eq!(
6967 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6968 [60],
6969 "the caption's lane closed by its own span: the follower slid up"
6970 );
6971 assert!(p.undo(), "one step");
6972 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6973
6974 // By the sound: the same whole-group delete.
6975 let (mut p, s1) = group();
6976 assert!(p.delete_in(Lane::A1, 0));
6977 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6978 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6979
6980 // By the caption itself: the same again.
6981 let (mut p, s1) = group();
6982 assert!(p.delete_sub_in(s1, 0));
6983 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6984 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6985 assert!(links_are_consistent(&p.lanes).is_ok());
6986
6987 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6988 // unchanged.
6989 let (mut p, s1) = group();
6990 assert!(p.ungroup(s1, 0), "the caption stands alone");
6991 assert!(p.lift_sub(s1, 0));
6992 assert_eq!(
6993 p.sub_lane(s1)[0].start, 90,
6994 "the follower stayed put: a lone caption's lift is a gap"
6995 );
6996 }
6997
6998 /// Dragging a grouped caption carries its clips, one delta for all of them
6999 /// -- and a caption in no group refuses an overlap exactly as it always did.
7000 #[test]
7001 fn dragging_a_grouped_caption_carries_its_group() {
7002 let caption = |start: u32, frames: u32| SubClip {
7003 start,
7004 frames,
7005 track: 0,
7006 in_us: 0,
7007 out_us: i64::from(frames) * 1_000_000,
7008 link: None,
7009 };
7010 let track = || SubtitleTrack {
7011 path: FILE.into(),
7012 track: None,
7013 language: "eng".into(),
7014 name: String::new(),
7015 label: "eng".into(),
7016 cues: Vec::new(),
7017 bitmap: false,
7018 refused: None,
7019 };
7020 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7021 let s1 = p.add_lane(LaneKind::Subtitle);
7022 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7023 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7024
7025 // Same lane, further along: everyone moves by the same eight frames.
7026 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
7027 assert_eq!(p.sub_lane(s1)[0].start, 10);
7028 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
7029 assert!(links_are_consistent(&p.lanes).is_ok());
7030
7031 // ...and an ungrouped caption is the caption it always was.
7032 assert!(p.ungroup(s1, 0));
7033 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
7034 let s1 = q.add_lane(LaneKind::Subtitle);
7035 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
7036 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
7037 assert!(q
7038 .move_sub(s1, 0, s1, 3)
7039 .unwrap_err()
7040 .to_string()
7041 .contains("already covers"));
7042 }
7043
7044 /// A trim carries a group's caption by the same delta as its clips, clamped
7045 /// to the caption's own walls -- the offsets between the members survive.
7046 #[test]
7047 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
7048 let caption = |start: u32, frames: u32| SubClip {
7049 start,
7050 frames,
7051 track: 0,
7052 in_us: 0,
7053 out_us: i64::from(frames) * 1_000_000,
7054 link: None,
7055 };
7056 let track = || SubtitleTrack {
7057 path: FILE.into(),
7058 track: None,
7059 language: "eng".into(),
7060 name: String::new(),
7061 label: "eng".into(),
7062 cues: Vec::new(),
7063 bitmap: false,
7064 refused: None,
7065 };
7066 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7067 let s1 = p.add_lane(LaneKind::Subtitle);
7068 // The caption sits two frames into the take and ends one early. The
7069 // source runs past the clip, or there is no tail to pull out.
7070 let src = &[20];
7071 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
7072 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7073
7074 // The tail goes out by three: the clip to 12, the caption to 11.
7075 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
7076 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
7077 assert_eq!(
7078 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
7079 (2, 11),
7080 "the caption follows by the delta"
7081 );
7082 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
7083
7084 // The head comes in by two: everyone's start moves two along.
7085 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
7086 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
7087 assert!(links_are_consistent(&p.lanes).is_ok());
7088 }
7089
7090 #[test]
7091 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
7092 let mut p = three();
7093 let before = shape(&p);
7094 assert!(!p.split(0), "timeline 0 has nothing before it");
7095 assert!(!p.split(3), "existing boundary");
7096 assert!(!p.split(5), "existing boundary");
7097 assert!(!p.split(9), "one past the last frame");
7098 assert!(!p.split(1_000));
7099 assert_eq!(shape(&p), before);
7100 // one undo lands before the *second* split, so the refusals pushed nothing
7101 assert!(p.undo());
7102 assert_eq!(p.clips().len(), 2, "refused splits push no history");
7103
7104 // ...and a frame that is a gap in both lanes has nothing to split.
7105 let mut p = three();
7106 assert!(p.lift(Lane::V1, 1));
7107 assert!(p.lift(Lane::A1, 1));
7108 assert!(!p.split(4), "a gap is not a clip");
7109 }
7110
7111 #[test]
7112 fn regroup_refuses_what_a_split_could_not_have_made() {
7113 let mut p = three();
7114 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
7115 assert!(p.regroup(5));
7116 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
7117 // A boundary with a gap on one side, and one where the sources do not
7118 // meet, are both refused.
7119 let mut p = three();
7120 assert!(p.lift(Lane::V1, 1));
7121 assert!(p.lift(Lane::A1, 1));
7122 assert!(!p.regroup(3), "nothing starts at 3 any more");
7123 let mut p = three();
7124 for l in p.lanes() {
7125 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
7126 }
7127 assert!(!p.regroup(3), "source 100 does not follow source 3");
7128 assert!(!p.regroup(0), "nothing ends at 0");
7129 assert!(!p.regroup(1_000));
7130 }
7131
7132 #[test]
7133 fn map_and_spans_sweep_every_boundary() {
7134 let p = three();
7135 assert_eq!(p.timeline_frames(), 9);
7136 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
7137 // contiguous source here, so the clip index is what actually moves
7138 let expect = [
7139 (0, (0, 0)),
7140 (1, (0, 1)),
7141 (2, (0, 2)),
7142 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
7143 (4, (1, 4)),
7144 (5, (2, 5)),
7145 (6, (2, 6)),
7146 (7, (2, 7)),
7147 (8, (2, 8)),
7148 ];
7149 for (t, want) in expect {
7150 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
7151 }
7152 assert_eq!(p.map_timeline(9), None);
7153 // A span is the rest of the clip from where it was asked about.
7154 assert_eq!(
7155 p.span_at(Lane::V1, 6),
7156 Some(Span {
7157 start: 6,
7158 len: 3,
7159 from: Some((0, 6)),
7160 speed: Speed::NORMAL
7161 })
7162 );
7163 assert_eq!(p.span_at(Lane::V1, 9), None);
7164 }
7165
7166 /// The fit policy is one byte *in* the clip rather than an index into a
7167 /// table like the eq and the grade: there is nothing for a table to share.
7168 /// It costs the clip nothing at all -- the fields before it (a `usize`
7169 /// source and two `Option<u16>`s) already left the struct padded to 40
7170 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
7171 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
7172 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
7173 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
7174 /// words after it pads out to the next multiple of 8: 56 bytes total.
7175 /// The transform index is a third `Option<u16>`, same reason as the eq and
7176 /// colour ones before it -- it lands in bytes already spent on padding, so
7177 /// the struct still costs 56.
7178 /// This is the assert that says so: a clip that grows a word grows every
7179 /// undo snapshot and every clipboard copy with it.
7180 #[test]
7181 fn a_fit_policy_costs_the_clip_no_word() {
7182 assert_eq!(
7183 std::mem::size_of::<Clip>(),
7184 56,
7185 "Clip changed size: {} bytes",
7186 std::mem::size_of::<Clip>()
7187 );
7188 }
7189
7190 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
7191 /// anything in `three()` so it is recognisable wherever it lands.
7192 const PASTED: Clip = Clip {
7193 fade_in: 0,
7194 fade_out: 0,
7195 transition_out: 0,
7196 start: 0,
7197 in_frame: 100,
7198 out_frame: 102,
7199 source: 0,
7200 link: None,
7201 eq: None,
7202 color: None,
7203 transform: None,
7204 fit: FitPolicy::Fit,
7205 speed: Speed::NORMAL,
7206 };
7207
7208 #[test]
7209 fn paste_mid_clip_splits_around_it() {
7210 let mut p = three();
7211 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
7212 assert_eq!(p.timeline_frames(), 11);
7213 assert_eq!(
7214 shape(&p)[0],
7215 vec![
7216 clip(0, 0, 3, 0),
7217 clip(3, 3, 5, 0),
7218 clip(5, 5, 6, 0),
7219 clip(6, 100, 102, 0),
7220 clip(8, 6, 9, 0),
7221 ]
7222 );
7223 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
7224 // The pasted frames are exactly where they were asked for, and the
7225 // split-off remainder resumes after them.
7226 assert_eq!(p.map_timeline(6), Some((3, 100)));
7227 assert_eq!(p.map_timeline(7), Some((3, 101)));
7228 assert_eq!(p.map_timeline(8), Some((4, 6)));
7229 }
7230
7231 #[test]
7232 fn paste_at_boundary_zero_and_end() {
7233 let mut p = three();
7234 assert!(p.paste(3, PASTED), "existing boundary: no split");
7235 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
7236 assert_eq!(p.map_timeline(3), Some((1, 100)));
7237
7238 let mut p = three();
7239 assert!(p.paste(0, PASTED));
7240 assert_eq!(p.map_timeline(0), Some((0, 100)));
7241 assert_eq!(p.map_timeline(2), Some((1, 0)));
7242
7243 // At the end: appended, there being nothing in front to leave black.
7244 let mut p = three();
7245 assert!(p.paste(9, PASTED));
7246 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
7247 // Past it: down on the frame it was asked for, black in front of it --
7248 // a row let go on the open bed lands under the ghost that promised it.
7249 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
7250 assert!(p.paste(1_000, PASTED));
7251 assert_eq!(p.timeline_frames(), 1_002);
7252 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
7253 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
7254
7255 // An empty clip is the one thing refused, and it pushes no history.
7256 let mut p = three();
7257 assert!(!p.paste(4, clip(0, 7, 7, 0)));
7258 assert_eq!(p.clips().len(), 3);
7259 }
7260
7261 /// The data-loss paste: a clip of a source with no picture used to land on
7262 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
7263 /// carried it was refused on the way back in ("a box with a larger size").
7264 #[test]
7265 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
7266 let mut p = three();
7267 let wav = p.import("/nonexistent/song.wav", 0);
7268 let copied = Clip {
7269 fade_in: 0,
7270 fade_out: 0,
7271 transition_out: 0,
7272 source: wav,
7273 ..PASTED
7274 };
7275 assert!(p.paste(3, copied));
7276 // The room is opened on every lane, or the two would slide apart...
7277 assert_eq!(p.timeline_frames(), 11);
7278 assert_eq!(
7279 shape(&p)[0],
7280 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
7281 "the video lane got room and nothing else"
7282 );
7283 // ...but the clip itself only reaches the lane that can play it.
7284 assert_eq!(
7285 shape(&p)[1],
7286 vec![
7287 clip(0, 0, 3, 0),
7288 clip(3, 100, 102, wav),
7289 clip(5, 3, 5, 0),
7290 clip(7, 5, 9, 0)
7291 ]
7292 );
7293 // A source with a picture is unchanged: still the grouped pair.
7294 let mut p = three();
7295 assert!(p.paste(3, PASTED));
7296 assert_eq!(shape(&p)[0], shape(&p)[1]);
7297 }
7298
7299 /// A hand-written file may hold a clip that ends at the very last frame
7300 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
7301 /// to wrap its start round to the front of the lane: an overlap in debug, a
7302 /// project no reload would accept in release.
7303 #[test]
7304 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
7305 let far = clip(u32::MAX - 90, 0, 90, 0);
7306 let parts = |c: Clip| {
7307 Project::from_parts(
7308 vec![Source::new(FILE, 0)],
7309 two(vec![c], vec![c]),
7310 Vec::new(),
7311 Vec::new(),
7312 Vec::new(),
7313 )
7314 .expect("valid parts")
7315 };
7316 let mut p = parts(far);
7317 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
7318 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
7319 assert!(!p.undo(), "...and pushes no history either");
7320 assert!(
7321 !p.paste(u32::MAX, PASTED),
7322 "appending has nowhere to go either: the timeline ends at the last frame"
7323 );
7324 // With room for exactly those frames the same paste is taken.
7325 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
7326 assert!(p.paste(0, PASTED));
7327 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
7328 }
7329
7330 #[test]
7331 fn paste_undoes_in_one_step() {
7332 let mut p = three();
7333 let before = shape(&p);
7334 assert!(p.paste(6, PASTED));
7335 assert!(p.undo());
7336 assert_eq!(shape(&p), before, "a paste is one undo step");
7337 }
7338
7339 #[test]
7340 fn a_copy_outlives_the_clip_it_came_from() {
7341 let mut p = three();
7342 let copied = p.clips()[1]; // [3,5)
7343 assert!(p.delete(1));
7344 // Just a frame range: the source is still on disk either way.
7345 assert!(p.paste(0, copied));
7346 assert_eq!(p.map_timeline(0), Some((0, 3)));
7347 assert_eq!(p.timeline_frames(), 9);
7348 }
7349
7350 #[test]
7351 fn delete_closes_the_gap_on_both_lanes() {
7352 let mut p = three();
7353 assert!(p.delete(1));
7354 assert_eq!(p.timeline_frames(), 7);
7355 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
7356 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
7357 // timeline 3 used to be source 3; the gap closed so it is source 5 now
7358 assert_eq!(p.map_timeline(3), Some((1, 5)));
7359 assert_eq!(p.map_timeline(6), Some((1, 8)));
7360 assert_eq!(p.map_timeline(7), None);
7361 }
7362
7363 #[test]
7364 fn delete_first_last_and_only() {
7365 let mut p = three();
7366 assert!(p.delete(0));
7367 assert_eq!(p.map_timeline(0), Some((0, 3)));
7368 assert_eq!(p.timeline_frames(), 6);
7369
7370 let mut p = three();
7371 assert!(p.delete(2));
7372 assert_eq!(p.timeline_frames(), 5);
7373 assert_eq!(p.map_timeline(4), Some((1, 4)));
7374
7375 assert!(!p.delete(2), "index past the end");
7376 assert!(p.delete(1));
7377 assert!(p.delete(0), "and the last remaining clip goes too");
7378 assert_eq!(p.clips().len(), 0);
7379 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
7380 assert!(!p.delete(0), "there is nothing left to delete");
7381 assert!(p.undo(), "one gesture, one undo");
7382 assert_eq!(p.clips().len(), 1);
7383 }
7384
7385 /// The offset model's point: one lane loses a clip, the other does not move.
7386 #[test]
7387 fn a_lift_leaves_a_gap_and_moves_nothing() {
7388 let mut p = three();
7389 let video_before = shape(&p)[0].clone();
7390 assert!(p.lift(Lane::A1, 1));
7391 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7392 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7393 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7394 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7395 assert_eq!(p.map(Lane::A1, 4), None);
7396 assert_eq!(
7397 p.span_at(Lane::A1, 3),
7398 Some(Span {
7399 start: 3,
7400 len: 2,
7401 from: None,
7402 speed: Speed::NORMAL
7403 })
7404 );
7405 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7406 assert!(p.undo());
7407 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7408 }
7409
7410 #[test]
7411 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7412 let mut p = three();
7413 assert!(p.lift(Lane::A1, 2));
7414 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7415 assert_eq!(
7416 p.span_at(Lane::A1, 5),
7417 Some(Span {
7418 start: 5,
7419 len: 4,
7420 from: None,
7421 speed: Speed::NORMAL
7422 }),
7423 "the audio lane holds silence to the end of the picture"
7424 );
7425 assert_eq!(p.span_at(Lane::A1, 9), None);
7426 // Every lane covers the timeline exactly, gaps included.
7427 for l in p.lanes() {
7428 let spans = p.spans_from(l, 0);
7429 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7430 assert_eq!(spans[0].start, 0);
7431 }
7432 }
7433
7434 /// The timeline is emptiable: the last placement comes off like any other,
7435 /// the project holds "nothing on any lane" as a state, and one undo per
7436 /// gesture brings it back.
7437 #[test]
7438 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7439 let mut p = Project::single(FILE, 9);
7440 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7441 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7442 assert_eq!(p.timeline_frames(), 0);
7443 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7444 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7445 assert!(!p.lift(Lane::A1, 0), "index past the end");
7446 assert!(p.undo(), "and the last lift comes back");
7447 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7448 // A saved-and-loaded empty timeline is a project like any other, and it
7449 // still names the file its frame rate came from.
7450 assert!(p.lift(Lane::V1, 0));
7451 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7452 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7453 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7454 assert_eq!(back.timeline_frames(), 0);
7455 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7456 }
7457
7458 /// What a keyboard selection walks: one answer per lane, gaps included --
7459 /// the composite's own answer is one lane's and cannot say what the audio
7460 /// lane holds under the same playhead.
7461 #[test]
7462 fn lane_clip_at_answers_for_each_lane_separately() {
7463 let mut p = Project::single(FILE, 9);
7464 assert!(p.split(3), "both lanes split");
7465 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7466 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7467 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7468 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7469 // A gap on one lane leaves the other's clip selectable there.
7470 assert!(p.lift(Lane::A1, 0));
7471 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7472 assert_eq!(
7473 p.lane_clip_at(Lane::A1, 3),
7474 Some(0),
7475 "indices moved with it"
7476 );
7477 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7478 // A lane that is not there is not a panic.
7479 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7480 }
7481
7482 #[test]
7483 fn place_overwrites_only_its_own_lane() {
7484 let mut p = three();
7485 let audio_before = shape(&p)[1].clone();
7486 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7487 // is trimmed, nothing shifts.
7488 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7489 assert_eq!(
7490 shape(&p)[0],
7491 vec![
7492 clip(0, 0, 3, 0),
7493 clip(3, 3, 4, 0),
7494 clip(4, 100, 102, 0),
7495 clip(6, 6, 9, 0),
7496 ]
7497 );
7498 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7499 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7500
7501 // Placed inside one clip, it splits it in two.
7502 let mut p = Project::single(FILE, 9);
7503 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7504 assert_eq!(
7505 shape(&p)[0],
7506 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7507 );
7508 // ...and placed past the end it makes a gap, which is the whole point.
7509 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7510 assert_eq!(p.timeline_frames(), 22);
7511 assert_eq!(
7512 p.span_at(Lane::V1, 9),
7513 Some(Span {
7514 start: 9,
7515 len: 11,
7516 from: None,
7517 speed: Speed::NORMAL
7518 })
7519 );
7520 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7521 }
7522
7523 /// A file with sound let go over a further video track: both halves go down,
7524 /// on the same frames, and the audio row is added when the `+ V` button left
7525 /// the project without one. One undo takes the lane and both clips back.
7526 #[test]
7527 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7528 let mut p = three();
7529 let v2 = p.add_lane(LaneKind::Video);
7530 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7531
7532 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7533 let a2 = Lane::new(LaneKind::Audio, 1);
7534 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7535 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7536 assert_eq!(p.lane(v2)[0].start, 4);
7537 assert_eq!(p.lane(v2)[0].end(), 6);
7538 assert_eq!(
7539 p.lane(v2)[0].link,
7540 p.lane(a2)[0].link,
7541 "one take, not two placements"
7542 );
7543 assert!(p.lane(v2)[0].link.is_some());
7544 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7545 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7546
7547 // The pair overwrites its own two lanes and nothing else, exactly as a
7548 // one-lane place does.
7549 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7550 assert_eq!(p.lane(v2), p.lane(a2));
7551 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7552 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7553
7554 assert!(p.undo(), "one step for the second pair");
7555 assert_eq!(p.lane(v2).len(), 1);
7556 assert!(p.undo(), "one step for the first pair *and* its lane");
7557 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7558 assert!(p.lane(v2).is_empty());
7559
7560 // Refusals cost nothing: sound placed alone is `place`'s door.
7561 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7562 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7563 assert!(
7564 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7565 "a lane that is not there"
7566 );
7567 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7568 }
7569
7570 /// The drag between tracks: let go at the frames it already covers the clip
7571 /// keeps them, one undo takes it back, and every way it can be refused
7572 /// leaves the project untouched.
7573 #[test]
7574 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7575 let v2 = Lane::new(LaneKind::Video, 1);
7576 let mut p = three();
7577 assert_eq!(p.add_lane(LaneKind::Video), v2);
7578 let before = shape(&p);
7579
7580 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7581 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7582 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7583 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7584 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7585 // One snapshot: a single undo, and the lane list survives it.
7586 assert!(p.undo());
7587 assert_eq!(shape(&p), before);
7588
7589 // A lane that is not there, the lane and frame it is already at, an
7590 // index that is not there, and a move across kinds: all refused,
7591 // nothing changed.
7592 let history = p.history.len();
7593 for (from, idx, to, start) in [
7594 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7595 (Lane::V1, 1, Lane::V1, 3),
7596 (Lane::V1, 9, v2, 3),
7597 (Lane::V1, 1, Lane::A1, 3),
7598 (Lane::A1, 1, v2, 3),
7599 ] {
7600 assert!(
7601 !p.move_clip(from, idx, to, start),
7602 "{from:?} {idx} -> {to:?} at {start}"
7603 );
7604 }
7605 assert_eq!(shape(&p), before);
7606 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7607
7608 // Landing on another clip is refused rather than overwriting it: the
7609 // pointer named the lane, never the take already sitting there.
7610 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7611 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7612 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7613 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7614 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7615 }
7616
7617 /// The drag *along* a track, which is the one every other editor has: the
7618 /// clip lands on the frame the pointer let it go at, and stops dead against
7619 /// the neighbour rather than overwriting it.
7620 #[test]
7621 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7622 let sources = vec![Source::new(FILE, 0)];
7623 let lanes = vec![
7624 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7625 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7626 ];
7627 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7628 let before = shape(&p);
7629
7630 // Into the gap, exactly where it was let go -- nothing else moves.
7631 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7632 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7633 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7634 // Dragged past the clip in front of it: clamped to its wall, laid end
7635 // to end with it, never over it.
7636 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7637 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7638 // One undo per drag, and both of them together are the state it started
7639 // in -- the frames each clip plays never changed.
7640 assert!(p.undo() && p.undo());
7641 assert_eq!(shape(&p), before);
7642
7643 // A drop that changes nothing is a click, not an edit.
7644 let history = p.history.len();
7645 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7646 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7647 }
7648
7649 /// A drag carries the whole take: the sound half travels exactly as far as
7650 /// the picture does, and the tighter of their two walls stops both.
7651 #[test]
7652 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7653 let mut p = three();
7654 assert!(
7655 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7656 "room to the right"
7657 );
7658 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7659 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7660 // Something in the sound's way, and nothing at all in the picture's.
7661 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7662 let before = shape(&p);
7663
7664 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7665 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7666 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7667 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7668 assert!(p.undo());
7669 assert_eq!(shape(&p), before, "one undo for the whole take");
7670 }
7671
7672 /// The drag that does both at once -- another lane *and* another frame --
7673 /// which is what a pointer let go over a lane always names.
7674 #[test]
7675 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7676 let v2 = Lane::new(LaneKind::Video, 1);
7677 let mut p = three();
7678 assert_eq!(p.add_lane(LaneKind::Video), v2);
7679
7680 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7681 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7682 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7683 assert_eq!(
7684 p.lane(Lane::A1)[2].start,
7685 20,
7686 "its sound travelled the same distance"
7687 );
7688 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7689 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7690 }
7691
7692 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7693 /// [`three`] cuts up all nine of its frames.
7694 const SRC: &[u32] = &[9];
7695
7696 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7697 /// else on the lane moves, and every wall stops the edge rather than
7698 /// refusing the gesture.
7699 #[test]
7700 fn trimming_the_tail_stops_at_every_wall() {
7701 let mut p = three();
7702
7703 // Pulled in: a gap opens behind it and the clip after it stays put.
7704 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7705 assert_eq!(
7706 shape(&p)[0],
7707 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7708 );
7709 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7710 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7711
7712 // ...and back out, no further than the clip behind it.
7713 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7714 assert_eq!(
7715 shape(&p)[0][1],
7716 clip(3, 3, 5, 0),
7717 "stopped at the neighbour"
7718 );
7719 assert!(
7720 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7721 "already at the wall"
7722 );
7723
7724 // One frame of clip always survives, however far back the pointer went.
7725 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7726 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7727
7728 // The last clip has no neighbour, so what stops it is the file: nine
7729 // frames is nine frames.
7730 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7731 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7732 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7733 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7734 // A source nobody told us the length of may not grow at all -- an
7735 // out-point past the end of a file is a save that will not open again.
7736 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7737 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7738 }
7739
7740 /// The head pulled in takes the in-point with it -- what stays plays what it
7741 /// always played -- and stops at the source's own first frame.
7742 #[test]
7743 fn trimming_the_head_moves_the_in_point() {
7744 let mut p = three();
7745 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7746 assert_eq!(
7747 shape(&p)[0][0],
7748 clip(2, 2, 3, 0),
7749 "two frames off the front"
7750 );
7751 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7752 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7753 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7754 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7755 // One frame survives here too.
7756 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7757 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7758
7759 // A clip that does not begin at its source's first frame: its head goes
7760 // back to source frame 0 and not one frame further.
7761 let mut p = Project::single(FILE, 9);
7762 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7763 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7764 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7765 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7766 }
7767
7768 /// A clip whose in-point is *past* its own start -- what a ripple delete
7769 /// leaves, the piece in front of it gone and this one slid back to frame 0
7770 /// carrying the in-point the cut gave it. Its head has more source behind it
7771 /// than the timeline has room for, and the timeline's own first frame is the
7772 /// wall: asking is not an overflow, and the answer is 0.
7773 #[test]
7774 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
7775 let mut p = Project::single(FILE, 9);
7776 assert!(p.split(5));
7777 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
7778 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
7779
7780 assert_eq!(
7781 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
7782 Some((0, 3)),
7783 "back to frame 0 at most, and one frame of clip always survives"
7784 );
7785 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
7786 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7787 assert_eq!(
7788 shape(&p)[0],
7789 vec![clip(2, 7, 9, 0)],
7790 "the in-point followed"
7791 );
7792 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
7793 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
7794 }
7795
7796 /// A still is trimmed from its head exactly as it is from its tail: it has
7797 /// no earlier frame to walk an in-point back to, so the wall is the length
7798 /// the caller's table allows it, measured back from the tail. Measured from
7799 /// the in-point -- which a placed picture has at 0 -- its left edge could
7800 /// never be dragged outwards at all.
7801 #[test]
7802 fn a_stills_head_stretches_out_like_its_tail() {
7803 const STILL: &str = "/nonexistent/card.png";
7804 /// What a still is held to, as `PlaybackSession` fills the table in.
7805 const CAP: &[u32] = &[60];
7806
7807 let mut p = Project::single(STILL, 20);
7808 assert!(p.lift(Lane::A1, 0), "a picture is silent");
7809 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
7810 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
7811
7812 // A source with no entry in the table may not grow, here as at the tail.
7813 assert_eq!(
7814 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
7815 Some((100, 119)),
7816 "a length nobody told us buys no head room"
7817 );
7818 assert_eq!(
7819 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
7820 Some((60, 119)),
7821 "back to a whole cap's worth, one frame of clip surviving"
7822 );
7823 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
7824 assert_eq!(
7825 shape(&p)[0][0],
7826 clip(80, 0, 40, 0),
7827 "twenty frames longer, and still read from the source's first frame"
7828 );
7829 // Past the cap is clamped, exactly as the tail is -- not refused.
7830 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
7831 assert_eq!(
7832 shape(&p)[0][0],
7833 clip(60, 0, 60, 0),
7834 "a cap's worth, no more"
7835 );
7836 // ...and the clip in front is the nearer wall of the two: no head trim
7837 // may open an overlap.
7838 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
7839 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
7840 assert_eq!(
7841 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
7842 Some((85, 119)),
7843 "up to the neighbour's last frame and not over it"
7844 );
7845 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
7846 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
7847 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
7848 }
7849
7850 /// Linked halves trim as one: a link is one span on however many lanes, so
7851 /// the sound follows the picture's edge -- and the tightest wall of the two
7852 /// is what stops both.
7853 #[test]
7854 fn linked_halves_trim_together() {
7855 let mut p = three();
7856 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
7857 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
7858
7859 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
7860 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
7861 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
7862 assert!(
7863 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
7864 "either half drags it"
7865 );
7866 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
7867 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7868
7869 // Something in the way on the *audio* lane stops the picture's tail as
7870 // well: the group can only go as far as its tightest member.
7871 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
7872 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7873 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
7874 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
7875 links_are_consistent(&p.lanes).expect("still one span");
7876 }
7877
7878 /// A whole drag is one undo step -- the front-end commits once, at the
7879 /// release -- and an edge asked to stay where it is costs none at all.
7880 #[test]
7881 fn a_trim_is_one_undo_step() {
7882 let mut p = three();
7883 let before = shape(&p);
7884 let history = p.history.len();
7885
7886 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7887 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7888 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7889 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7890 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7891 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7892
7893 assert!(p.undo());
7894 assert_eq!(shape(&p), before, "both halves back, in one step");
7895 }
7896
7897 /// A moved half stays in its group: a link names a span, not a lane, so the
7898 /// picture on `V2` is still the same take as the sound under it on `A1`.
7899 #[test]
7900 fn move_clip_keeps_the_group() {
7901 let v2 = Lane::new(LaneKind::Video, 1);
7902 let mut p = three();
7903 p.add_lane(LaneKind::Video);
7904 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7905 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7906 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7907 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7908 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7909 assert_eq!(
7910 p.lane(v2)[0].start,
7911 p.lane(Lane::A1)[1].start,
7912 "and still covers the same span as its sound"
7913 );
7914 }
7915
7916 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
7917 /// head of a lane, between two clips, inside a clip, past the last one,
7918 /// and on a lane holding nothing at all.
7919 #[test]
7920 fn gap_at_finds_the_hole_a_frame_sits_in() {
7921 let mut p = Project::single(FILE, 1);
7922 let v = p.add_lane(LaneKind::Video);
7923 // Empty lane: nothing before and nothing after -- not a gap, since
7924 // there is nothing to ripple toward.
7925 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
7926
7927 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
7928 // Before the only clip: the gap runs from the timeline's own head.
7929 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
7930 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
7931 // Inside the clip: not a gap.
7932 assert_eq!(p.gap_at(v, 5), None);
7933 assert_eq!(p.gap_at(v, 7), None);
7934 // Past the only clip: the open end of the lane, not a gap -- there is
7935 // nothing after it to slide back.
7936 assert_eq!(p.gap_at(v, 8), None);
7937 assert_eq!(p.gap_at(v, 100), None);
7938
7939 assert!(p.place(v, 12, clip(12, 0, 2, 0)), "a second clip at [12,14)");
7940 // Between the two: the gap [8,12).
7941 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
7942 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
7943 assert_eq!(p.gap_at(v, 14), None, "still the open end");
7944
7945 assert!(
7946 p.place(v, 8, clip(8, 0, 4, 0)),
7947 "fills [8,12) exactly, meeting both neighbours"
7948 );
7949 assert_eq!(p.gap_at(v, 8), None, "adjacent clips leave no frame to name a gap");
7950 assert_eq!(p.gap_at(v, 11), None);
7951 }
7952
7953 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
7954 /// menu named: the clip after the gap slides back on that lane, a clip on
7955 /// another lane at the very same frame range does not move, and the whole
7956 /// close is one press of undo.
7957 #[test]
7958 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
7959 let mut p = Project::single(FILE, 1);
7960 let v = p.add_lane(LaneKind::Video);
7961 let a = p.add_lane(LaneKind::Audio);
7962 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
7963 assert!(
7964 p.place(a, 0, clip(0, 0, 3, 0)),
7965 "A clip at [0,3) -- outside the video lane's gap and this scope"
7966 );
7967 let before = shape(&p);
7968 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
7969 assert_eq!((start, len), (0, 5));
7970 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
7971 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
7972 assert_eq!(p.lane(a)[0].start, 0, "the untouched lane's clip did not move");
7973 assert!(p.undo(), "one press undoes the whole close");
7974 assert_eq!(shape(&p), before, "back to exactly where it was");
7975 }
7976
7977 /// A clip carrying an explicit link id -- what a
7978 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
7979 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
7980 /// already builds inline.
7981 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
7982 Clip {
7983 fade_in: 0,
7984 fade_out: 0,
7985 transition_out: 0,
7986 start,
7987 in_frame,
7988 out_frame,
7989 source: 0,
7990 link: Some(link),
7991 eq: None,
7992 color: None,
7993 transform: None,
7994 fit: FitPolicy::default(),
7995 speed: Speed::NORMAL,
7996 }
7997 }
7998
7999 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
8000 /// bordered by a linked take whose `A1` half is empty across the very
8001 /// same stretch widens the scope to both lanes, so the ripple carries the
8002 /// take rather than tearing it -- and one undo puts both halves back.
8003 #[test]
8004 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
8005 let sources = vec![Source::new(FILE, 0)];
8006 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8007 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8008 let mut p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8009 .expect("valid parts");
8010 let before = shape(&p);
8011 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8012 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 2)), "the same stretch is empty on A1 too");
8013
8014 let scope = p
8015 .gap_take_scope(Lane::V1, 3, 2)
8016 .expect("a matching gap on both halves widens the scope");
8017 assert_eq!(scope.len(), 2, "the take's other lane joins");
8018 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
8019
8020 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
8021 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
8022 assert_eq!(p.lane(Lane::A1)[1].start, 3, "A1's far half rode along, in sync");
8023 assert!(p.undo(), "one press undoes the whole close");
8024 assert_eq!(shape(&p), before, "back to exactly where it was");
8025 }
8026
8027 /// The real design question: a take whose gap is not the *same size* on
8028 /// both lanes cannot ripple by one number without pulling a lane's clip
8029 /// out from under the other's sync -- refused by name, with the frame
8030 /// naming which lane is out of step, rather than silently taking real
8031 /// media off the shorter side.
8032 #[test]
8033 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
8034 let sources = vec![Source::new(FILE, 0)];
8035 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8036 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
8037 // shorter than V1's [3,5) -- a legal offset-preserving group, and
8038 // still one take.
8039 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
8040 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8041 .expect("valid parts");
8042 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8043 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
8044
8045 let err = p
8046 .gap_take_scope(Lane::V1, 3, 2)
8047 .expect_err("a mismatched gap cannot ripple by one number")
8048 .to_string();
8049 assert!(err.contains("A1"), "{err}");
8050 assert!(err.contains("out of sync"), "{err}");
8051 }
8052
8053 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
8054 /// there -- cannot close without cutting that audio out from under
8055 /// nothing asked to touch it: refused, not widened silently past.
8056 #[test]
8057 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
8058 let sources = vec![Source::new(FILE, 0)];
8059 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8060 // A1 plays through the whole span as one continuous clip, sharing
8061 // V1's first-half link: nothing empty at frame 3 there at all.
8062 let audio = vec![linked(0, 0, 9, 1)];
8063 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8064 .expect("valid parts");
8065 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8066 assert_eq!(p.gap_at(Lane::A1, 3), None, "A1 plays through, no gap there");
8067
8068 let err = p
8069 .gap_take_scope(Lane::V1, 3, 2)
8070 .expect_err("a solid partner cannot ripple with the gap")
8071 .to_string();
8072 assert!(err.contains("A1"), "{err}");
8073 assert!(err.contains("detach"), "{err}");
8074 }
8075
8076
8077 /// The sweep is the single-gap close repeated on one lane, but measured once
8078 /// and applied from the right. The differing gap lengths here expose a
8079 /// front-to-back bug: the last clip would be cut against a stale frame after
8080 /// the first gap shifted it.
8081 #[test]
8082 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
8083 let mut p = Project::single(FILE, 1);
8084 let v = p.add_lane(LaneKind::Video);
8085 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
8086 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
8087 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
8088 let before = shape(&p);
8089
8090 assert_eq!(p.gap_count(v), 3);
8091 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
8092 assert_eq!(report.closed, 3);
8093 assert!(report.skipped.is_empty());
8094 assert_eq!(
8095 p.lane(v),
8096 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
8097 "all gaps closed without eating source frames"
8098 );
8099 assert!(p.undo(), "one undo for the whole sweep");
8100 assert_eq!(shape(&p), before);
8101 }
8102
8103 /// Empty, already-contiguous and tail-only lanes are not controls that do
8104 /// work. A single clip with a head gap does close, because there is a real
8105 /// placement to ripple back.
8106 #[test]
8107 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
8108 let mut p = Project::single(FILE, 9);
8109 let v = p.add_lane(LaneKind::Video);
8110 let history = p.history.len();
8111 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
8112 assert_eq!(report, GapSweep::default(), "an empty lane has no bounded gap");
8113 assert_eq!(p.history.len(), history, "no undo step for a no-op");
8114
8115 let mut p = Project::single(FILE, 9);
8116 let v = p.add_lane(LaneKind::Video);
8117 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
8118 let before = shape(&p);
8119 let report = p.close_all_gaps_on_lane(v).expect("single clip lane exists");
8120 assert_eq!(report.closed, 1, "the head gap closes");
8121 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8122 assert!(p.undo());
8123 assert_eq!(shape(&p), before);
8124
8125 let mut p = Project::single(FILE, 9);
8126 let history = p.history.len();
8127 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8128 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
8129 assert_eq!(p.history.len(), history);
8130
8131 let mut p = Project::single(FILE, 9);
8132 let v = p.add_lane(LaneKind::Video);
8133 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
8134 let history = p.history.len();
8135 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
8136 assert_eq!(report, GapSweep::default(), "the open-ended tail is not closed");
8137 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8138 assert_eq!(p.history.len(), history);
8139 }
8140
8141 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
8142 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
8143 /// while V1's [6,9) has only [6,8) empty on A1.
8144 #[test]
8145 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
8146 let sources = vec![Source::new(FILE, 0)];
8147 let video = vec![
8148 linked(0, 0, 2, 1),
8149 linked(4, 4, 6, 2),
8150 clip(9, 9, 11, 0),
8151 ];
8152 let audio = vec![
8153 linked(0, 0, 2, 1),
8154 linked(4, 4, 6, 2),
8155 clip(8, 8, 11, 0),
8156 ];
8157 let mut p =
8158 Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8159 .expect("valid parts");
8160 let before = shape(&p);
8161
8162 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8163 assert_eq!(report.closed, 1);
8164 assert_eq!(report.skipped.len(), 1);
8165 assert_eq!(report.skipped[0].start, 6);
8166 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
8167 assert!(report.skipped[0].reason.contains("out of sync"), "{report:?}");
8168
8169 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
8170 assert_eq!(p.lane(Lane::A1)[1].start, 2, "and its other half stayed in sync");
8171 assert_eq!(p.lane(Lane::V1)[2].start, 7, "the skipped later gap remains");
8172 assert_eq!(p.lane(Lane::A1)[2].start, 6, "A1's shorter gap remains shorter");
8173 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
8174 assert!(p.undo(), "one undo restores every closed gap");
8175 assert_eq!(shape(&p), before);
8176 }
8177
8178 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
8179 /// their own caption storage: head gaps and gaps between cues count, an
8180 /// empty lane and the tail after the last cue do not.
8181 #[test]
8182 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
8183 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8184 let s = p.add_lane(LaneKind::Subtitle);
8185 assert_eq!(p.gap_at(s, 0), None, "an empty subtitle lane has nothing to close");
8186
8187 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8188 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
8189 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
8190 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
8191 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
8192
8193 p.place_sub(s, 12, caption(0, 2)).expect("second cue at [12,14)");
8194 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
8195 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
8196 assert_eq!(p.gap_at(s, 14), None, "tail after the last cue is still open-ended");
8197 }
8198
8199 /// Closing a caption gap ripples the subtitle lane only. It is not a media
8200 /// take close, so the video and audio lanes keep their frame positions.
8201 #[test]
8202 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
8203 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8204 let s = p.add_lane(LaneKind::Subtitle);
8205 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8206 let before_clips = shape(&p);
8207 let before_subs = p.sub_lane(s).to_vec();
8208
8209 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
8210 assert_eq!((start, len), (0, 5));
8211 p.cut_regions(&[(start, len)], &[s]).expect("caption lane gap closes");
8212
8213 assert_eq!(shape(&p), before_clips, "media lanes did not move");
8214 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
8215 assert!(p.undo(), "one undo restores the caption close");
8216 assert_eq!(shape(&p), before_clips);
8217 assert_eq!(p.sub_lane(s), before_subs);
8218 }
8219
8220 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
8221 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
8222 /// history entry for empty or already-contiguous lanes.
8223 #[test]
8224 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
8225 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8226 let s = p.add_lane(LaneKind::Subtitle);
8227 let history = p.history.len();
8228 let report = p.close_all_gaps_on_lane(s).expect("empty subtitle lane exists");
8229 assert_eq!(report, GapSweep::default(), "empty subtitle lane has no bounded gap");
8230 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
8231
8232 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
8233 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
8234 p.place_sub(s, 14, caption(0, 1)).expect("middle gap [9,14), tail after 15");
8235 let before = p.sub_lane(s).to_vec();
8236
8237 assert_eq!(p.gap_count(s), 3);
8238 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8239 assert_eq!(report.closed, 3);
8240 assert!(report.skipped.is_empty());
8241 assert_eq!(
8242 p.sub_lane(s),
8243 &[caption(0, 2), caption(2, 2), caption(4, 1)],
8244 "all bounded caption gaps closed without touching windows"
8245 );
8246 assert!(p.undo(), "one undo restores every caption gap");
8247 assert_eq!(p.sub_lane(s), before);
8248
8249 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8250 let s = p.add_lane(LaneKind::Subtitle);
8251 p.place_sub(s, 0, caption(0, 3)).expect("contiguous at the head");
8252 let history = p.history.len();
8253 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8254 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
8255 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
8256 assert_eq!(p.history.len(), history);
8257 }
8258
8259 #[test]
8260 fn ripple_delete_spans_partial_clips() {
8261 let mut p = three();
8262 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
8263 assert!(p.ripple_delete(2, 4));
8264 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
8265 assert_eq!(shape(&p)[1], shape(&p)[0]);
8266 assert_eq!(p.timeline_frames(), 5);
8267 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
8268 assert!(p.undo());
8269 assert_eq!(shape(&p), shape(&three()));
8270 // One that takes everything is a delete like any other: the timeline
8271 // empties, and the undo it cost brings it back whole.
8272 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
8273 assert_eq!(p.timeline_frames(), 0);
8274 assert!(
8275 !p.ripple_delete(0, 100),
8276 "and a delete with nothing left to take is not an undo step"
8277 );
8278 assert!(p.undo());
8279 assert_eq!(shape(&p), shape(&three()));
8280 }
8281
8282 #[test]
8283 fn undo_restores_exactly() {
8284 let mut p = three();
8285 let after_splits = shape(&p);
8286 assert!(p.delete(1));
8287 assert!(p.undo());
8288 assert_eq!(shape(&p), after_splits);
8289
8290 // walk all the way back through both splits, then run dry
8291 assert!(p.undo());
8292 assert_eq!(p.clips().len(), 2);
8293 assert!(p.undo());
8294 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8295 assert!(!p.undo(), "empty history");
8296 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8297 }
8298
8299 #[test]
8300 fn redo_restores_exactly() {
8301 let mut p = three();
8302 assert!(p.delete(1));
8303 let after_delete = p.parts();
8304 assert!(p.undo());
8305 assert!(p.redo());
8306 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
8307 assert!(!p.redo(), "empty redo stack");
8308 }
8309
8310 #[test]
8311 fn edit_after_undo_empties_redo() {
8312 let mut p = three();
8313 assert!(p.delete(1));
8314 assert!(p.undo());
8315 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
8316 assert!(p.split(1), "a fresh edit");
8317 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
8318 assert!(!p.redo(), "so redo has nothing left");
8319 }
8320
8321 #[test]
8322 fn redo_on_empty_stack_is_false() {
8323 let mut p = three();
8324 assert!(!p.redo(), "nothing has been undone yet");
8325 }
8326
8327 /// Past the cap the *oldest* step goes, so a long session undoes exactly
8328 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
8329 #[test]
8330 fn history_stops_at_the_cap() {
8331 let mut p = Project::single(FILE, 400);
8332 for frame in 1..=150 {
8333 assert!(p.split(frame), "split {frame} is an edit");
8334 }
8335 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
8336 for step in 0..HISTORY_CAP {
8337 assert!(p.undo(), "undo {step} is inside the cap");
8338 }
8339 assert!(!p.undo(), "and the 101st has nothing left to take");
8340 // 100 undos off 150 splits is the timeline after the 50th: the older
8341 // steps were dropped, not the newer ones.
8342 assert_eq!(p.clips().len(), 51);
8343 }
8344
8345 /// Undo/redo by hand across a split must never merge two takes into one
8346 /// group by reusing an id.
8347 #[test]
8348 fn group_ids_are_never_reused() {
8349 let mut p = Project::single(FILE, 9);
8350 assert!(p.split(3));
8351 let first = p.clips()[1].link;
8352 assert!(p.undo());
8353 assert!(p.split(5));
8354 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
8355 }
8356
8357 #[test]
8358 fn segments_from_reads_the_audio_lane() {
8359 let p = three();
8360 // mid-clip: partial first segment, whole clips after it
8361 assert_eq!(
8362 p.segments_from(4, FPS),
8363 vec![
8364 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8365 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8366 ]
8367 );
8368 // on a boundary: nothing partial
8369 assert_eq!(
8370 p.segments_from(3, FPS),
8371 vec![
8372 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
8373 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8374 ]
8375 );
8376 // from the top: one entry per clip
8377 assert_eq!(p.segments_from(0, FPS).len(), 3);
8378 // last clip only
8379 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
8380 // past the end / unusable fps
8381 assert!(p.segments_from(9, FPS).is_empty());
8382 assert!(p.segments_from(0, 0.0).is_empty());
8383 assert!(p.segments_from(0, f64::NAN).is_empty());
8384 }
8385
8386 #[test]
8387 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
8388 let mut p = three();
8389 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
8390 assert_eq!(
8391 p.segments_from(0, FPS),
8392 vec![
8393 (Some(0), 0.0, 3.0 / 30.0),
8394 (None, 0.0, 2.0 / 30.0),
8395 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8396 ]
8397 );
8398 // The list still covers exactly the timeline: that is what stops the
8399 // master clock stalling at the hole.
8400 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8401 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
8402 // Starting inside the gap trims the silence, not the clip after it.
8403 assert_eq!(
8404 p.segments_from(4, FPS),
8405 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
8406 );
8407 // ...and a lane that is nothing but gap is a run of silence.
8408 assert!(p.lift(Lane::A1, 0));
8409 assert!(p.lift(Lane::A1, 0));
8410 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
8411 }
8412
8413 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
8414 /// of source 0 then [0,4) of source 1.
8415 fn two_sources() -> Project {
8416 let mut p = three();
8417 let s = p.import(FILE2, 0);
8418 assert_eq!(s, 1);
8419 assert!(p.append_clip(s, 4));
8420 p
8421 }
8422
8423 #[test]
8424 fn import_dedups_and_appends() {
8425 let mut p = Project::single(FILE, 9);
8426 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
8427 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
8428 assert_eq!(p.import(FILE2, 0), 1);
8429 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
8430 // ...but the same file on another audio stream is another source: it is
8431 // what a clip names, and a clip plays exactly one stream.
8432 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
8433 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
8434 assert_eq!(p.sources()[2].audio_stream, 1);
8435 assert!(p.append_clip(2, 4), "a stream entry is placeable");
8436 assert!(p.undo());
8437 assert_eq!(p.sources().len(), 3);
8438 assert!(!p.append_clip(3, 5), "unknown source index");
8439 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
8440
8441 // Two spellings of one real file are one source: this is the case the
8442 // raw-path comparison above would get wrong.
8443 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
8444 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
8445 let mut p = Project::single(here, 9);
8446 assert_eq!(p.import(detour, 0), 0);
8447 assert_eq!(p.sources().len(), 1);
8448 }
8449
8450 #[test]
8451 fn append_clip_is_one_undo_step() {
8452 let mut p = two_sources();
8453 assert_eq!(p.timeline_frames(), 13);
8454 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
8455 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
8456 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
8457 assert!(p.undo());
8458 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
8459 assert_eq!(
8460 p.sources().len(),
8461 2,
8462 "the orphan source entry stays -- indexes are forever"
8463 );
8464 // ...and it is still usable, so a redo-by-hand costs no reimport.
8465 assert!(p.append_clip(1, 0));
8466 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
8467 }
8468
8469 #[test]
8470 fn edits_carry_the_source_along() {
8471 let mut p = two_sources();
8472 // A split inside the second source splits into two source-1 clips.
8473 assert!(p.split(11));
8474 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
8475 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
8476
8477 // A source-1 clip pasted into source-0 territory keeps its file, and so
8478 // does the source-0 half that got split off around it.
8479 let copied = p.clips()[4];
8480 assert!(p.paste(1, copied));
8481 assert_eq!(p.clips()[1].source, 1);
8482 assert_eq!(p.clips()[1].in_frame, 2);
8483 assert_eq!(p.clips()[2].source, 0);
8484 assert!(p.undo());
8485 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
8486 }
8487
8488 #[test]
8489 fn segments_from_names_the_source() {
8490 let p = two_sources();
8491 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
8492 assert_eq!(
8493 p.segments_from(4, FPS),
8494 vec![
8495 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8496 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8497 (Some(1), 0.0, 4.0 / 30.0),
8498 ]
8499 );
8500 // Mid-clip in source 1: only that source is left.
8501 assert_eq!(
8502 p.segments_from(10, FPS),
8503 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
8504 );
8505 assert!(p.segments_from(13, FPS).is_empty());
8506 // Segments still cover exactly the timeline across the join.
8507 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8508 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
8509 }
8510
8511 #[test]
8512 fn segments_follow_deletes_and_fps() {
8513 let mut p = three();
8514 assert!(p.delete(0));
8515 // source seconds, not timeline: deleting the head does not shift them
8516 let segs = p.segments_from(0, 25.0);
8517 assert_eq!(
8518 segs,
8519 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
8520 );
8521 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
8522 assert!(
8523 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
8524 "segments must cover exactly the timeline: {played}"
8525 );
8526 }
8527
8528 #[test]
8529 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
8530 // Import a second file, undo it: source 1 is now an orphan.
8531 let mut p = two_sources();
8532 assert!(p.undo());
8533 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8534 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
8535 assert!(eq.is_empty(), "and a project with no equalizer writes none");
8536 assert!(color.is_empty(), "nor a colour it never graded with");
8537 assert_eq!(
8538 lanes,
8539 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
8540 "the clips are untouched"
8541 );
8542
8543 // Three sources where only the middle one is orphaned: the survivors
8544 // renumber, and the clips follow.
8545 let mut p = Project::single(FILE, 9);
8546 assert_eq!(p.import(FILE2, 0), 1);
8547 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
8548 assert!(p.append_clip(2, 4));
8549 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8550 assert_eq!(
8551 sources,
8552 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
8553 );
8554 assert_eq!(
8555 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
8556 [0, 1]
8557 );
8558 // ...and what comes out is loadable, with the same timeline.
8559 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8560 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
8561 assert_eq!(reloaded.sources().len(), 2);
8562 }
8563
8564 /// Taking a file out of the library: refused by name -- lanes and counts --
8565 /// while a clip still plays from it, and once nothing does, the entry goes
8566 /// and every clip that indexed past it is renumbered onto the short list.
8567 #[test]
8568 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
8569 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
8570 // plus a second stream of FILE as source 2 with a take of its own.
8571 let mut p = two_sources();
8572 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
8573 assert!(p.append_clip(2, 4));
8574
8575 let refusal = p
8576 .remove_source(1)
8577 .expect_err("a source with clips on it cannot go")
8578 .to_string();
8579 assert!(refusal.contains(FILE2), "names the file: {refusal}");
8580 assert!(
8581 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
8582 "names the lanes holding it: {refusal}"
8583 );
8584 assert!(refusal.contains("still plays"), "{refusal}");
8585 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
8586 assert_eq!(shape(&p)[0][3].source, 1);
8587
8588 // Delete FILE2's take -- the whole span, on every lane -- and the entry
8589 // is free to go. Source 2's clips become source 1's.
8590 assert!(p.delete_in(Lane::V1, 3));
8591 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
8592 p.remove_source(1).expect("nothing plays FILE2 any more");
8593 assert_eq!(
8594 p.sources(),
8595 [Source::new(FILE, 0), Source::new(FILE, 1)],
8596 "the middle entry is gone"
8597 );
8598 assert_eq!(
8599 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
8600 [0, 0, 0, 1],
8601 "the clips past it renumbered"
8602 );
8603 assert_eq!(
8604 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
8605 [0, 0, 0, 1],
8606 "on every lane"
8607 );
8608 // What is left is a project that still loads, which is the whole point
8609 // of renumbering rather than leaving a hole.
8610 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8611 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8612 }
8613
8614 /// The two edges of a removal: it retires the undo stack (the corner-cut on
8615 /// [`Project::remove_source`]), and the last entry goes like any other
8616 /// once nothing plays it -- a project may name no file at all.
8617 #[test]
8618 fn remove_source_retires_undo_and_empties_the_library() {
8619 let mut p = two_sources();
8620 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
8621 assert!(!p.history.is_empty(), "there is something to undo");
8622 p.remove_source(1).expect("nothing plays FILE2");
8623 assert!(
8624 p.history.is_empty(),
8625 "a snapshot naming the removed source must not survive it"
8626 );
8627 assert!(!p.undo(), "and so there is nothing left to undo");
8628
8629 // The last file standing is held to the one rule every row is -- what
8630 // plays cannot go -- and to no other.
8631 assert_eq!(p.sources().len(), 1);
8632 let refusal = p
8633 .remove_source(0)
8634 .expect_err("its clips are still on the lanes")
8635 .to_string();
8636 assert!(refusal.contains("still plays"), "{refusal}");
8637 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
8638 while p.delete_in(Lane::V1, 0) {}
8639 p.remove_source(0)
8640 .expect("the last row goes like any other");
8641 assert!(
8642 p.sources().is_empty(),
8643 "a project may name no file at all: an empty library over an empty timeline"
8644 );
8645 assert_eq!(p.timeline_frames(), 0);
8646 assert!(
8647 p.remove_source(0).is_err(),
8648 "and an index that is not there is refused, not panicked on"
8649 );
8650 }
8651
8652 /// A clip's equalizer is the clip's: it survives every edit that copies a
8653 /// placement, and it comes back with an undo.
8654 #[test]
8655 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
8656 let mut p = three();
8657 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
8658 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
8659 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8660 assert!(
8661 p.eq_of(Lane::V1, 0).is_none(),
8662 "one clip, not the lane above"
8663 );
8664
8665 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
8666 assert!(p.split(1));
8667 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8668 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
8669 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
8670
8671 // A clipboard copy carries it -- onto another lane, at that.
8672 let copied = p.lane(Lane::A1)[1];
8673 assert!(p.place(Lane::V1, 20, copied));
8674 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
8675 assert!(p.undo());
8676 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
8677
8678 // ...and a change to one is one undo step, in both directions.
8679 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
8680 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
8681 assert!(p.undo());
8682 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8683 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
8684 assert!(p.eq_of(Lane::A1, 0).is_none());
8685 assert!(p.undo());
8686 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8687
8688 // Two refusals, neither of which costs an undo step.
8689 let mut nan = band_at(1);
8690 nan.bands[0].q = f32::INFINITY;
8691 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
8692 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
8693 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8694 assert!(p.undo());
8695 assert_eq!(
8696 p.lane(Lane::A1).len(),
8697 3,
8698 "one step back is before the split"
8699 );
8700 assert!(p.undo());
8701 assert!(
8702 p.eq_of(Lane::A1, 0).is_none(),
8703 "and the next is before the setting: the refusals pushed none"
8704 );
8705 }
8706
8707 /// The table is append-only within a session, exactly as the sources are, so
8708 /// an undone setting is still in it -- and a save is where it goes.
8709 #[test]
8710 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
8711 let mut p = three();
8712 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
8713 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
8714 assert!(p.undo(), "back to the first setting");
8715 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
8716
8717 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8718 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
8719 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
8720 assert_eq!(lanes[0].1[1].eq, None);
8721
8722 // One curve on three clips is one entry: settings that are equal share.
8723 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
8724 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
8725 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8726 assert_eq!(eq.len(), 1, "equal settings share their entry");
8727 assert_eq!(lanes[1].1[2].eq, Some(0));
8728 reloads(&p, "an equalizer that outlived an undo");
8729 }
8730
8731 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8732 /// grade is the clip's, through every edit that copies a placement.
8733 #[test]
8734 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
8735 let mut p = three();
8736 assert!(
8737 p.color_of(Lane::V1, 0).is_none(),
8738 "a fresh clip is ungraded"
8739 );
8740 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8741 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8742 assert!(
8743 p.color_of(Lane::A1, 0).is_none(),
8744 "one clip, not the lane below"
8745 );
8746 assert!(
8747 p.eq_of(Lane::V1, 0).is_none(),
8748 "and a grade is not an equalizer"
8749 );
8750
8751 // Cutting a graded clip must not grade half of it: both halves inherit.
8752 assert!(p.split(1));
8753 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8754 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
8755 assert!(
8756 p.color_of(Lane::V1, 2).is_none(),
8757 "the clip after it is ungraded"
8758 );
8759
8760 // A clipboard copy carries it -- onto another lane, at that.
8761 let copied = p.lane(Lane::V1)[1];
8762 assert!(p.place(Lane::A1, 20, copied));
8763 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
8764 assert!(p.undo());
8765 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8766
8767 // ...and a change to one is one undo step, in both directions.
8768 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
8769 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
8770 assert!(p.undo());
8771 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8772 assert!(
8773 p.set_color(Lane::V1, 0, None),
8774 "and taking it off is an edit"
8775 );
8776 assert!(p.color_of(Lane::V1, 0).is_none());
8777 assert!(p.undo());
8778 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8779
8780 // Two refusals, neither of which costs an undo step.
8781 let nan = ColorParams {
8782 contrast: f32::NAN,
8783 ..grade_at(1)
8784 };
8785 assert!(
8786 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
8787 "no clip there"
8788 );
8789 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
8790 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8791 assert!(p.undo());
8792 assert_eq!(
8793 p.lane(Lane::V1).len(),
8794 3,
8795 "one step back is before the split"
8796 );
8797 assert!(p.undo());
8798 assert!(
8799 p.color_of(Lane::V1, 0).is_none(),
8800 "and the next is before the grade: the refusals pushed none"
8801 );
8802 }
8803
8804 /// A slider drag is one gesture: the press snapshots, every sample after it
8805 /// only regrades, and the single undo lands on what the clip was *before*
8806 /// the hand touched it -- not one step back down the drag.
8807 #[test]
8808 fn a_whole_colour_drag_undoes_in_one_step() {
8809 let mut p = three();
8810 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
8811 for n in 2..=8 {
8812 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
8813 }
8814 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
8815 assert!(p.undo());
8816 assert!(
8817 p.color_of(Lane::V1, 0).is_none(),
8818 "one undo is the whole gesture, back to ungraded"
8819 );
8820
8821 // The live write refuses what the snapshotting one refuses, and a
8822 // refusal still costs no history either way.
8823 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
8824 assert!(!p.set_color_live(
8825 Lane::V1,
8826 0,
8827 Some(ColorParams {
8828 contrast: f32::NAN,
8829 ..grade_at(1)
8830 })
8831 ));
8832 assert!(p.undo());
8833 assert_eq!(
8834 p.lane(Lane::V1).len(),
8835 2,
8836 "the next step back is the split before the drag: no sample pushed one"
8837 );
8838 }
8839
8840 /// The colour table is append-only within a session, exactly as the eq one
8841 /// is -- and a save is where an undone grade goes.
8842 #[test]
8843 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
8844 let mut p = three();
8845 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
8846 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8847 assert!(p.undo(), "back to the first grade");
8848 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
8849
8850 let (_, lanes, _, color, _) = p.without_orphan_sources();
8851 assert_eq!(
8852 color,
8853 vec![grade_at(1)],
8854 "what nothing plays is not written"
8855 );
8856 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
8857 assert_eq!(lanes[0].1[1].color, None);
8858
8859 // One grade on three clips is one entry: settings that are equal share.
8860 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
8861 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
8862 let (_, lanes, _, color, _) = p.without_orphan_sources();
8863 assert_eq!(color.len(), 1, "equal grades share their entry");
8864 assert_eq!(lanes[1].1[2].color, Some(0));
8865 reloads(&p, "a colour that outlived an undo");
8866
8867 // An equalizer and a grade on one clip are two independent tables.
8868 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
8869 let (_, lanes, eq, color, _) = p.without_orphan_sources();
8870 assert_eq!((eq.len(), color.len()), (1, 1));
8871 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
8872 }
8873
8874 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8875 /// placement is the clip's, through every edit that copies one.
8876 #[test]
8877 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
8878 let mut p = three();
8879 assert!(
8880 p.transform_of(Lane::V1, 0).is_none(),
8881 "a fresh clip is untransformed"
8882 );
8883 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8884 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8885 assert!(
8886 p.transform_of(Lane::A1, 0).is_none(),
8887 "one clip, not the lane below"
8888 );
8889 assert!(
8890 p.color_of(Lane::V1, 0).is_none(),
8891 "and a placement is not a grade"
8892 );
8893
8894 // Cutting a transformed clip must not transform half of it: both
8895 // halves inherit.
8896 assert!(p.split(1));
8897 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8898 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
8899 assert!(
8900 p.transform_of(Lane::V1, 2).is_none(),
8901 "the clip after it is untransformed"
8902 );
8903
8904 // A clipboard copy carries it -- onto another lane, at that.
8905 let copied = p.lane(Lane::V1)[1];
8906 assert!(p.place(Lane::A1, 20, copied));
8907 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
8908 assert!(p.undo());
8909 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8910
8911 // ...and a change to one is one undo step, in both directions.
8912 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
8913 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
8914 assert!(p.undo());
8915 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8916 assert!(
8917 p.set_transform(Lane::V1, 0, None),
8918 "and taking it off is an edit"
8919 );
8920 assert!(p.transform_of(Lane::V1, 0).is_none());
8921 assert!(p.undo());
8922 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8923
8924 // Two refusals, neither of which costs an undo step.
8925 let nan = TransformParams {
8926 scale: f32::NAN,
8927 ..transform_at(1)
8928 };
8929 assert!(
8930 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
8931 "no clip there"
8932 );
8933 assert!(
8934 !p.set_transform(Lane::V1, 0, Some(nan)),
8935 "not a finite value"
8936 );
8937 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8938 assert!(p.undo());
8939 assert_eq!(
8940 p.lane(Lane::V1).len(),
8941 3,
8942 "one step back is before the split"
8943 );
8944 assert!(p.undo());
8945 assert!(
8946 p.transform_of(Lane::V1, 0).is_none(),
8947 "and the next is before the placement: the refusals pushed none"
8948 );
8949 }
8950
8951 /// The transform table is append-only within a session, exactly as the eq
8952 /// and colour ones are -- and a save is where an undone placement goes.
8953 #[test]
8954 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
8955 let mut p = three();
8956 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
8957 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8958 assert!(p.undo(), "back to the first placement");
8959 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
8960
8961 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8962 assert_eq!(
8963 transform,
8964 vec![transform_at(1)],
8965 "what nothing plays is not written"
8966 );
8967 assert_eq!(
8968 lanes[0].1[0].transform,
8969 Some(0),
8970 "and the survivor renumbers"
8971 );
8972 assert_eq!(lanes[0].1[1].transform, None);
8973
8974 // One placement on three clips is one entry: settings that are equal
8975 // share.
8976 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
8977 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
8978 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8979 assert_eq!(transform.len(), 1, "equal placements share their entry");
8980 assert_eq!(lanes[1].1[2].transform, Some(0));
8981 reloads(&p, "a transform that outlived an undo");
8982
8983 // A grade and a placement on one clip are two independent tables.
8984 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
8985 let (_, lanes, _, color, transform) = p.without_orphan_sources();
8986 assert_eq!((color.len(), transform.len()), (1, 1));
8987 assert_eq!(
8988 (lanes[0].1[0].color, lanes[0].1[0].transform),
8989 (Some(0), Some(0))
8990 );
8991 }
8992
8993 /// Not a claim about correctness but about cost: a clip is copied on every
8994 /// paste, every undo snapshot and every lane clone, so its size is worth
8995 /// knowing. The eq index fit the padding a `Copy` clip already had; the
8996 /// colour one did not, and the struct grew a word. The transform index is
8997 /// a third `Option<u16>`, and it fits the padding the fit policy and the
8998 /// transition byte already left behind, so the struct did not grow again.
8999 #[test]
9000 fn a_clip_is_still_a_small_copy() {
9001 assert_eq!(
9002 std::mem::size_of::<Clip>(),
9003 56,
9004 "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index"
9005 );
9006 }
9007
9008 #[test]
9009 fn from_parts_has_no_history_and_checks_the_invariants() {
9010 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
9011 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
9012 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
9013 .expect("valid parts");
9014 assert_eq!(p.clips(), three().clips());
9015 assert!(!p.undo(), "a loaded project has nothing to undo");
9016 assert!(p.split(4), "...and is editable from there");
9017 assert!(p.undo());
9018
9019 // A lane may be empty, and so may every lane -- an emptied timeline is a
9020 // project. No lane at all is not one: there would be nothing to place on.
9021 assert!(
9022 Project::from_parts(
9023 sources.clone(),
9024 two(video.clone(), Vec::new()),
9025 Vec::new(),
9026 Vec::new(),
9027 Vec::new(),
9028 )
9029 .is_ok()
9030 );
9031 assert!(
9032 Project::from_parts(
9033 sources.clone(),
9034 two(Vec::new(), Vec::new()),
9035 Vec::new(),
9036 Vec::new(),
9037 Vec::new(),
9038 )
9039 .is_ok()
9040 );
9041 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
9042 let bad: [Vec<Clip>; 5] = [
9043 vec![clip(0, 0, 3, 1)], // source that is not there
9044 vec![clip(0, 3, 3, 0)], // empty clip
9045 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
9046 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
9047 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
9048 ];
9049 for clips in bad {
9050 assert!(
9051 Project::from_parts(
9052 sources.clone(),
9053 two(clips.clone(), Vec::new()),
9054 Vec::new(),
9055 Vec::new(),
9056 Vec::new(),
9057 )
9058 .is_err(),
9059 "{clips:?}"
9060 );
9061 assert!(
9062 Project::from_parts(
9063 sources.clone(),
9064 two(video.clone(), clips.clone()),
9065 Vec::new(),
9066 Vec::new(),
9067 Vec::new(),
9068 )
9069 .is_err()
9070 );
9071 // ...and on a third lane, which is checked by the same walk.
9072 assert!(
9073 Project::from_parts(
9074 sources.clone(),
9075 vec![
9076 (LaneKind::Video, video.clone()),
9077 (LaneKind::Audio, audio.clone()),
9078 (LaneKind::Video, clips),
9079 ],
9080 Vec::new(),
9081 Vec::new(),
9082 Vec::new(),
9083 )
9084 .is_err()
9085 );
9086 }
9087 // An equalizer index no table entry answers, and a table entry the file
9088 // format could not have written, are refused at this door too.
9089 let eqd = |i: u16| {
9090 vec![Clip {
9091 fade_in: 0,
9092 fade_out: 0,
9093 transition_out: 0,
9094 eq: Some(i),
9095 ..video[0]
9096 }]
9097 };
9098 assert!(
9099 Project::from_parts(
9100 sources.clone(),
9101 two(eqd(0), Vec::new()),
9102 Vec::new(),
9103 Vec::new(),
9104 Vec::new(),
9105 )
9106 .is_err()
9107 );
9108 let mut nan = band_at(1);
9109 nan.bands[0].freq_hz = f32::NAN;
9110 assert!(
9111 Project::from_parts(
9112 sources.clone(),
9113 two(eqd(0), Vec::new()),
9114 vec![nan],
9115 Vec::new(),
9116 Vec::new(),
9117 )
9118 .is_err()
9119 );
9120 let loaded = Project::from_parts(
9121 sources.clone(),
9122 two(eqd(0), Vec::new()),
9123 vec![band_at(1)],
9124 Vec::new(),
9125 Vec::new(),
9126 )
9127 .expect("an eq the table holds");
9128 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
9129
9130 // The same two refusals for a colour, at the same door.
9131 let graded = |i: u16| {
9132 vec![Clip {
9133 fade_in: 0,
9134 fade_out: 0,
9135 transition_out: 0,
9136 color: Some(i),
9137 fit: FitPolicy::default(),
9138 speed: Speed::NORMAL,
9139 ..video[0]
9140 }]
9141 };
9142 assert!(
9143 Project::from_parts(
9144 sources.clone(),
9145 two(graded(0), Vec::new()),
9146 Vec::new(),
9147 Vec::new(),
9148 Vec::new(),
9149 )
9150 .is_err(),
9151 "a colour index no entry answers"
9152 );
9153 assert!(
9154 Project::from_parts(
9155 sources.clone(),
9156 two(graded(0), Vec::new()),
9157 Vec::new(),
9158 vec![ColorParams {
9159 tint: f32::NAN,
9160 ..grade_at(1)
9161 }],
9162 Vec::new(),
9163 )
9164 .is_err(),
9165 "a value the file format could not have written"
9166 );
9167 let loaded = Project::from_parts(
9168 sources.clone(),
9169 two(graded(0), Vec::new()),
9170 Vec::new(),
9171 vec![grade_at(1)],
9172 Vec::new(),
9173 )
9174 .expect("a colour the table holds");
9175 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
9176
9177 // Group ids survive a load, and the next split gets a fresh one.
9178 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
9179 assert!(p.split(4));
9180 assert!(p.clips().iter().all(|c| c.link.is_some()));
9181 }
9182
9183 /// The grouping rules, at the untrusted door and after every edit that can
9184 /// touch a link. A link id is at most one placement per lane -- a clip or a
9185 /// caption, whichever carries it -- and no sequence of edits may produce
9186 /// otherwise, because what an edit produces is what a save writes and a load
9187 /// reads.
9188 ///
9189 /// Amended for the offset-preserving group: the members keep their own
9190 /// spans, so two placements of one id covering different frames is *legal*
9191 /// -- it is what a hand-built group is -- and the only refusal left is the
9192 /// doubled id inside one lane.
9193 #[test]
9194 fn a_link_id_is_never_two_clips_of_one_lane() {
9195 let sources = vec![Source::new(FILE, 0)];
9196 let linked = |start, in_frame, out_frame, link| Clip {
9197 fade_in: 0,
9198 fade_out: 0,
9199 transition_out: 0,
9200 start,
9201 in_frame,
9202 out_frame,
9203 source: 0,
9204 link: Some(link),
9205 eq: None,
9206 color: None,
9207 transform: None,
9208 fit: FitPolicy::default(),
9209 speed: Speed::NORMAL,
9210 };
9211
9212 // The door: a doubled id inside one lane, refused by name.
9213 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
9214 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
9215 .expect_err("refused")
9216 .to_string()
9217 };
9218 assert!(
9219 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
9220 .contains("link 7 names two clips in the V1 lane"),
9221 "a duplicate id inside one lane is refused by name"
9222 );
9223 // ...and the same doubling on a subtitle lane, in its own words: a
9224 // caption is the other placement an id may name.
9225 let caption = |start: u32, frames: u32, link| SubClip {
9226 start,
9227 frames,
9228 track: 0,
9229 in_us: 0,
9230 out_us: i64::from(frames) * 1_000_000,
9231 link: Some(link),
9232 };
9233 let subs = LaneData {
9234 clips: Vec::new(),
9235 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
9236 ..LaneData::new(LaneKind::Subtitle, Vec::new())
9237 };
9238 assert_eq!(
9239 links_are_consistent(&[subs]).unwrap_err().to_string(),
9240 "link 7 names two captions in the S1 lane"
9241 );
9242 // A pair covering *different* frames is legal now: the members of a
9243 // hand-built group keep their own spans, and what binds them is the id.
9244 let apart = Project::from_parts(
9245 sources.clone(),
9246 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
9247 Vec::new(),
9248 Vec::new(),
9249 Vec::new(),
9250 );
9251 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
9252 // A one-sided link is *not* an error: it is what a lift leaves behind.
9253 let mut p = Project::single(FILE, 9);
9254 assert!(p.lift(Lane::A1, 0));
9255 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
9256 assert!(
9257 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
9258 "a lifted lane's project has to load again"
9259 );
9260
9261 // The edits: nothing below may break either rule.
9262 let consistent = |p: &Project, what: &str| {
9263 assert!(
9264 links_are_consistent(&p.lanes).is_ok(),
9265 "{what}: {:?}",
9266 p.lanes
9267 );
9268 };
9269 let mut p = three();
9270 let copied = p.clips()[0];
9271 assert!(
9272 copied.link.is_some(),
9273 "the clipboard clip carries its group"
9274 );
9275 assert!(p.lift(Lane::V1, 0));
9276 assert!(p.place(Lane::V1, 0, copied));
9277 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
9278 assert_eq!(
9279 p.clips().iter().filter(|c| c.link == copied.link).count(),
9280 0,
9281 "a placement belongs to no group, so it cannot duplicate one"
9282 );
9283 consistent(&p, "lift + place twice");
9284 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
9285 consistent(&p, "place through a grouped clip");
9286 assert!(p.paste(6, copied), "a rippling paste through another");
9287 consistent(&p, "paste");
9288 assert!(p.split(2));
9289 consistent(&p, "split");
9290 assert!(p.ripple_delete(1, 3));
9291 consistent(&p, "ripple_delete");
9292 assert!(p.undo());
9293 consistent(&p, "undo");
9294 }
9295
9296 /// What an edit produces is what a save writes, so *every* state the public
9297 /// API can reach has to load again. The two the verifier panel found where
9298 /// it did not: a split and a regroup handed one group id to two clips that
9299 /// were not the same span, because the lanes had been edited apart.
9300 #[test]
9301 fn every_reachable_state_reloads() {
9302 let mut p = Project::single(FILE, 150);
9303 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
9304 assert!(p.split(10), "the lanes are cut apart at 10");
9305 reloads(&p, "place on one lane, then split");
9306
9307 let mut p = Project::single(FILE, 150);
9308 assert!(p.split(30));
9309 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
9310 assert!(p.regroup(30), "only the audio lane can rejoin");
9311 assert!(p.split(60));
9312 reloads(&p, "lift, regroup one lane, split");
9313
9314 // Two audio streams of one file, both placed: two source entries with
9315 // one path between them, which is the state a stream picked out of the
9316 // library reaches -- and the state a save has to write and read back.
9317 let mut p = Project::single(FILE, 150);
9318 let second = p.import(FILE, 1);
9319 assert_eq!(second, 1, "the same file on another stream is a new source");
9320 assert!(p.append_clip(second, 150));
9321 assert!(p.split(200));
9322 reloads(
9323 &p,
9324 "a second audio stream of the same file, placed and split",
9325 );
9326 let (sources, ..) = p.without_orphan_sources();
9327 assert_eq!(
9328 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
9329 [0, 1],
9330 "both entries survive the orphan prune: both are played"
9331 );
9332 }
9333
9334 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
9335 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
9336 /// is the stamp playback puts on a decoded source frame -- and the *last*
9337 /// source frame the pump is still holding at a timeline frame has to be
9338 /// exactly the one the export encoded there, at every rate. Anything else is
9339 /// A/V drift that grows with the clip, and no test of either side alone
9340 /// would see it.
9341 ///
9342 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
9343 /// is a better answer than the floor/floor this had: floor/floor put the
9344 /// preview a whole held frame off the export at slow rates.)
9345 #[test]
9346 fn speed_maps_both_ways() {
9347 for permille in (250..=4000).step_by(1) {
9348 let speed = Speed::from_permille(permille);
9349 assert_eq!(speed.permille(), permille, "no clamping in range");
9350 for d in 0..200u32 {
9351 let want = speed.source_at(d);
9352 // What the pump shows at `d` is the last frame whose stamp has
9353 // come due -- and it is `want`, the frame the export encodes
9354 // there. Slowed, that is the frame it is still holding; sped up,
9355 // it is the newest of the several that arrived.
9356 let held = (0..=want + 8)
9357 .filter(|&s| speed.timeline_at(s) <= d)
9358 .next_back();
9359 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
9360 }
9361 for n in 1..300u32 {
9362 // A footprint is never zero: a clip occupying no timeline frame
9363 // is a placement the lane invariants cannot hold.
9364 let frames = speed.frames(n);
9365 assert!(frames >= 1, "{speed} of {n} frames");
9366 // ...and its last timeline frame never reads past the clip.
9367 assert!(
9368 speed.source_at(frames - 1) < n,
9369 "{speed}: the last timeline frame of {n} reads past the clip"
9370 );
9371 // The trim inverse never overshoots the room it was given, and
9372 // answers for every room a footprint can be.
9373 let fit = speed.fit(frames).expect("a clip fits its own footprint");
9374 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
9375 // A room narrower than one source frame's own footprint holds
9376 // nothing, and says so rather than rounding something into it.
9377 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
9378 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
9379 }
9380 }
9381 // Real time is the identity map, byte for byte.
9382 for d in 0..1000 {
9383 assert_eq!(Speed::NORMAL.source_at(d), d);
9384 assert_eq!(Speed::NORMAL.timeline_at(d), d);
9385 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
9386 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
9387 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
9388 }
9389 // The one door: no zero, no reverse, nothing past the ends.
9390 assert_eq!(Speed::from_permille(0), Speed::MIN);
9391 assert_eq!(Speed::from_permille(249), Speed::MIN);
9392 assert_eq!(Speed::from_permille(4001), Speed::MAX);
9393 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
9394 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
9395 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
9396 }
9397
9398 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
9399 /// export encodes at a timeline frame is the one playback is holding there,
9400 /// a file is as long in timeline frames as the seconds it lasts, and the two
9401 /// compose so a speeded clip at another rate is exactly both.
9402 #[test]
9403 fn rate_composes_with_speed() {
9404 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
9405 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
9406 // the identity map or a single-rate project would move.
9407 for (source_fps, timeline_fps) in [
9408 (24000. / 1001., 30.),
9409 (30., 24000. / 1001.),
9410 (60., 30.),
9411 (25., 30.),
9412 (30., 30.),
9413 ] {
9414 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
9415 for n in 0..2000u32 {
9416 let source = rate.source_at(n);
9417 // The stamp is the *first* timeline-rate frame that shows it, so
9418 // the picture on screen at `n` is the picture encoded at `n`.
9419 let held = (0..=source + 4)
9420 .filter(|&s| rate.timeline_at(s) <= n)
9421 .next_back();
9422 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
9423 }
9424 // A file of `count` frames is `timeline_at(count)` frames long here,
9425 // and its last one still reads a frame the file has.
9426 for count in 1..500u32 {
9427 let frames = rate.timeline_at(count);
9428 assert!(frames >= 1, "a file is never zero frames long");
9429 assert!(
9430 rate.source_at(frames - 1) < count,
9431 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
9432 );
9433 }
9434 // No drift: the mapping is one exact division of the *rate itself*,
9435 // not an accumulation and not a rounded rate, so an hour in is as
9436 // true as the first second. (Held to the real ratio of the two rates
9437 // the caller asked for -- `as_f64` would be true of a wrong rate.)
9438 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
9439 let want = f64::from(n) * source_fps / timeline_fps;
9440 assert!(
9441 (f64::from(rate.source_at(n)) - want).abs() < 1.,
9442 "{source_fps} on {timeline_fps}: frame {n} drifted"
9443 );
9444 }
9445 }
9446 // The timeline's own rate is the identity, whichever way it is written.
9447 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
9448 assert!(
9449 Rate::from_fps(30.0004, 30.)
9450 .expect("30.0004 over 30")
9451 .is_real_time(),
9452 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
9453 );
9454 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
9455 // one thing `matches_timeline` refuses a file for now that the rate gate
9456 // is gone.
9457 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
9458 assert!(Rate::from_fps(30., f64::NAN).is_err());
9459 for n in 0..1000 {
9460 assert_eq!(Rate::REAL_TIME.source_at(n), n);
9461 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
9462 }
9463 // ...and the composition, in the order the decoder's door applies it:
9464 // the speed picks the clip's (timeline-rate) frame, the rate picks the
9465 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
9466 // timeline frames per frame shown, each of them exactly 800/1001 of a
9467 // file frame.
9468 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
9469 let speed = Speed::from_permille(2000);
9470 for d in 0..100u32 {
9471 assert_eq!(
9472 rate.source_at(speed.source_at(d)),
9473 (u64::from(d) * 2 * 800 / 1001) as u32,
9474 "2x of a 23.976 fps file at timeline frame {d}"
9475 );
9476 }
9477 }
9478
9479 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
9480 /// source frames per timeline frame and still starts at its own in-point,
9481 /// and a half-speed one shows every source frame twice.
9482 #[test]
9483 fn a_rate_maps_timeline_frames_onto_source_frames() {
9484 let mut p = Project::single(FILE, 40);
9485 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9486 .expect("room enough");
9487 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
9488 assert_eq!(
9489 p.map(Lane::V1, 0),
9490 Some((0, 0)),
9491 "and it starts where it did"
9492 );
9493 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
9494 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
9495 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
9496 // The span a decoder is handed: as many source frames as it will read,
9497 // which is the last shown frame's own and not one more -- timeline frame
9498 // 19 shows source frame 38, so 39 frames are read and the 40th is a
9499 // picture nothing would display.
9500 let span = p.span_at(Lane::V1, 0).expect("a span");
9501 assert_eq!((span.len, span.source_len()), (20, 39));
9502 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
9503 // ...and the same clip the other way round.
9504 let mut p = Project::single(FILE, 40);
9505 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9506 .expect("room enough");
9507 assert_eq!(p.timeline_frames(), 80);
9508 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
9509 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
9510 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
9511 assert_eq!(
9512 p.map(Lane::V1, 79),
9513 Some((0, 39)),
9514 "and the last timeline frame is still inside the source range"
9515 );
9516 }
9517
9518 /// A trim of a speeded clip is still a trim of its *source*, and the edge
9519 /// still stops at the wall: the room a rate leaves is measured in timeline
9520 /// frames and the range it commits in source ones.
9521 #[test]
9522 fn trimming_a_speeded_clip_stays_inside_its_room() {
9523 let mut p = Project::single(FILE, 40);
9524 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9525 .expect("room enough");
9526 // A second clip butted against the first, so the wall is a real one.
9527 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
9528 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
9529 assert_eq!(room, (1, 20), "out to the neighbour and no further");
9530 assert!(
9531 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
9532 "clamped to the wall, which is where the edge already is"
9533 );
9534 let c = p.clips()[0];
9535 assert_eq!(c.end(), 20, "so nothing moved");
9536 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
9537 // ...and in: half the timeline frames is half the source range.
9538 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
9539 let c = p.clips()[0];
9540 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
9541 assert_eq!(c.end(), 10, "and ten timeline frames of them");
9542 assert!(sorted_disjoint(p.clips()));
9543 }
9544
9545 /// The frames a rate cannot address: at half speed each source frame is on
9546 /// screen twice, and the cut between the two showings is not a cut in the
9547 /// file. Refused, so the two halves always add up to the clip that was cut.
9548 #[test]
9549 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
9550 let mut p = Project::single(FILE, 10);
9551 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9552 .expect("room enough");
9553 assert_eq!(p.timeline_frames(), 20);
9554 assert!(
9555 !p.split(3),
9556 "an odd frame is between two showings of one frame"
9557 );
9558 assert_eq!(p.clips().len(), 1, "and nothing was cut");
9559 assert!(p.split(4), "an even one is a frame boundary");
9560 let halves = p.clips().to_vec();
9561 assert_eq!(
9562 (halves[0].end(), halves[1].start, halves[1].end()),
9563 (4, 4, 20),
9564 "the halves meet, and still end where the clip did"
9565 );
9566 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
9567 assert!(p.regroup(4), "and the inverse puts it back");
9568 assert_eq!(p.clips().len(), 1);
9569 }
9570
9571 /// The same claim, swept: random op sequences off the public surface, the
9572 /// project reloaded after every one of them. A failure prints its seed, and
9573 /// the seed replays the whole sequence.
9574 #[test]
9575 fn random_edit_sequences_reload() {
9576 // Two thousand, not two hundred: the overlap a hole punched into a slow
9577 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
9578 // sequences, and a 200-seed sweep walked straight past it (it took a
9579 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
9580 // has no business being the narrow one.
9581 for seed in 0..2000u64 {
9582 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9583 let mut next = move |n: u32| {
9584 // xorshift64*: no dependency, and the seed replays it exactly.
9585 rng ^= rng << 13;
9586 rng ^= rng >> 7;
9587 rng ^= rng << 17;
9588 (rng >> 33) as u32 % n
9589 };
9590 let mut p = Project::single(FILE, 40);
9591 for step in 0..24 {
9592 let frame = next(44);
9593 // A clipboard copy carries the group id of the take it came from
9594 // -- the input that made a placement duplicate an id -- and, one
9595 // time in three, a rate of its own: a *speeded clip placed over
9596 // a speeded clip* is the shape whose remainders have to be run
9597 // through `Speed::fit`, and it is not a shape the lanes hand out
9598 // on their own often enough to be sure of.
9599 let mut copied = *p
9600 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
9601 .get(next(4) as usize)
9602 .unwrap_or(&clip(0, 0, 5, 0));
9603 if next(3) == 0 {
9604 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
9605 }
9606 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
9607 let idx = next(4) as usize;
9608 let _ = match next(16) {
9609 // A clip dragged along its own lane to wherever the pointer
9610 // let it go: the op that moves a placement without changing
9611 // what it plays, so what it may not do is land on top of the
9612 // neighbour it was dragged at.
9613 15 => p.move_clip(lane, idx, lane, frame),
9614 // ...and a second `place`, so a punch lands inside a clip
9615 // far more often than one op in fourteen would put it there.
9616 14 => p.place(lane, frame, copied),
9617 0 => p.split(frame),
9618 1 => p.regroup(frame),
9619 2 => p.lift(lane, idx),
9620 3 => p.place(lane, frame, copied),
9621 4 => p.paste(frame, copied),
9622 5 => p.ripple_delete(frame, next(9)),
9623 6 => p.delete(idx),
9624 7 => p.undo(),
9625 // An equalizer put on and taken off in the mix: what a clip
9626 // carries has to reload with it, and the entries an undo
9627 // orphans must not come back out of the prune.
9628 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9629 9 => p.set_eq(lane, idx, None),
9630 // ...and a colour grade in the same mix, for the same
9631 // reason: it rides on the clip and its orphans must go.
9632 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
9633 11 => p.set_color(lane, idx, None),
9634 // ...and a rate in with them, which is the one of the three
9635 // that moves *placements*: a clip that grew has to be
9636 // refused rather than overlap, and one that shrank leaves a
9637 // lane that still loads. Both are what `reloads` asks.
9638 12 => p
9639 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9640 .is_ok(),
9641 _ => p.append_clip(0, 1 + next(9)),
9642 };
9643 reloads(&p, &format!("seed {seed}, step {step}"));
9644 }
9645 }
9646 }
9647
9648 /// The save/load round trip a project must survive: the parts a save writes,
9649 /// handed back to the constructor a load goes through -- every lane of them,
9650 /// and the reloaded timeline has to be the same lanes in the same order.
9651 fn reloads(p: &Project, what: &str) {
9652 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
9653 match Project::from_parts(sources, lanes, eq, color, transform) {
9654 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
9655 Ok(back) => {
9656 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
9657 // Placements, not whole clips: an orphan prune renumbers the
9658 // sources a clip names, which is the point of it.
9659 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
9660 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
9661 };
9662 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
9663 // The prune renumbers the eq table too, so what has to survive
9664 // is the settings themselves, clip by clip.
9665 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
9666 p.lanes()
9667 .into_iter()
9668 .map(|l| {
9669 (0..p.lane(l).len())
9670 .map(|i| p.eq_of(l, i).cloned())
9671 .collect()
9672 })
9673 .collect()
9674 };
9675 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
9676 // The colour table renumbers in the same prune, so the same
9677 // claim: the params a clip names, not the index it names them by.
9678 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
9679 p.lanes()
9680 .into_iter()
9681 .map(|l| {
9682 (0..p.lane(l).len())
9683 .map(|i| p.color_of(l, i).copied())
9684 .collect()
9685 })
9686 .collect()
9687 };
9688 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
9689 // ...and the transform table, by the same claim again.
9690 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
9691 p.lanes()
9692 .into_iter()
9693 .map(|l| {
9694 (0..p.lane(l).len())
9695 .map(|i| p.transform_of(l, i).copied())
9696 .collect()
9697 })
9698 .collect()
9699 };
9700 assert_eq!(
9701 transforms(&back),
9702 transforms(p),
9703 "{what}: the transforms changed"
9704 );
9705 }
9706 }
9707 }
9708
9709 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
9710 /// -- each one sorted and disjoint, and one span per group id -- asserted
9711 /// directly, where the point is the invariant rather than the round trip.
9712 fn invariants_hold(p: &Project, what: &str) {
9713 for lane in p.lanes() {
9714 assert!(
9715 sorted_disjoint(p.lane(lane)),
9716 "{what}: {} is out of order or overlaps itself: {:?}",
9717 lane.label(),
9718 p.lane(lane)
9719 );
9720 }
9721 if let Err(e) = links_are_consistent(&p.lanes) {
9722 panic!("{what}: {e}\n{:?}", p.lanes);
9723 }
9724 }
9725
9726 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
9727 /// edited without any other lane hearing about it. A handle naming a lane
9728 /// that is not there reads as empty and refuses to mutate.
9729 #[test]
9730 fn a_third_lane_is_a_peer() {
9731 let mut p = three();
9732 assert_eq!(p.lane_count(LaneKind::Video), 1);
9733 assert_eq!(p.lane_count(LaneKind::Audio), 1);
9734 let v2 = p.add_lane(LaneKind::Video);
9735 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
9736 assert_eq!(v2.label(), "V2");
9737 assert_eq!(p.lane_count(LaneKind::Video), 2);
9738 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9739 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
9740
9741 // A handle for a lane that is not there: empty, and no mutation takes.
9742 let v3 = Lane::new(LaneKind::Video, 2);
9743 assert!(p.lane(v3).is_empty());
9744 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
9745 assert!(!p.lift(v3, 0));
9746 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
9747
9748 // Placing on V2 moves nothing else, and the lane can outrun the rest.
9749 let before = shape(&p);
9750 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9751 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
9752 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
9753 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9754 assert_eq!(
9755 p.timeline_frames(),
9756 16,
9757 "the last lane to end sets the length"
9758 );
9759 assert_eq!(p.map(v2, 5), Some((0, 21)));
9760 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
9761 assert_eq!(
9762 p.span_at(v2, 0),
9763 Some(Span {
9764 start: 0,
9765 len: 4,
9766 from: None,
9767 speed: Speed::NORMAL
9768 })
9769 );
9770 // Every lane still covers the whole timeline, gaps included.
9771 for l in p.lanes() {
9772 let spans = p.spans_from(l, 0);
9773 assert_eq!(
9774 spans.iter().map(|s| s.len).sum::<u32>(),
9775 16,
9776 "{}",
9777 l.label()
9778 );
9779 }
9780 // ...and playback still reads V1 and A1, whatever else is there.
9781 assert_eq!(p.clips(), p.lane(Lane::V1));
9782 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
9783 let segments = p.segments_from(0, FPS);
9784 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
9785 assert_eq!(
9786 segments[3],
9787 (None, 0.0, 7.0 / FPS),
9788 "A1 keeps the clock counting over the picture V2 added"
9789 );
9790 invariants_hold(&p, "place on V2");
9791
9792 // A lift is that lane's business too, and the lane list undoes.
9793 assert!(p.lift(v2, 0));
9794 assert!(p.lane(v2).is_empty());
9795 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
9796 assert!(p.undo());
9797 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9798 assert!(p.undo());
9799 assert!(p.lane(v2).is_empty(), "the placement came off V2");
9800 assert!(p.undo(), "and one more step takes the lane itself back");
9801 assert_eq!(p.lane_count(LaneKind::Video), 1);
9802 assert_eq!(shape(&p), shape(&three()));
9803 }
9804
9805 /// The add taken back: an empty lane comes off, a lane holding clips never
9806 /// does (and says which clips), the last lane of a kind never does, the
9807 /// lanes below the one that went move up an `ord`, and one undo puts it
9808 /// back where it stood.
9809 #[test]
9810 fn an_empty_lane_comes_off_again() {
9811 let mut p = three();
9812 let v2 = p.add_lane(LaneKind::Video);
9813 let v3 = p.add_lane(LaneKind::Video);
9814 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
9815 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
9816 let history = p.history.len();
9817
9818 // The last lane of its kind stays: `V1`/`A1` are where an import and a
9819 // paste land, and a project missing one would swallow half of a file
9820 // dropped on it.
9821 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
9822 assert_eq!(
9823 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
9824 "there is no V10 to remove"
9825 );
9826
9827 // A lane with clips on it refuses and names them: a track removal never
9828 // deletes a take.
9829 let refusal = why(p.remove_lane(v3));
9830 assert!(refusal.contains("V3 still holds"), "{refusal}");
9831 assert!(refusal.contains(FILE), "{refusal}");
9832 assert!(refusal.contains("at frame 0"), "{refusal}");
9833 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
9834 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
9835
9836 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
9837 // all.
9838 p.remove_lane(v2).expect("V2 is empty");
9839 assert_eq!(p.lane_count(LaneKind::Video), 2);
9840 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9841 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
9842 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
9843 invariants_hold(&p, "remove V2");
9844
9845 // ...and one stroke puts the empty lane back above it.
9846 assert!(p.undo());
9847 assert_eq!(p.lane_count(LaneKind::Video), 3);
9848 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
9849 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
9850 }
9851
9852 /// A track dragged to another place in the stack: the whole lane travels --
9853 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
9854 /// a video one, a lane that crosses one of its own kind swaps names with it
9855 /// (and swaps the composite with it), one undo puts the order back, and a
9856 /// save carries it.
9857 #[test]
9858 fn a_track_is_dragged_to_another_place_in_the_stack() {
9859 let mut p = three();
9860 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
9861 let before = shape(&p);
9862 let history = p.history.len();
9863
9864 // A1 over V1: the screen is rearranged and nothing else is. Both keep
9865 // their names -- neither crossed a lane of its own kind -- so every
9866 // handle a front-end holds still names the track it named before.
9867 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
9868 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
9869 assert_eq!(
9870 shape(&p),
9871 vec![before[1].clone(), before[0].clone()],
9872 "each lane's clips travelled with it, and none was remapped"
9873 );
9874 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
9875 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
9876 invariants_hold(&p, "A1 over V1");
9877
9878 // Nothing moves for a lane that is not there, a slot that is not, or a
9879 // lane already standing in the one it was pointed at.
9880 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
9881 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
9882 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
9883 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
9884
9885 // ...and one stroke puts the order back.
9886 assert!(p.undo());
9887 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
9888 assert_eq!(shape(&p), before);
9889
9890 // A second video lane over the first: display order *is* the stack, so
9891 // the last video lane covering a frame is the picture that shows.
9892 let v2 = p.add_lane(LaneKind::Video);
9893 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
9894 let over = shape(&p)[2].clone();
9895 assert_eq!(
9896 p.composite_span_at(0).map(|s| s.len),
9897 Some(5),
9898 "V2's five frames are what frame 0 shows"
9899 );
9900
9901 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
9902 // a position among the lanes of its kind. The picture that wins changes
9903 // with it: the take that was covering is the covered one now.
9904 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
9905 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
9906 assert_eq!(
9907 shape(&p),
9908 vec![over.clone(), before[0].clone(), before[1].clone()],
9909 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
9910 );
9911 assert_eq!(
9912 p.composite_span_at(0).map(|s| s.len),
9913 Some(3),
9914 "the lower video lane wins, and it is the old V1 now"
9915 );
9916 invariants_hold(&p, "V2 over V1");
9917
9918 // A save writes that order and a load takes it back.
9919 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9920 assert_eq!(
9921 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9922 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
9923 );
9924 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
9925 assert_eq!(back.lanes(), p.lanes());
9926 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
9927
9928 assert!(p.undo(), "and the stack goes back to how it stood");
9929 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
9930 }
9931
9932 /// The grouping rule across more than two lanes, under the offset model: a
9933 /// split *keeps* the group on the left halves and hands the right halves of
9934 /// that group one fresh id of their own -- a clip in no group comes out of
9935 /// the cut in none. So a take cut apart is two takes, one per side, and a
9936 /// lane that was never part of it stays out of both.
9937 #[test]
9938 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
9939 let mut p = Project::single(FILE, 9);
9940 let take = p.clips()[0].link.expect("a fresh project is one take");
9941 let v2 = p.add_lane(LaneKind::Video);
9942 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
9943 assert!(p.split(4));
9944 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
9945 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
9946 };
9947 let (left, right) = (side(&p, 0), side(&p, 1));
9948 // The lanes in order are V1, A1, V2: the take's two keep its id on the
9949 // left, and the placed clip never had one for the cut to keep.
9950 assert_eq!(
9951 left,
9952 vec![Some(take), Some(take), None],
9953 "the left halves keep the take"
9954 );
9955 // ...and the right halves of that take are one fresh group.
9956 assert_eq!(right[0], right[1]);
9957 assert_ne!(right[0], Some(take));
9958 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
9959 invariants_hold(&p, "split across three lanes");
9960
9961 // V2 ends early: the left halves still keep what each clip carried --
9962 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
9963 // shared by exactly the take's lanes.
9964 let mut p = Project::single(FILE, 9);
9965 let v2 = p.add_lane(LaneKind::Video);
9966 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
9967 assert!(p.split(3));
9968 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
9969 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
9970 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
9971 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
9972 invariants_hold(&p, "split where one lane ends early");
9973
9974 // The inverse rejoins each lane into the group its left half kept.
9975 assert!(p.regroup(3));
9976 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
9977 assert_eq!(
9978 p.lane(Lane::V1)[0].link,
9979 Some(take),
9980 "the take's id is back, not a fresh one"
9981 );
9982 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
9983 invariants_hold(&p, "regroup across three lanes");
9984 }
9985
9986 /// A group is one placement per lane, on however many lanes carry the id --
9987 /// not a video/audio pair and not a pairing by `ord` -- and the members may
9988 /// cover whatever frames they cover: the offset between them is what a
9989 /// hand-built group keeps. Lanes built by hand, because the rule is checked
9990 /// at the untrusted door and no edit can produce the one thing it refuses.
9991 #[test]
9992 fn a_group_may_span_any_lane() {
9993 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
9994 let one = |start: u32, end: u32, link| Clip {
9995 fade_in: 0,
9996 fade_out: 0,
9997 transition_out: 0,
9998 start,
9999 in_frame: start,
10000 out_frame: end,
10001 source: 0,
10002 link: Some(link),
10003 eq: None,
10004 color: None,
10005 transform: None,
10006 fit: FitPolicy::default(),
10007 speed: Speed::NORMAL,
10008 };
10009 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
10010 let kinds = [
10011 LaneKind::Video,
10012 LaneKind::Audio,
10013 LaneKind::Video,
10014 LaneKind::Audio,
10015 ];
10016 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
10017 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
10018 };
10019 let take = || vec![one(0, 4, 7)];
10020 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
10021 // The same take on V1 + A2 only, the lanes between it empty: legal, the
10022 // way a lifted half is legal.
10023 let across = build([take(), Vec::new(), Vec::new(), take()]);
10024 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
10025 // ...and so is a group whose members disagree about their spans: the
10026 // offset between them is the hand's business, not the loader's.
10027 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
10028 assert!(
10029 links_are_consistent(&apart).is_ok(),
10030 "[0, 4) on V1 and [2, 6) on A2 are one group"
10031 );
10032 // One id twice in one lane is still that lane's error, by name.
10033 let twice = build([
10034 Vec::new(),
10035 Vec::new(),
10036 vec![one(0, 4, 7), one(4, 8, 7)],
10037 Vec::new(),
10038 ]);
10039 assert_eq!(
10040 links_are_consistent(&twice).unwrap_err().to_string(),
10041 "link 7 names two clips in the V2 lane"
10042 );
10043 }
10044
10045 /// Every lane a save writes comes out, in display order and with its kind --
10046 /// an empty one included, since it is state a front-end shows -- and a
10047 /// two-lane project still writes exactly the parts it always did.
10048 #[test]
10049 fn a_save_writes_every_lane_it_has() {
10050 let mut p = three();
10051 let before = p.without_orphan_sources();
10052 assert_eq!(before.1.len(), 2, "V1 and A1");
10053 let v2 = p.add_lane(LaneKind::Video);
10054 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10055 let a2 = p.add_lane(LaneKind::Audio);
10056 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10057 assert_eq!(
10058 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10059 [
10060 LaneKind::Video,
10061 LaneKind::Audio,
10062 LaneKind::Video,
10063 LaneKind::Audio
10064 ],
10065 "display order, not video-then-audio"
10066 );
10067 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
10068 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
10069 // ...and all four load again as the same four.
10070 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
10071 assert_eq!(back.lanes(), p.lanes());
10072 assert_eq!(back.lane(a2), p.lane(a2));
10073
10074 // Taking the lanes back leaves exactly what a two-lane save wrote.
10075 for _ in 0..3 {
10076 assert!(p.undo());
10077 }
10078 assert_eq!(
10079 p.without_orphan_sources(),
10080 before,
10081 "byte for byte the same parts a two-lane save always wrote"
10082 );
10083 }
10084
10085 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
10086 /// three lanes and grows more: every lane's own order and the one
10087 /// span-per-id rule after every op, *and* the reload the v4 format restored
10088 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
10089 /// project of any number of lanes.
10090 #[test]
10091 fn random_edit_sequences_keep_many_lanes_consistent() {
10092 for seed in 0..2000u64 {
10093 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
10094 let mut next = move |n: u32| {
10095 rng ^= rng << 13;
10096 rng ^= rng >> 7;
10097 rng ^= rng << 17;
10098 (rng >> 33) as u32 % n
10099 };
10100 let mut p = Project::single(FILE, 40);
10101 let v2 = p.add_lane(LaneKind::Video);
10102 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
10103 let lanes = [Lane::V1, Lane::A1, v2];
10104 for step in 0..24 {
10105 let frame = next(44);
10106 let copied = *p
10107 .lane(lanes[next(3) as usize])
10108 .get(next(4) as usize)
10109 .unwrap_or(&clip(0, 0, 5, 0));
10110 let lane = lanes[next(3) as usize];
10111 let idx = next(4) as usize;
10112 let _ = match next(14) {
10113 // The drag, in the mix: a clip dragged along its own lane
10114 // and onto another one, at a frame the pointer picked --
10115 // which is where the group rule and the sorted+disjoint one
10116 // meet, since every half travels the same distance.
10117 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
10118 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
10119 11 => p.set_eq(lane, idx, None),
10120 // A rate, which on many lanes is the group rule as well:
10121 // every clip carrying the link moves together or none of
10122 // them does, and `invariants_hold` is what says so.
10123 12 => p
10124 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
10125 .is_ok(),
10126 0 => p.split(frame),
10127 1 => p.regroup(frame),
10128 2 => p.lift(lane, idx),
10129 3 => p.place(lane, frame, copied),
10130 4 => p.paste(frame, copied),
10131 5 => p.ripple_delete(frame, next(9)),
10132 6 => p.delete(idx),
10133 7 => p.undo(),
10134 8 => {
10135 p.add_lane(if next(2) == 0 {
10136 LaneKind::Video
10137 } else {
10138 LaneKind::Audio
10139 });
10140 true
10141 }
10142 _ => p.append_clip(0, 1 + next(9)),
10143 };
10144 invariants_hold(&p, &format!("seed {seed}, step {step}"));
10145 reloads(&p, &format!("seed {seed}, step {step}"));
10146 }
10147 }
10148 }
10149
10150 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
10151 /// there, `V1` shows again on either side of it, and a frame no video lane
10152 /// covers is a gap however many lanes there are.
10153 #[test]
10154 fn the_composite_is_the_topmost_lane_with_a_clip() {
10155 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10156 let lanes = vec![
10157 // V1: the whole 30 frames of source 0.
10158 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10159 // V2: source 1 over the middle third.
10160 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
10161 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10162 ];
10163 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10164 assert_eq!(
10165 p.composite_spans_from(0),
10166 vec![
10167 Span {
10168 start: 0,
10169 len: 10,
10170 from: Some((0, 0)),
10171 speed: Speed::NORMAL
10172 },
10173 Span {
10174 start: 10,
10175 len: 10,
10176 from: Some((1, 5)),
10177 speed: Speed::NORMAL
10178 },
10179 Span {
10180 start: 20,
10181 len: 10,
10182 from: Some((0, 20)),
10183 speed: Speed::NORMAL
10184 },
10185 ],
10186 "V2 takes over for its own span and hands V1 back"
10187 );
10188 // A mid-span ask resolves the same way, which is what a seek does.
10189 assert_eq!(
10190 p.composite_span_at(15),
10191 Some(Span {
10192 start: 15,
10193 len: 5,
10194 from: Some((1, 10)),
10195 speed: Speed::NORMAL
10196 })
10197 );
10198 assert_eq!(p.composite_span_at(30), None, "past the end");
10199
10200 // A hole in V1 under V2's clip: black between the two, and black after
10201 // both run out (the audio lane is still holding the timeline open).
10202 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10203 let holed = vec![
10204 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
10205 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
10206 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10207 ];
10208 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
10209 assert_eq!(
10210 p.composite_spans_from(0),
10211 vec![
10212 Span {
10213 start: 0,
10214 len: 5,
10215 from: Some((0, 0)),
10216 speed: Speed::NORMAL
10217 },
10218 Span {
10219 start: 5,
10220 len: 5,
10221 from: None,
10222 speed: Speed::NORMAL
10223 },
10224 Span {
10225 start: 10,
10226 len: 10,
10227 from: Some((1, 0)),
10228 speed: Speed::NORMAL
10229 },
10230 Span {
10231 start: 20,
10232 len: 10,
10233 from: None,
10234 speed: Speed::NORMAL
10235 },
10236 ]
10237 );
10238
10239 // One video lane: the composite *is* that lane, span for span -- the
10240 // promise every existing two-lane project rests on.
10241 let p = Project::single(FILE, 30);
10242 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
10243 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
10244 }
10245
10246 /// Every audio lane holding something gets a play list, and only those.
10247 #[test]
10248 fn audio_segments_cover_every_lane_that_holds_something() {
10249 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10250 let lanes = vec![
10251 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10252 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10253 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
10254 (LaneKind::Audio, Vec::new()),
10255 ];
10256 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10257 let lists = p.audio_segments_from(0, FPS);
10258 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
10259 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
10260 // A2 is a gap up to frame 15, then the whole of source 1.
10261 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
10262
10263 // No audio lane holds anything: one all-gap list, so such a timeline
10264 // still plays silence against a master clock.
10265 let p = Project::from_parts(
10266 vec![Source::new(FILE, 0)],
10267 vec![
10268 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10269 (LaneKind::Audio, Vec::new()),
10270 ],
10271 vec![],
10272 vec![],
10273 Vec::new(),
10274 )
10275 .expect("valid parts");
10276 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
10277 }
10278}