forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb8aec29Tahinli2 months ago966 commits

project.rs10868 lines, 467.6 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! 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::eq::EqParams;
81use crate::limiter::{Limiter, db_to_linear};
82use crate::scale::FitPolicy;
83use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
84use crate::transform::TransformParams;
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 /// The palette, which the history holds beside the lanes and an undo
120 /// therefore restores ([`Project::undo`]). Left out of this shape, a
121 /// round-trip check passed with the palette restore deleted outright.
122 pub(crate) Vec<SubtitleTrack>,
123 pub(crate) ProjectSettings,
124);
125
126impl Speed {
127 /// Real time -- what every clip is until something says otherwise, and the
128 /// value every path in this engine short-circuits on.
129 pub const NORMAL: Speed = Speed(1000);
130 pub const MIN: Speed = Speed(250);
131 pub const MAX: Speed = Speed(4000);
132
133 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
134 /// unrepresentable rather than merely refused: nothing downstream divides
135 /// by a speed that could be nothing.
136 pub fn from_permille(permille: u16) -> Self {
137 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
138 }
139
140 pub fn permille(self) -> u16 {
141 self.0
142 }
143
144 pub fn is_normal(self) -> bool {
145 self == Self::NORMAL
146 }
147
148 /// As a multiplier, for the sound worker and for a label.
149 pub fn as_f64(self) -> f64 {
150 f64::from(self.0) / 1000.
151 }
152
153 /// How many *timeline* frames `source` source frames occupy at this rate --
154 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
155 /// clip that occupied no frames would be an empty placement, which the lane
156 /// invariant forbids and which nothing could ever click on again.
157 pub fn frames(self, source: u32) -> u32 {
158 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
159 n.clamp(1, u64::from(u32::MAX)) as u32
160 }
161
162 /// The mapping itself: which source frame of a clip the `offset`th timeline
163 /// frame of it plays. Floored, so the first timeline frame is the clip's own
164 /// in-point at every rate.
165 pub fn source_at(self, offset: u32) -> u32 {
166 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
167 }
168
169 /// Its inverse, for a decoder's frames on their way back out: which timeline
170 /// frame of the clip the `offset`th *source* frame of it lands on.
171 ///
172 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
173 /// decoded frame with this and shows the newest whose stamp has come due, so
174 /// what is on screen at timeline offset `d` is the last source frame with
175 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
176 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
177 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
178 /// the two the same way would put the preview a frame off the export at some
179 /// speeds and a whole held frame off at slow ones -- drift that no test of
180 /// either side alone would catch.
181 pub fn timeline_at(self, offset: u32) -> u32 {
182 (u64::from(offset) * 1000)
183 .div_ceil(u64::from(self.0))
184 .min(u64::from(u32::MAX)) as u32
185 }
186
187 /// The longest source range that still *fits* in `frames` timeline frames at
188 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
189 /// any room narrower than the four timeline frames one source frame occupies.
190 ///
191 /// What a trim commits and what a hole-punch leaves behind: rounding could
192 /// otherwise hand back a range wider than the room, and a clip that outgrew
193 /// its room would overlap its neighbour -- the one thing a lane may never do.
194 /// `None` is not an error, it is "no remainder": the caller drops that piece
195 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
196 /// is `frames` itself, so nothing about an unspeeded edit changes.
197 pub fn fit(self, frames: u32) -> Option<u32> {
198 if frames == 0 || self.frames(1) > frames {
199 return None;
200 }
201 let mut src = self.source_at(frames).max(1);
202 // At most a step or two: `frames` is monotone in `src` and the rounding
203 // above can only overshoot by one source frame's worth.
204 while src > 1 && self.frames(src) > frames {
205 src -= 1;
206 }
207 Some(src)
208 }
209
210 /// How many timeline frames `source` source frames of head (or tail) are
211 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
212 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
213 /// empty, but the room in front of one may well be.
214 pub fn room(self, source: u32) -> u32 {
215 match source {
216 0 => 0,
217 n => self.frames(n),
218 }
219 }
220
221 /// How many timeline frames from `offset` on show the **same** source frame:
222 /// one at real time and faster, more when the clip is slowed. What an export
223 /// encodes without decoding the same picture twice, and the count that makes
224 /// its frame walk exactly as long as the span.
225 pub fn repeats(self, offset: u32, len: u32) -> u32 {
226 let want = self.source_at(offset);
227 (offset..len)
228 .take_while(|&t| self.source_at(t) == want)
229 .count() as u32
230 }
231
232 /// Where in the source a cut `offset` timeline frames into a clip of `len`
233 /// source frames falls -- and `None` when this rate cannot address that
234 /// frame at all.
235 ///
236 /// At half speed a clip of ten source frames is twenty timeline frames long
237 /// and every source frame is on screen twice, so a cut between the two
238 /// showings of one frame is not a cut in the *file*: taking it would leave
239 /// two halves whose lengths no longer add up to the clip that was cut --
240 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
241 /// the model stays exact and the front-end can say why. At real time every
242 /// interior frame answers, which is the path a project without speeds is on.
243 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
244 let src = self.source_at(offset);
245 (src > 0
246 && src < len
247 && self.frames(src) == offset
248 && self.frames(len - src) == self.frames(len) - offset)
249 .then_some(src)
250 }
251}
252
253impl Default for Speed {
254 fn default() -> Self {
255 Self::NORMAL
256 }
257}
258
259impl std::fmt::Display for Speed {
260 /// `2.00x` -- what a card prints and what a clip box is marked with.
261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262 write!(f, "{:.2}x", self.as_f64())
263 }
264}
265
266/// What a file's own frame rate is against the timeline's, as an exact
267/// rational: how many frames of the *file* one frame of the timeline is worth.
268///
269/// Every frame number in this module counts **timeline** frames -- a clip's
270/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
271/// timeline is as many frames long as the seconds it lasts, and every edit
272/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
273/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
274/// opens a worker with it and [`crate::export`] pulls pictures through it. The
275/// file's own numbering exists nowhere else.
276///
277/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
278/// export encodes at a timeline frame has to be the frame playback is holding
279/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
280/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
281///
282/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
283/// stays `800/1001` however far the timeline runs, where a rate rounded to
284/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
285/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
286///
287/// [`PlaybackSession`]: crate::PlaybackSession
288#[derive(Clone, Copy, PartialEq, Eq, Debug)]
289pub struct Rate {
290 /// Frames of the file...
291 source: u32,
292 /// ...per this many frames of the timeline it plays on. Never zero.
293 timeline: u32,
294}
295
296impl Rate {
297 /// A file shot at the timeline's own rate: every conversion below is the
298 /// identity, which is the path a single-rate project is on.
299 pub const REAL_TIME: Self = Self {
300 source: 1,
301 timeline: 1,
302 };
303
304 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
305 /// exactly.
306 ///
307 /// Both rates come out of a container as a division, so neither is ever the
308 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
309 /// already knows how to name one exactly -- it is the same pair the muxer
310 /// counts an export's frames in -- and this is that pair divided by that
311 /// pair, reduced. A rate no timescale can name is an `Err` in that
312 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
313 /// where a file carrying one is refused by name, beside the codec.
314 ///
315 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
316 /// timeline that had ever opened in this editor before mixed rates.
317 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
318 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
319 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
320 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
321 let num = u64::from(src_scale) * u64::from(tl_ticks);
322 let den = u64::from(src_ticks) * u64::from(tl_scale);
323 Ok(Self::reduced(num, den))
324 }
325
326 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
327 fn reduced(num: u64, den: u64) -> Self {
328 let g = gcd(num, den);
329 let (mut num, mut den) = (num / g, den / g);
330 // A ratio no pair of real frame rates produces, but the fields are `u32`
331 // so that every multiplication below fits a `u64` at any frame count.
332 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
333 (num, den) = (num.div_ceil(2), den.div_ceil(2));
334 }
335 Self {
336 source: num.max(1) as u32,
337 timeline: den.max(1) as u32,
338 }
339 }
340
341 /// The same file against a timeline that has itself been retimed: `self` is
342 /// its frames per frame of the old timeline and `k` is old frames per new
343 /// one, so this is its frames per frame of the *new* one -- exactly, without
344 /// going back through an `f64` fps that names neither rate
345 /// ([`crate::PlaybackSession::set_frame_rate`]).
346 pub fn then(self, k: Rate) -> Self {
347 Self::reduced(
348 u64::from(self.source) * u64::from(k.source),
349 u64::from(self.timeline) * u64::from(k.timeline),
350 )
351 }
352
353 pub fn is_real_time(self) -> bool {
354 self.source == self.timeline
355 }
356
357 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
358 /// is, given the timeline's, for a library row that names it.
359 pub fn as_f64(self) -> f64 {
360 f64::from(self.source) / f64::from(self.timeline)
361 }
362
363 /// Which frame of the file the `frame`th timeline-rate frame of it is:
364 /// floored, [`Speed::source_at`]'s half of the pair.
365 pub fn source_at(self, frame: u32) -> u32 {
366 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
367 .min(u64::from(u32::MAX)) as u32
368 }
369
370 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
371 /// timeline-rate frame that shows source frame `source_frame` -- which is
372 /// the stamp playback puts on a decoded picture, and, applied to a file's
373 /// frame *count*, how long that file is in timeline frames.
374 pub fn timeline_at(self, source_frame: u32) -> u32 {
375 (u64::from(source_frame) * u64::from(self.timeline))
376 .div_ceil(u64::from(self.source))
377 .min(u64::from(u32::MAX)) as u32
378 }
379}
380
381/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
382/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
383fn gcd(a: u64, b: u64) -> u64 {
384 match b {
385 0 => a.max(1),
386 b => gcd(b, a % b),
387 }
388}
389
390/// A half-open `[in_frame, out_frame)` range of frames of source
391/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
392/// Never empty.
393///
394/// Counted at the **timeline's** frame rate, not the file's: a source shot at
395/// another rate is converted at the decoder's door ([`Rate`]), so every edit
396/// here is frames of one clock.
397#[derive(Clone, Copy, PartialEq, Eq, Debug)]
398pub struct Clip {
399 /// Timeline frame the clip's first frame is shown at. Meaningless on a
400 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
401 /// with where the caller asked for.
402 pub start: u32,
403 pub in_frame: u32,
404 pub out_frame: u32,
405 /// Index into [`Project::sources`].
406 pub source: usize,
407 /// Group id: clips sharing one were split from the same take. `None` for a
408 /// clip that belongs to no group.
409 pub link: Option<u32>,
410 /// Index into the project's equalizer table
411 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
412 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
413 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
414 /// plain assignment. The table is append-only within a session, so an index
415 /// on a clipboard clip or inside an undo snapshot can never dangle.
416 pub eq: Option<u16>,
417 /// Index into the project's colour table
418 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
419 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
420 /// promises: `Copy`, append-only within a session, never dangling.
421 pub color: Option<u16>,
422 /// Index into the project's transform table
423 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
424 /// clip that plays at its fit policy's own placement. An index for
425 /// [`Clip::color`]'s reason and with the same promises.
426 pub transform: Option<u16>,
427 /// How this clip's picture meets a project canvas of another shape
428 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
429 /// two above: it is one byte with no parameters, so there is nothing for a
430 /// table to share, and a clip that is the project's own size never consults
431 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
432 /// where the aspect does not agree.
433 pub fit: FitPolicy,
434 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
435 /// eq and colour indexes: it is two bytes with nothing to share, and a table
436 /// would put a level of indirection between the mapping and the one number
437 /// every frame of it is divided by.
438 ///
439 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
440 /// the clip plays, so a trim and a split still address the file. What it
441 /// changes is how many *timeline* frames that range is spread over
442 /// ([`Clip::frames`]).
443 pub speed: Speed,
444 /// Timeline frames of ramp-up from silence at the clip's own start, inline
445 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
446 /// number with nothing to share, and every consumer (mixer, exporter) wants
447 /// it sitting right next to the frame range it shapes. Clamped to the
448 /// clip's own length by the setter -- never wider than the clip is long.
449 pub fade_in: u32,
450 /// Timeline frames of ramp-down to silence at the clip's own end. Same
451 /// promises as [`Clip::fade_in`].
452 pub fade_out: u32,
453 /// Timeline frames of cross-dissolve into the clip immediately after this
454 /// one on the same video lane, at this clip's own end -- `0` for a hard
455 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
456 /// reason, and clamped the same way by its setter
457 /// ([`Project::set_transition_out`]): never wider than this clip's own
458 /// length, nor than the successor it dissolves into. Meaningless -- and
459 /// left as whatever it was -- the moment the next clip stops abutting
460 /// this one; a reader that cares checks adjacency itself rather than
461 /// trusting this field alone, exactly as a stored fade is trusted only
462 /// because a clip's own length is checked beside it.
463 pub transition_out: u32,
464 /// Non-zero: this clip is a waveform of its source's sound, painted
465 /// onto a video lane. Bit 0 is the flag; bits 1-2 style; bit 3 fast.
466 /// Zero is an ordinary picture. Older project files have no field and
467 /// mean zero.
468 pub visualizer: u8,
469 /// Packed look: hue 0-255, sat 0-255, strands 0-255, glow 0-255 in the
470 /// low four bytes as they have been since v22, then the strand colour's
471 /// own bytes above them -- its hue at 32 and sat at 40
472 /// ([`crate::decode::viz_strand_hue_ui`]) -- with the top bit as
473 /// [`crate::decode::viz_strand_set`]. All-zero is the default (timeline
474 /// azure, full sat, 8 strands, glow 2, no strand colour of its own).
475 /// Older files have no field and mean zero; a v22 file's 32-bit value
476 /// is the low half of this one, byte for byte.
477 pub viz_paint: u64,
478}
479
480impl Clip {
481 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
482 /// reads out of its file -- not how long it is on the timeline, which is
483 /// [`Clip::frames`] and differs the moment it is speeded.
484 pub fn len(&self) -> u32 {
485 self.out_frame - self.in_frame
486 }
487
488 /// Timeline frames it occupies: its source range at its own speed, never
489 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
490 /// what it overlaps, how wide its box is -- is asked of this and not of
491 /// [`Clip::len`].
492 pub fn frames(&self) -> u32 {
493 self.speed.frames(self.len())
494 }
495
496 /// One past the last timeline frame it covers.
497 pub fn end(&self) -> u32 {
498 self.start + self.frames()
499 }
500}
501
502/// A file the timeline plays from, and *which* of its audio streams it plays:
503/// a file carrying one track per language is several sources, one per stream,
504/// sharing a path. Two entries differing only in the stream are two sources --
505/// they are what a clip names, and a clip plays exactly one stream.
506///
507/// The path is always canonical ([`Source::new`]), so the same file reached by
508/// two paths is one source.
509#[derive(Clone, Debug, PartialEq, Eq)]
510pub struct Source {
511 pub path: PathBuf,
512 /// Position among the file's audio tracks in file order, the numbering
513 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
514 /// single track, and for a silent one.
515 pub audio_stream: usize,
516}
517
518impl Source {
519 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
520 Self {
521 path: canonical(path.as_ref()),
522 audio_stream,
523 }
524 }
525}
526
527/// What a lane carries, which is what a *gap* in it means: black frames on a
528/// video lane, silence on an audio one, nothing over the picture on a subtitle
529/// one.
530#[derive(Clone, Copy, PartialEq, Eq, Debug)]
531pub enum LaneKind {
532 Video,
533 Audio,
534 /// Words over the picture, placed and trimmed like everything else
535 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
536 /// so a caption is dragged, cut, rippled and undone by the machinery every
537 /// other clip already goes through.
538 ///
539 /// It carries no [`Clip`] at all, and that is what keeps the media paths
540 /// free of it: [`Project::lane`] hands back an empty slice, so every
541 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
542 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
543 /// check it already had, [`Project::composite_span_at`] and
544 /// [`Project::audio_lanes`] never look at it, and the three doors that
545 /// could still put a picture on one -- [`Project::from_parts`],
546 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
547 Subtitle,
548}
549
550/// Which lane an operation acts on: a kind plus a 0-based position among the
551/// lanes of that kind, so [`Lane::V1`] is the first video lane and
552/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
553///
554/// A handle, not the lane itself. It stays meaningful while lanes are added,
555/// and one naming a lane that is not there reads as an empty lane and refuses
556/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
557/// bounds check of its own.
558#[derive(Clone, Copy, PartialEq, Eq, Debug)]
559pub struct Lane {
560 pub kind: LaneKind,
561 pub ord: usize,
562}
563
564impl Lane {
565 /// The first video lane: what a decoder plays and what an export renders.
566 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
567 /// The first audio lane: what the audio worker plays.
568 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
569 /// The first subtitle lane -- the one a project has only once something
570 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
571 /// alone.
572 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
573
574 pub const fn new(kind: LaneKind, ord: usize) -> Self {
575 Self { kind, ord }
576 }
577
578 /// `V1`, `A2`: how a lane is written in a header column and named in an
579 /// error about it.
580 pub fn label(self) -> String {
581 let kind = match self.kind {
582 LaneKind::Video => 'V',
583 LaneKind::Audio => 'A',
584 LaneKind::Subtitle => 'S',
585 };
586 format!("{kind}{}", self.ord + 1)
587 }
588}
589
590/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
591/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
592/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
593/// frames. Never empty at either end.
594///
595/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
596/// actually has, and placed by the same one number: the window is in the
597/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
598/// placement is in timeline frames like everything else on a lane. So the lane
599/// invariant is the lane's ([`subs_sorted_disjoint`] is
600/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
601/// else, and only the two calls that change a *duration* -- a trim, and the
602/// mapping out -- ever need the timeline's rate.
603///
604/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
605/// paste and an undo snapshot are a plain assignment and can never dangle.
606#[derive(Clone, Copy, PartialEq, Eq, Debug)]
607pub struct SubClip {
608 /// Timeline frame its first frame is shown at.
609 pub start: u32,
610 /// How many timeline frames it covers; `>= 1`. Held rather than derived
611 /// from the window because a [`Project`] has no frame rate -- the rate
612 /// enters at the door of the two calls that need it -- and every placement
613 /// question (where it ends, what it overlaps) is asked in frames.
614 pub frames: u32,
615 /// Index into [`Project::subtitles`]: *which* track's words these are.
616 pub track: usize,
617 /// The half-open window of that track it shows, in microseconds from the
618 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
619 /// timed in, so no conversion stands between a cue and the window that
620 /// keeps it.
621 pub in_us: i64,
622 pub out_us: i64,
623 /// Group id: `Some` exactly when a hand put this caption in a group with
624 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
625 /// no group, and what a cut cuts apart loses the one it had
626 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
627 /// clip is what makes the caption move, trim and delete with it.
628 pub link: Option<u32>,
629}
630
631impl SubClip {
632 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
633 /// what every overlap question is asked of.
634 pub fn end(&self) -> u32 {
635 self.start + self.frames
636 }
637
638 /// How much of its track it shows, in microseconds; `>= 1` by the
639 /// never-empty invariant.
640 pub fn window_us(&self) -> i64 {
641 self.out_us - self.in_us
642 }
643
644 /// Where in its window the timeline frame `frame` falls, in microseconds --
645 /// the cut a split, a ripple and a trim all land on.
646 ///
647 /// By proportion and not by the timeline's rate: the window and the frame
648 /// count measure the same stretch of time, so the fraction of the frames
649 /// before `frame` is the fraction of the microseconds before it. That is
650 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
651 /// without either of them learning an fps.
652 fn window_at(&self, frame: u32) -> i64 {
653 let into = i64::from(frame.saturating_sub(self.start));
654 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
655 }
656}
657
658/// One lane: what it is and what it holds. A struct rather than a bare
659/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
660/// compositing mode, a name -- and it belongs next to the clips it applies to.
661#[derive(Clone, Debug)]
662struct LaneData {
663 kind: LaneKind,
664 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
665 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
666 /// ever seeing a subtitle: they all read this list.
667 clips: Vec<Clip>,
668 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
669 /// empty on a video or audio one. Beside the clips rather than an enum over
670 /// them so that everything a lane *is* -- its place in the stack, its
671 /// label, its undo snapshot, its removal -- stays one code path for all
672 /// three kinds.
673 subs: Vec<SubClip>,
674 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
675 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
676 /// makes it a different thing from a clip's equalizer: it moves everything
677 /// on the track by the same amount, cuts included. Meaningless on a video
678 /// lane, where it is kept at 0 and asked by nothing.
679 gain_db: f32,
680}
681
682impl LaneData {
683 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
684 Self {
685 kind,
686 clips,
687 subs: Vec::new(),
688 gain_db: 0.0,
689 }
690 }
691
692 /// The two lanes a project starts with: `V1` then `A1`, in display order.
693 /// One place, because a freshly opened file is exactly this pair.
694 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
695 vec![
696 LaneData::new(LaneKind::Video, video),
697 LaneData::new(LaneKind::Audio, audio),
698 ]
699 }
700}
701
702/// The placements one group id names, split by the two lists a lane holds:
703/// what a drag, a trim and a delete each have to walk, now that a group may
704/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
705/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
706/// -- so the pairs are `(lane storage index, index into that lane's list)`.
707#[derive(Default)]
708struct Members {
709 clips: Vec<(usize, usize)>,
710 subs: Vec<(usize, usize)>,
711}
712
713impl Members {
714 /// Whether the group is the one placement and no more: what a lift leaves
715 /// behind, and what every whole-group question answers "not one" for.
716 fn alone(&self) -> bool {
717 self.clips.len() + self.subs.len() < 2
718 }
719}
720
721/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
722#[derive(Clone, Copy, PartialEq, Eq, Debug)]
723pub enum Edge {
724 /// Its first timeline frame; moving it changes where in the source the clip
725 /// starts reading, so the picture behind the edge slides with it.
726 Start,
727 /// One past its last timeline frame; moving it only says how much of the
728 /// source to keep.
729 End,
730}
731
732/// What a lane holds over one stretch of the timeline: either a placed clip or
733/// a gap. Returned already trimmed to the position it was asked about, so a
734/// caller can hand `len` straight to a decoder (or to a black-frame generator).
735#[derive(Clone, Copy, PartialEq, Eq, Debug)]
736pub struct Span {
737 /// Timeline frame the span starts at.
738 pub start: u32,
739 /// Frames it covers; `>= 1`.
740 pub len: u32,
741 /// `(source index, first source frame)`, or `None` for a gap -- which the
742 /// engine renders as black frames and as silence.
743 pub from: Option<(usize, u32)>,
744 /// The rate the clip this came off plays at ([`Clip::speed`]);
745 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
746 /// timeline frames whatever it says -- the speed is how many *source* frames
747 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
748 /// come back to the timeline.
749 pub speed: Speed,
750}
751
752impl Span {
753 /// One past the last timeline frame it covers.
754 pub fn end(&self) -> u32 {
755 self.start + self.len
756 }
757
758 /// How many source frames it reads: what a decoder is asked for and how wide
759 /// an audio window is. `len` at real time, and the one arithmetic both the
760 /// picture and the sound go through, so they cannot disagree about where a
761 /// speeded clip ends.
762 pub fn source_len(&self) -> u32 {
763 match self.from {
764 // The last timeline frame's own source frame is the last one needed
765 // -- never one more, which at a slow rate would read a frame the
766 // next clip owns and at a fast one would decode a picture nothing
767 // shows.
768 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
769 None => self.len,
770 }
771 }
772
773 /// Where a source frame of this span lands on the timeline: the stamp
774 /// playback puts on a decoded frame, through the ceil half of the pair
775 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
776 /// frame, so a frame before it stamps at the span's start.
777 pub fn timeline_at(&self, source_frame: u32) -> u32 {
778 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
779 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
780 }
781}
782
783/// What one speeded audio segment asks of the worker: how many source frames to
784/// consume per output frame, and how many seconds of timeline it has to fill.
785/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
786/// resampling at all.
787#[derive(Clone, Copy, PartialEq, Debug)]
788pub struct Stretch {
789 /// Source frames per output frame -- the speed as a multiplier.
790 pub step: f64,
791 /// What the segment owes the timeline, which is what it is padded or
792 /// trimmed to.
793 pub timeline_secs: f64,
794}
795
796/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
797/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
798/// against where in the *clip* -- not the segment, which may start mid-clip
799/// on a seek -- this segment's first frame lands.
800#[derive(Clone, Copy, PartialEq, Eq, Debug)]
801pub struct Fade {
802 /// How many of the clip's own frames already played before this
803 /// segment's first frame: `0` unless playback started mid-clip.
804 pub elapsed: u32,
805 /// The clip's [`Clip::fade_in`].
806 pub fade_in: u32,
807 /// The clip's [`Clip::fade_out`].
808 pub fade_out: u32,
809 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
810 /// which this segment may only cover the tail.
811 pub total: u32,
812}
813
814impl Fade {
815 /// The gain at clip-relative frame `pos`, an equal-power curve on each
816 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
817 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
818 /// ramp, so a fade lands on silence at its very first (or very last)
819 /// frame and reaches unity smoothly rather than at a constant slope --
820 /// the same curve [`Project::crossfade`] relies on to keep two clips'
821 /// sum around one level through the join. Both ramps multiply where a
822 /// clip is short enough for them to overlap.
823 fn gain_at(self, pos: u32) -> f32 {
824 let mut g = 1.0f32;
825 if self.fade_in > 0 && pos < self.fade_in {
826 let t = pos as f32 / self.fade_in as f32;
827 g *= (t * std::f32::consts::FRAC_PI_2).sin();
828 }
829 if self.fade_out > 0 {
830 let out_start = self.total.saturating_sub(self.fade_out);
831 if pos >= out_start {
832 let remaining = self.total.saturating_sub(pos);
833 let t = remaining as f32 / self.fade_out as f32;
834 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
835 }
836 }
837 g
838 }
839
840 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
841 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
842 pub fn apply(self, frames: &mut [f32], channels: usize) {
843 for (i, block) in frames.chunks_mut(channels).enumerate() {
844 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
845 for s in block {
846 *s *= g;
847 }
848 }
849 }
850
851 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
852 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
853 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
854 /// position is in) but [`Self::apply`] multiplies *audio* frames --
855 /// `channels`-wide sample blocks at whatever rate the mix is running at,
856 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
857 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
858 /// few milliseconds into any clip, so a fade-out silenced the rest of the
859 /// clip outright and a fade-in finished before a listener's ear caught up
860 /// -- audible on nothing shorter than a clip a few fps-frames long, which
861 /// is why 338 green tests never once ran the two curves out of step.
862 /// `ratio` is `sample_rate / fps`, applied once where the audio session
863 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
864 pub fn scaled(self, ratio: f64) -> Fade {
865 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
866 Fade {
867 elapsed: conv(self.elapsed),
868 fade_in: conv(self.fade_in),
869 fade_out: conv(self.fade_out),
870 total: conv(self.total),
871 }
872 }
873}
874
875/// What a save writes and a load takes back: the sources, every lane in
876/// display order with its kind, and the equalizer and colour tables their clips
877/// index into -- [`Project::without_orphan_sources`] out,
878/// [`Project::from_parts`] in.
879pub type Parts = (
880 Vec<Source>,
881 Vec<(LaneKind, Vec<Clip>)>,
882 Vec<EqParams>,
883 Vec<ColorParams>,
884 Vec<TransformParams>,
885);
886
887/// How many undo steps a project keeps. One gesture is one step, so 100 is past
888/// any chain a person walks back by hand, and the oldest step is dropped rather
889/// than the history growing without end: a snapshot is the whole lane list plus
890/// the palette and the project's own settings, so on a 1394-clip jumpcut
891/// timeline this is a bounded ~10 MB instead of a leak that grows for as long
892/// as the session lasts.
893const HISTORY_CAP: usize = 100;
894
895/// The project's own settings, as one value: the header a `.edith` file carries
896/// beside the edit list, and what every undo step restores beside the lanes.
897/// None of it is the media's own -- the scaffolding file's picture and rate
898/// ([`PlaybackSession::native`]) stay on the session and are never rolled back.
899#[derive(Clone, Debug, PartialEq)]
900pub(crate) struct ProjectSettings {
901 /// The canvas every clip is composed onto: the project resolution, which a
902 /// clip of another size is placed onto rather than refused for.
903 pub(crate) resolution: (u32, u32),
904 /// The rate the timeline is cut at, which every clip and source is
905 /// conformed to ([`Project::retime`]).
906 pub(crate) frame_rate: f64,
907 /// Which encoder an export of this project opens its picture on
908 /// ([`crate::export::EncoderSeat`]).
909 pub(crate) encoder_seat: crate::export::EncoderSeat,
910 /// The rate the mix was picked to run at, or `None` for the one the first
911 /// audio source derives.
912 pub(crate) sample_rate: Option<u32>,
913 /// Whether the picture is decoded from the stand-ins ([`crate::proxy`]).
914 pub(crate) proxies: bool,
915 /// Whether a source that wants a stand-in gets one made for it as it
916 /// arrives ([`crate::proxy::wanted`]).
917 pub(crate) auto_proxies: bool,
918 /// Which HDR-to-SDR rendition the picture is watched and exported in.
919 pub(crate) tone: crate::tonemap::Preset,
920 /// The master limiter every lane's sound is summed through.
921 pub(crate) limiter: Limiter,
922}
923
924impl ProjectSettings {
925 /// What a project built by hand carries before its constructor names the
926 /// canvas: the defaults every fresh open has -- nobody has picked stand-ins
927 /// (the films themselves are cut), an encoder or a mix rate, and the
928 /// rendition and limiter are the reference ones. Every door that builds a
929 /// session chains [`Project::with_canvas`] straight after, so the zero
930 /// canvas here is never a project anybody plays from.
931 fn placeholder() -> Self {
932 Self {
933 resolution: (0, 0),
934 frame_rate: 0.0,
935 encoder_seat: crate::export::EncoderSeat::default(),
936 sample_rate: None,
937 proxies: false,
938 auto_proxies: true,
939 tone: crate::tonemap::Preset::default(),
940 limiter: Limiter::default(),
941 }
942 }
943}
944
945/// One undo step: the lanes, the subtitle palette and the project's own
946/// settings exactly as they were before the edit that pushed it. Whole values
947/// rather than the lane list alone, so an undo (or a redo) restores all three
948/// together and no half of one edit can come back without the others -- which
949/// is what lets a subtitle removal reindex every placement and still undo: the
950/// restored palette names the very tracks the restored placements index.
951#[derive(Clone, Debug)]
952struct Snapshot {
953 lanes: Vec<LaneData>,
954 subtitles: Vec<SubtitleTrack>,
955 settings: ProjectSettings,
956}
957
958/// One gap a close-all sweep left open, with the frame it still starts on and
959/// the same refusal a single [`Project::gap_take_scope`] close would have said.
960#[derive(Clone, Debug, PartialEq, Eq)]
961pub struct GapSkip {
962 pub start: u32,
963 pub reason: String,
964}
965
966/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
967/// skipped gaps are the take-safety refusals the sweep did not hide.
968#[derive(Clone, Debug, Default, PartialEq, Eq)]
969pub struct GapSweep {
970 pub closed: usize,
971 pub skipped: Vec<GapSkip>,
972}
973
974/// The edit list plus its undo history.
975#[derive(Clone, Debug)]
976pub struct Project {
977 /// Append-only: never popped, never reordered. See the module docs.
978 sources: Vec<Source>,
979 /// In display order, which is the order [`Lane::ord`] counts in: the nth
980 /// lane of a kind here is that kind's `ord` n. Never empty.
981 lanes: Vec<LaneData>,
982 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
983 eq: Vec<EqParams>,
984 /// The same, for [`Clip::color`].
985 color: Vec<ColorParams>,
986 /// The same, for [`Clip::transform`].
987 transform: Vec<TransformParams>,
988 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
989 /// whole lane list, the subtitle palette and the project's own settings,
990 /// so adding a lane undoes as well and so does picking a resolution. Bounded
991 /// by [`HISTORY_CAP`]: at the cap the oldest step goes.
992 history: Vec<Snapshot>,
993 /// Snapshots `undo` has stepped past; `redo` pops one. Cleared by
994 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
995 /// the undone steps came from. Not saved to `.edith`, matching `history`.
996 redo: Vec<Snapshot>,
997 /// Never rolled back by an undo: an id retired by an undone split must not
998 /// come back and group two clips that were never together.
999 next_link: u32,
1000 /// The subtitle tracks this timeline shows, in the order they were added.
1001 /// Saved as a *reference* to the file the cues came out of
1002 /// ([`crate::subtitle`]). In the history snapshots since the widened
1003 /// [`Snapshot`]: a placement names a track by index into this list, so a
1004 /// removal that reindexes the placements can only undo together with the
1005 /// palette it removed the row from.
1006 subtitles: Vec<SubtitleTrack>,
1007 /// The project's own settings ([`ProjectSettings`]) -- the canvas, the
1008 /// rate, the proxies switches, the encoder seat, the mix rate, the
1009 /// rendition and the limiter. In every snapshot, so each of them undoes
1010 /// like a lane edit: they are the header of the project's own `.edith`
1011 /// file, not this machine's, and a pick a ctrl+z could not take back
1012 /// would be the one setting with no way out.
1013 settings: ProjectSettings,
1014}
1015
1016impl Project {
1017 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
1018 /// grouped -- the state of a freshly opened video, where the timeline is the
1019 /// source. `frame_count` of 0 would break the never-empty invariant, so it
1020 /// is clamped to one frame.
1021 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
1022 let clip = Clip {
1023 fade_in: 0,
1024 fade_out: 0,
1025 transition_out: 0,
1026 visualizer: 0,
1027 viz_paint: 0,
1028 start: 0,
1029 in_frame: 0,
1030 out_frame: frame_count.max(1),
1031 source: 0,
1032 link: Some(0),
1033 eq: None,
1034 color: None,
1035 transform: None,
1036 fit: FitPolicy::default(),
1037 speed: Speed::NORMAL,
1038 };
1039 Self {
1040 // A file is opened on its first audio stream: nothing has picked
1041 // one yet, and every file with audio at all has that one.
1042 sources: vec![Source::new(path, 0)],
1043 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
1044 eq: Vec::new(),
1045 color: Vec::new(),
1046 transform: Vec::new(),
1047 history: Vec::new(),
1048 redo: Vec::new(),
1049 next_link: 1,
1050 subtitles: Vec::new(),
1051 settings: ProjectSettings::placeholder(),
1052 }
1053 }
1054
1055 /// A project rebuilt from a saved edit list -- the load half of
1056 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
1057 /// an `ord` is a lane's position among the lanes of that kind, exactly as
1058 /// [`Project::lanes`] hands them back. History is *not* saved, so
1059 /// [`Project::undo`] is `false` until the first edit of the new session.
1060 /// This is the one door untrusted parts come in through, so every invariant
1061 /// every other constructor keeps is checked here, by name and in release:
1062 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
1063 /// or a colour) that is not there, a clip whose end overflows, a lane that is
1064 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
1065 /// below.
1066 ///
1067 /// A project whose lanes are all *empty* is not among them: an emptied
1068 /// timeline is a project like any other -- it plays black and silent, it
1069 /// saves, and it loads back. What a project cannot be is laneless, because
1070 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
1071 /// handle indexes into.
1072 pub fn from_parts(
1073 sources: Vec<Source>,
1074 lanes: Vec<(LaneKind, Vec<Clip>)>,
1075 eq: Vec<EqParams>,
1076 color: Vec<ColorParams>,
1077 transform: Vec<TransformParams>,
1078 ) -> crate::Result<Self> {
1079 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
1080 return Err(format!("eq {bad} holds a band that is not a finite number").into());
1081 }
1082 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
1083 return Err(format!("color {bad} holds a value that is not a finite number").into());
1084 }
1085 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
1086 return Err(
1087 format!("transform {bad} holds a value that is not a finite number").into(),
1088 );
1089 }
1090 if lanes.is_empty() {
1091 return Err("no lanes at all: that is not a project".into());
1092 }
1093 let lanes: Vec<LaneData> = lanes
1094 .into_iter()
1095 .map(|(kind, clips)| LaneData::new(kind, clips))
1096 .collect();
1097 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
1098 let name = lane.label();
1099 // A subtitle lane carries words and never a picture
1100 // ([`LaneKind::Subtitle`]); a file that puts one there names a
1101 // source on a lane that has nothing to play it with, and every
1102 // media path below would then read a clip off a lane it does not
1103 // know about.
1104 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
1105 return Err(format!(
1106 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
1107 data.clips.len()
1108 )
1109 .into());
1110 }
1111 for c in &data.clips {
1112 if c.out_frame <= c.in_frame {
1113 return Err(format!(
1114 "{name} clip at {} plays the empty range [{}, {})",
1115 c.start, c.in_frame, c.out_frame
1116 )
1117 .into());
1118 }
1119 if c.source >= sources.len() {
1120 return Err(format!(
1121 "{name} clip at {} names source {} of {}",
1122 c.start,
1123 c.source,
1124 sources.len()
1125 )
1126 .into());
1127 }
1128 if c.start.checked_add(c.frames()).is_none() {
1129 return Err(format!(
1130 "{name} clip at {} runs past the last frame there is",
1131 c.start
1132 )
1133 .into());
1134 }
1135 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1136 return Err(format!(
1137 "{name} clip at {} names eq {} of {}",
1138 c.start,
1139 c.eq.unwrap_or_default(),
1140 eq.len()
1141 )
1142 .into());
1143 }
1144 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1145 return Err(format!(
1146 "{name} clip at {} names color {} of {}",
1147 c.start,
1148 c.color.unwrap_or_default(),
1149 color.len()
1150 )
1151 .into());
1152 }
1153 if c.transform
1154 .is_some_and(|i| usize::from(i) >= transform.len())
1155 {
1156 return Err(format!(
1157 "{name} clip at {} names transform {} of {}",
1158 c.start,
1159 c.transform.unwrap_or_default(),
1160 transform.len()
1161 )
1162 .into());
1163 }
1164 }
1165 if !sorted_disjoint(&data.clips) {
1166 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1167 }
1168 }
1169 links_are_consistent(&lanes)?;
1170 // The counter sits past every id the file names, on either of a lane's
1171 // lists: a v16 caption may carry the highest link there is, and a
1172 // re-issued id would silently group it with the next placement that
1173 // asks for one -- the loader refusing a save the editor just wrote.
1174 let next_link = lanes
1175 .iter()
1176 .flat_map(|l| {
1177 let clips = l.clips.iter().filter_map(|c| c.link);
1178 let subs = l.subs.iter().filter_map(|s| s.link);
1179 clips.chain(subs)
1180 })
1181 .max()
1182 // Saturating so a crafted file cannot make the counter wrap: at the
1183 // ceiling ids stop being fresh, which loses grouping, not memory.
1184 .map_or(0, |m| m.saturating_add(1));
1185 Ok(Self {
1186 sources: sources
1187 .iter()
1188 .map(|s| Source::new(&s.path, s.audio_stream))
1189 .collect(),
1190 lanes,
1191 eq,
1192 color,
1193 transform,
1194 history: Vec::new(),
1195 redo: Vec::new(),
1196 next_link,
1197 subtitles: Vec::new(),
1198 settings: ProjectSettings::placeholder(),
1199 })
1200 }
1201
1202 /// The first video lane -- what an export renders and what a single-lane
1203 /// caller still means by "the clips".
1204 pub fn clips(&self) -> &[Clip] {
1205 self.lane(Lane::V1)
1206 }
1207
1208 /// The clips of `lane`, or nothing at all for a lane that is not there.
1209 pub fn lane(&self, lane: Lane) -> &[Clip] {
1210 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1211 }
1212
1213 /// Every lane's handle, in display order -- what a walk over "all lanes"
1214 /// iterates, and what a front-end lays out top to bottom.
1215 pub fn lanes(&self) -> Vec<Lane> {
1216 handles(&self.lanes)
1217 }
1218
1219 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1220 /// for every `ord` below it, and none at or above it.
1221 pub fn lane_count(&self, kind: LaneKind) -> usize {
1222 self.lanes.iter().filter(|l| l.kind == kind).count()
1223 }
1224
1225 /// Appends an empty lane of `kind` and hands back its handle. One undo
1226 /// step, because the lane list is state a front-end shows: an added lane
1227 /// that could not be taken back would be the one edit with no way out.
1228 /// Nothing plays differently until something is placed on it.
1229 ///
1230 /// An empty lane is a lane like any other -- so is a whole project of them
1231 /// ([`Project::from_parts`]); nothing plays until something is placed.
1232 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1233 self.snapshot();
1234 self.lanes.push(LaneData::new(kind, Vec::new()));
1235 Lane::new(kind, self.lane_count(kind) - 1)
1236 }
1237
1238 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1239 /// one undo step like it, which restores the lane where it stood.
1240 ///
1241 /// Refused, changing nothing, while the lane holds anything: the refusal
1242 /// names the clips (file and first frame), because a track removal that
1243 /// deleted takes with it would be the one edit nobody sees coming. Refused
1244 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1245 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1246 /// kind and *skips* a kind that is not there), so a project without one
1247 /// would swallow half of every file dropped on it, silently.
1248 ///
1249 /// The lanes below it move up one `ord`, so a handle a caller was holding
1250 /// (a selection, an open card) names the lane after it from here on -- the
1251 /// one thing a front-end owes this call.
1252 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1253 let Some(i) = self.index(lane) else {
1254 return Err(format!("there is no {} to remove", lane.label()).into());
1255 };
1256 // A subtitle lane is not in that rule: nothing lands on one by itself
1257 // -- a project starts without any and one is added when a caption is --
1258 // so the last of them comes off like any other empty track.
1259 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1260 return Err(format!(
1261 "{} is the only {} track: every import lands on it",
1262 lane.label(),
1263 match lane.kind {
1264 LaneKind::Video => "video",
1265 LaneKind::Audio => "audio",
1266 // Unreachable while the guard above lets the last subtitle
1267 // lane go, and its own word here so the sentence stays true
1268 // if that rule is ever relaxed.
1269 LaneKind::Subtitle => "subtitle",
1270 }
1271 )
1272 .into());
1273 }
1274 if !self.lanes[i].subs.is_empty() {
1275 // Three names and a count, exactly as the clips below get: the way
1276 // out of the refusal is the drag, so the words say so.
1277 let named: Vec<String> = self.lanes[i]
1278 .subs
1279 .iter()
1280 .take(3)
1281 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1282 .collect();
1283 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1284 0 => String::new(),
1285 n => format!(" and {n} more"),
1286 };
1287 return Err(format!(
1288 "{} still holds {}{rest}: delete those captions (or drag them to \
1289 another track) first",
1290 lane.label(),
1291 named.join(", ")
1292 )
1293 .into());
1294 }
1295 let clips = &self.lanes[i].clips;
1296 if !clips.is_empty() {
1297 // Three names and a count: a lane can hold forty clips and a
1298 // refusal nobody reads to the end says nothing at all.
1299 let named: Vec<String> = clips
1300 .iter()
1301 .take(3)
1302 .map(|c| {
1303 let name = self.sources.get(c.source).map_or_else(
1304 || format!("source {}", c.source),
1305 |s| s.path.display().to_string(),
1306 );
1307 format!("{name} at frame {}", c.start)
1308 })
1309 .collect();
1310 let rest = match clips.len().saturating_sub(named.len()) {
1311 0 => String::new(),
1312 n => format!(" and {n} more"),
1313 };
1314 return Err(format!(
1315 "{} still holds {}{rest}: delete those clips (or drag them to \
1316 another track) first",
1317 lane.label(),
1318 named.join(", ")
1319 )
1320 .into());
1321 }
1322 self.snapshot();
1323 self.lanes.remove(i);
1324 Ok(())
1325 }
1326
1327 /// Moves `lane` to display position `to` -- an index into
1328 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1329 /// the handle it answers to from now on. `None`, changing nothing and
1330 /// snapshotting nothing, for a lane that is not there, a position that is
1331 /// not, and a lane already standing in it.
1332 ///
1333 /// The whole track travels: its clips, its gain, its kind. Nothing is
1334 /// remapped, so no take changes lane and no group is broken -- this is the
1335 /// *order* of the lanes and nothing else, which is why one call is one undo
1336 /// step like an add or a removal.
1337 ///
1338 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1339 /// last video lane covering a frame, so moving one video lane past another
1340 /// changes which picture wins, in the preview and in an export alike. The
1341 /// audio lanes are summed and their sum does not care about order, so an
1342 /// audio track moved among the video ones is a rearrangement of the screen
1343 /// alone.
1344 ///
1345 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1346 /// position among the lanes of that kind), so a lane that crosses one of
1347 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1348 /// `V1`, clips and all -- while one that crosses only lanes of the other
1349 /// kind keeps its name. That is the returned handle: unchanged means every
1350 /// handle a caller holds still names the track it named before.
1351 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1352 let i = self.index(lane)?;
1353 if to >= self.lanes.len() || to == i {
1354 return None;
1355 }
1356 self.snapshot();
1357 let data = self.lanes.remove(i);
1358 self.lanes.insert(to, data);
1359 Some(handles(&self.lanes)[to])
1360 }
1361
1362 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1363 /// not there. The one place a handle becomes a position.
1364 fn index(&self, lane: Lane) -> Option<usize> {
1365 self.lanes
1366 .iter()
1367 .enumerate()
1368 .filter(|(_, l)| l.kind == lane.kind)
1369 .map(|(i, _)| i)
1370 .nth(lane.ord)
1371 }
1372
1373 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1374 let i = self.index(lane)?;
1375 Some(&mut self.lanes[i].clips)
1376 }
1377
1378 /// The files the clips index into, in import order; index 0 is the file the
1379 /// project was opened with.
1380 pub fn sources(&self) -> &[Source] {
1381 &self.sources
1382 }
1383
1384 /// The same list in the `(path, stream)` shape the audio engine indexes
1385 /// into -- [`crate::AudioSession::open_multi_streams`] and
1386 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1387 /// was placed with is the stream that plays *and* the stream that exports.
1388 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1389 self.sources
1390 .iter()
1391 .map(|s| (s.path.clone(), s.audio_stream))
1392 .collect()
1393 }
1394
1395 /// Index for `path` played on `audio_stream`, appending it if it is new.
1396 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1397 /// by two paths imports once and two streams of one file are two sources.
1398 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1399 /// no history: a source entry alone changes nothing playable.
1400 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1401 let source = Source::new(path, audio_stream);
1402 match self.sources.iter().position(|s| *s == source) {
1403 Some(idx) => idx,
1404 None => {
1405 self.sources.push(source);
1406 self.sources.len() - 1
1407 }
1408 }
1409 }
1410
1411 /// Append a whole-file clip of `source` to the end of every *media* lane,
1412 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1413 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1414 /// come in through [`Project::add_subtitles`], which is the palette.
1415 ///
1416 /// One history snapshot, so an import is one undo step, and undoing it
1417 /// leaves the (harmless) source entry behind, because indexes are forever.
1418 /// Refused for an unknown source index.
1419 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1420 if source >= self.sources.len() {
1421 return false;
1422 }
1423 self.snapshot();
1424 let start = self.timeline_frames();
1425 let clip = Clip {
1426 fade_in: 0,
1427 fade_out: 0,
1428 transition_out: 0,
1429 visualizer: 0,
1430 viz_paint: 0,
1431 start,
1432 in_frame: 0,
1433 out_frame: frame_count.max(1),
1434 source,
1435 link: Some(self.new_link()),
1436 eq: None,
1437 color: None,
1438 transform: None,
1439 fit: FitPolicy::default(),
1440 speed: Speed::NORMAL,
1441 };
1442 for data in self
1443 .lanes
1444 .iter_mut()
1445 .filter(|l| l.kind != LaneKind::Subtitle)
1446 {
1447 data.clips.push(clip);
1448 }
1449 true
1450 }
1451
1452 /// Drops a source entry -- the file a library row *is* -- and renumbers
1453 /// every clip that indexed past it, which is why this is more than a
1454 /// `Vec::remove`.
1455 ///
1456 /// Refused, changing nothing, while any clip still plays from it: the
1457 /// refusal names the lanes and how many clips each holds, so a caller can
1458 /// say what has to be deleted first. The *last* entry goes like any other
1459 /// -- a project may name no file at all, which is an empty library over an
1460 /// empty timeline (nothing can play, since a clip would have refused the
1461 /// removal). What a front-end does with that is its own decision: `edith`'s
1462 /// window goes back to the empty state it launches in, and
1463 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1464 /// refuses to write a project that names nothing, because no such file
1465 /// could be opened again.
1466 ///
1467 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1468 /// source index of its own -- a clipboard, which is the one thing outside
1469 /// this type that does -- has to fix it up or drop it, or a paste plays a
1470 /// different file. [`PlaybackSession::remove_source`] hands back the index
1471 /// that went for exactly that.
1472 ///
1473 /// corner-cut: this retires the undo stack. `history` holds the lanes, the
1474 /// subtitle palette and the project's own settings -- no source list -- so a
1475 /// snapshot older than the removal can name the very source being removed
1476 /// (delete a file's clips, then remove the file) and restoring it would
1477 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1478 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1479 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1480 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1481 /// exists) currently rules out.
1482 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1483 let Some(source) = self.sources.get(idx) else {
1484 return Err(format!("there is no source {idx} to remove").into());
1485 };
1486 let name = source.path.display().to_string();
1487 let used: Vec<String> = handles(&self.lanes)
1488 .into_iter()
1489 .zip(&self.lanes)
1490 .filter_map(|(lane, data)| {
1491 match data.clips.iter().filter(|c| c.source == idx).count() {
1492 0 => None,
1493 1 => Some(format!("{} (1 clip)", lane.label())),
1494 n => Some(format!("{} ({n} clips)", lane.label())),
1495 }
1496 })
1497 .collect();
1498 if !used.is_empty() {
1499 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1500 }
1501 self.sources.remove(idx);
1502 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1503 if c.source > idx {
1504 c.source -= 1;
1505 }
1506 }
1507 self.history.clear();
1508 Ok(())
1509 }
1510
1511 /// The sources a clip actually names, with the clips reindexed onto them
1512 /// -- what a save writes. Indexes are forever *inside* a session (see
1513 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1514 /// entry behind; writing that orphan to a project file would let a file
1515 /// nothing plays refuse a future load. New indexes are assigned in order of
1516 /// first use -- lane by lane, in display order -- so the same project always
1517 /// emits the same bytes.
1518 ///
1519 /// Every lane comes out, in display order and with its kind: that is what a
1520 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1521 /// takes back.
1522 ///
1523 /// The equalizer and colour tables are pruned the same way and for the same
1524 /// reason: an undone [`set_eq`](Project::set_eq) or
1525 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1526 /// and this is the one moment they can go -- the indexes that survive it are
1527 /// only the ones a clip names.
1528 ///
1529 /// One exception, and it is the emptied timeline's: a project no clip plays
1530 /// from still keeps its first source, if it has one. A file is what a
1531 /// reopened project scaffolds itself from -- the frame rate is written
1532 /// nowhere else -- so a save that pruned the last of them would write a
1533 /// project that cannot be loaded back at all.
1534 ///
1535 /// What comes out is *not* ordered by anything a reader may assume: first
1536 /// use, lane by lane, means the entry at index 0 can be a still or a song
1537 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1538 /// picks its rate and its audio reference by what a source *is*, never by
1539 /// where it sits.
1540 pub fn without_orphan_sources(&self) -> Parts {
1541 let mut moved = vec![None; self.sources.len()];
1542 let mut sources = Vec::new();
1543 let mut moved_eq = vec![None; self.eq.len()];
1544 let mut eq = Vec::new();
1545 let mut moved_color = vec![None; self.color.len()];
1546 let mut color = Vec::new();
1547 let mut moved_transform = vec![None; self.transform.len()];
1548 let mut transform = Vec::new();
1549 let mut lanes = self.lanes.clone();
1550 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1551 let old = c.source;
1552 c.source = match moved[old] {
1553 Some(new) => new,
1554 None => {
1555 sources.push(self.sources[old].clone());
1556 moved[old] = Some(sources.len() - 1);
1557 sources.len() - 1
1558 }
1559 };
1560 if let Some(old) = c.eq.map(usize::from) {
1561 c.eq = Some(match moved_eq[old] {
1562 Some(new) => new,
1563 None => {
1564 eq.push(self.eq[old].clone());
1565 let new = (eq.len() - 1) as u16;
1566 moved_eq[old] = Some(new);
1567 new
1568 }
1569 });
1570 }
1571 if let Some(old) = c.color.map(usize::from) {
1572 c.color = Some(match moved_color[old] {
1573 Some(new) => new,
1574 None => {
1575 color.push(self.color[old]);
1576 let new = (color.len() - 1) as u16;
1577 moved_color[old] = Some(new);
1578 new
1579 }
1580 });
1581 }
1582 if let Some(old) = c.transform.map(usize::from) {
1583 c.transform = Some(match moved_transform[old] {
1584 Some(new) => new,
1585 None => {
1586 transform.push(self.transform[old]);
1587 let new = (transform.len() - 1) as u16;
1588 moved_transform[old] = Some(new);
1589 new
1590 }
1591 });
1592 }
1593 }
1594 if sources.is_empty() {
1595 sources.extend(self.sources.first().cloned());
1596 }
1597 (
1598 sources,
1599 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1600 // comes out for one is an empty list, and its *place* in the display
1601 // order is what a save writes it for. What is on it travels beside
1602 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1603 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1604 eq,
1605 color,
1606 transform,
1607 )
1608 }
1609
1610 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1611 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1612 /// track moves by it, which is what makes it a different control from a
1613 /// clip's equalizer (one frequency range of one take) and from the master
1614 /// volume (what this machine monitors at, which no file carries).
1615 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1616 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1617 }
1618
1619 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1620 /// One undo step like every other edit -- it is in the lane list, so an
1621 /// undo restores it with the rest. `false`, and no history, for a lane that
1622 /// is not there, for a value that is not finite, and for one already set.
1623 ///
1624 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1625 /// a value nobody reads: words have no loudness, so a slider that appeared
1626 /// to move one would be a control with no effect. (A video lane's gain is
1627 /// meaningless in the same way but is kept settable: it is the pair `A1`
1628 /// carries for a take, and mixing reads it off the audio lane alone.)
1629 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1630 let Some(i) = self.index(lane) else {
1631 return false;
1632 };
1633 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1634 return false;
1635 }
1636 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1637 if self.lanes[i].gain_db == db {
1638 return false;
1639 }
1640 self.snapshot();
1641 self.lanes[i].gain_db = db;
1642 true
1643 }
1644
1645 /// Every lane's volume in dB, in display order -- what a save writes,
1646 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1647 ///
1648 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1649 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1650 /// one): a save zips the two lists, so a lane that is in one and not the
1651 /// other would hand every track below it the volume of the track above.
1652 pub fn lane_gains(&self) -> Vec<f32> {
1653 self.lanes.iter().map(|l| l.gain_db).collect()
1654 }
1655
1656 /// What is placed on every lane, in display order and in step with
1657 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1658 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1659 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1660 ///
1661 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1662 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1663 /// clip's source there is no orphan to prune and no index to move.
1664 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1665 self.lanes.iter().map(|l| l.subs.clone()).collect()
1666 }
1667
1668 /// The placements a *load* puts back, one list per lane in display order --
1669 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1670 /// same reason. Called *after*
1671 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1672 /// names.
1673 ///
1674 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1675 /// like it, by name and in release, because it is the same untrusted file:
1676 /// a placement on a lane that is not a subtitle lane, an empty span or an
1677 /// empty window, a track the palette does not have, a span running past the
1678 /// last frame there is, and a lane that is out of order or overlaps itself
1679 /// ([`place_sub`] refuses every one of those on the live timeline).
1680 ///
1681 /// [`place_sub`]: Project::place_sub
1682 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1683 let names = handles(&self.lanes);
1684 let palette = self.subtitles.len();
1685 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1686 let name = lane.label();
1687 if list.is_empty() {
1688 continue;
1689 }
1690 if data.kind != LaneKind::Subtitle {
1691 return Err(format!(
1692 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1693 subtitle track",
1694 list.len()
1695 )
1696 .into());
1697 }
1698 for s in &list {
1699 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1700 return Err(format!(
1701 "{name} caption at {} is empty: {} frames of [{}, {})",
1702 s.start, s.frames, s.in_us, s.out_us
1703 )
1704 .into());
1705 }
1706 if s.track >= palette {
1707 return Err(format!(
1708 "{name} caption at {} names subtitle track {} of {palette}",
1709 s.start, s.track
1710 )
1711 .into());
1712 }
1713 if s.start.checked_add(s.frames).is_none() {
1714 return Err(format!(
1715 "{name} caption at {} runs past the last frame there is",
1716 s.start
1717 )
1718 .into());
1719 }
1720 }
1721 if !subs_sorted_disjoint(&list) {
1722 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1723 }
1724 data.subs = list;
1725 // The counter also has to clear the ids these captions carry: this
1726 // is the door a load's placements come through, *after*
1727 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1728 // a hand-grouped caption may carry the highest id in the file.
1729 self.next_link = self.next_link.max(
1730 data.subs
1731 .iter()
1732 .filter_map(|s| s.link)
1733 .max()
1734 .map_or(0, |m| m.saturating_add(1)),
1735 );
1736 }
1737 Ok(self)
1738 }
1739
1740 /// The mix settings a *load* puts back: lane volumes in display order (a
1741 /// short list leaves the rest at unity) and the master limiter, both
1742 /// clamped as their setters clamp them.
1743 ///
1744 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1745 /// setters push an undo step, and a project that arrives one undo away from
1746 /// a state it was never in is a project whose first ctrl+z is a surprise.
1747 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1748 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1749 if db.is_finite() {
1750 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1751 }
1752 }
1753 self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db);
1754 self
1755 }
1756
1757 /// The HDR rendition a *load* puts back -- the same door
1758 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1759 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1760 self.settings.tone = preset;
1761 self
1762 }
1763
1764 /// The canvas and rate a *load* or a fresh open names -- the project
1765 /// resolution and the rate every clip is counted in. The same door
1766 /// [`with_mix`](Project::with_mix) is, and no undo step for the same
1767 /// reason: a project that arrives one undo away from a state it was never
1768 /// in is a project whose first ctrl+z is a surprise.
1769 pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self {
1770 self.settings.resolution = (width, height);
1771 self.settings.frame_rate = frame_rate;
1772 self
1773 }
1774
1775 /// The saved switches a *load* puts back: whether the picture is cut on
1776 /// the stand-ins, whether new ones are made on arrival, which encoder an
1777 /// export opens, and the rate the mix was picked to run at. The load half
1778 /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo
1779 /// step for [`with_mix`](Project::with_mix)'s reason.
1780 pub fn with_switches(
1781 mut self,
1782 proxies: bool,
1783 auto_proxies: bool,
1784 encoder_seat: crate::export::EncoderSeat,
1785 sample_rate: Option<u32>,
1786 ) -> Self {
1787 self.settings.proxies = proxies;
1788 self.settings.auto_proxies = auto_proxies;
1789 self.settings.encoder_seat = encoder_seat;
1790 self.settings.sample_rate = sample_rate;
1791 self
1792 }
1793
1794 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1795 /// project setting, not a clip's: one picture, one look
1796 /// ([`crate::tonemap::Preset`]).
1797 pub fn tone(&self) -> crate::tonemap::Preset {
1798 self.settings.tone
1799 }
1800
1801 /// Sets it. `false` for the one already in force, which is what keeps a
1802 /// re-pick of the current rendition from costing a reseek. One undo step
1803 /// like every other project-setting pick.
1804 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1805 if self.settings.tone == preset {
1806 return false;
1807 }
1808 self.snapshot();
1809 self.settings.tone = preset;
1810 true
1811 }
1812
1813 /// The subtitle tracks a *load* puts back, in the order they were saved --
1814 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1815 /// the same reason.
1816 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1817 self.subtitles = tracks;
1818 self
1819 }
1820
1821 /// What this timeline shows over the picture, in the order they were added:
1822 /// what a front-end lists and what a save writes.
1823 pub fn subtitles(&self) -> &[SubtitleTrack] {
1824 &self.subtitles
1825 }
1826
1827 /// Adds a track, unless the very same one -- same file, same track number
1828 /// inside it -- is already on the list. `false` for that repeat: importing
1829 /// the same `.srt` twice is one subtitle track, not two identical ones.
1830 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1831 if self
1832 .subtitles
1833 .iter()
1834 .any(|t| t.path == track.path && t.track == track.track)
1835 {
1836 return false;
1837 }
1838 self.subtitles.push(track.clone());
1839 true
1840 }
1841
1842 /// Takes the track at `idx` off the list -- what a row's own remove goes
1843 /// through, so whatever an import added can be taken back out. Refused by
1844 /// name for a row this project does not have, rather than a silent no-op:
1845 /// a front-end holding a stale index has picked the wrong row and needs to
1846 /// hear it.
1847 ///
1848 /// Every index past `idx` moves down by one, as [`remove_source`](
1849 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1850 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1851 /// it, or it names a different track afterwards. The placements on the
1852 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1853 /// index into this very list, so every one past `idx` is walked down with
1854 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1855 /// for its clips, for its reason.
1856 ///
1857 /// Refused, changing nothing, while anything placed on a subtitle lane
1858 /// plays *this* row: the placement would have to be deleted or retargeted,
1859 /// and either one is an edit nobody asked for. The refusal names the lane
1860 /// and the frame it is at, up to three of them --
1861 /// [`remove_source`](Project::remove_source) refuses the same way for the
1862 /// same silent corruption.
1863 ///
1864 /// One undo step, and the reindex with it: every placement names a track
1865 /// by index into the palette ([`crate::subtitle`]), so a removal that
1866 /// renumbers them can only come back together with the palette it took
1867 /// the row from -- which is what the history entry holds, beside the
1868 /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that
1869 /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`]
1870 /// -- the panel's own door, which reads the subtitles of a file and
1871 /// nothing else.
1872 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1873 if idx >= self.subtitles.len() {
1874 return Err(format!("there is no subtitle track {idx} to remove").into());
1875 }
1876 let placed: Vec<String> = handles(&self.lanes)
1877 .into_iter()
1878 .zip(&self.lanes)
1879 .flat_map(|(lane, data)| {
1880 data.subs
1881 .iter()
1882 .filter(move |s| s.track == idx)
1883 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1884 })
1885 .take(3)
1886 .collect();
1887 if !placed.is_empty() {
1888 return Err(format!(
1889 "{} is on the timeline ({}): delete those clips first",
1890 self.track_name(idx),
1891 placed.join(", ")
1892 )
1893 .into());
1894 }
1895 self.snapshot();
1896 self.subtitles.remove(idx);
1897 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1898 if s.track > idx {
1899 s.track -= 1;
1900 }
1901 }
1902 Ok(())
1903 }
1904
1905 /// What a refusal calls a palette row: the name the panel shows, and the
1906 /// index alone for a row that is not there.
1907 fn track_name(&self, track: usize) -> String {
1908 self.subtitles
1909 .get(track)
1910 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1911 }
1912
1913 /// The subtitle lanes in display order -- what a front-end lays out and
1914 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1915 /// [`audio_lanes`](Project::audio_lanes).
1916 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1917 self.lanes()
1918 .into_iter()
1919 .filter(|l| l.kind == LaneKind::Subtitle)
1920 .collect()
1921 }
1922
1923 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1924 /// for a subtitle track, and empty for every other lane and for one that is
1925 /// not there.
1926 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1927 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1928 }
1929
1930 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1931 /// twin, with one deliberate difference: it **refuses** an overlap instead
1932 /// of overwriting what it lands on.
1933 ///
1934 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1935 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1936 /// carries is a *window of a track* and where the hand let go, and the
1937 /// second of those is the argument. So a caller builds the placement once
1938 /// (from the palette row it dragged) and drops it at as many frames as it
1939 /// likes without rewriting the field each time.
1940 ///
1941 /// A picture placed over a picture hides it and the hidden one is still
1942 /// there to drag back out; two captions in one frame are two lines nobody
1943 /// asked to stack, and the words that lost are gone from the screen with
1944 /// nothing to show for it. So the refusal names the placement in the way,
1945 /// and the caller picks another frame or another lane -- which is what a
1946 /// second subtitle lane is for.
1947 ///
1948 /// One undo step on success, and none on any refusal: an empty window or an
1949 /// empty span, a track the palette does not have
1950 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1951 /// subtitle lane, a span that would run past the last frame there is, and
1952 /// the overlap above.
1953 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1954 if lane.kind != LaneKind::Subtitle {
1955 return Err(format!(
1956 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1957 the others",
1958 lane.label()
1959 )
1960 .into());
1961 }
1962 let Some(i) = self.index(lane) else {
1963 return Err(format!("there is no {} to place on", lane.label()).into());
1964 };
1965 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1966 return Err(format!(
1967 "that placement is empty: {} frames of [{}, {})",
1968 sub.frames, sub.in_us, sub.out_us
1969 )
1970 .into());
1971 }
1972 if sub.track >= self.subtitles.len() {
1973 return Err(format!(
1974 "it names subtitle track {} of {}",
1975 sub.track,
1976 self.subtitles.len()
1977 )
1978 .into());
1979 }
1980 // The placement belongs to no group, for [`place`]'s reason: a caption
1981 // dragged out of the palette arrives alone, and grouping it with what
1982 // is under it is a hand's decision ([`Project::group_all`]).
1983 let sub = SubClip {
1984 start: at,
1985 link: None,
1986 ..sub
1987 };
1988 if at.checked_add(sub.frames).is_none() {
1989 return Err(
1990 format!("a placement at frame {at} runs past the last frame there is").into(),
1991 );
1992 }
1993 if let Some(other) = self.lanes[i]
1994 .subs
1995 .iter()
1996 .find(|o| o.end() > sub.start && o.start < sub.end())
1997 {
1998 return Err(format!(
1999 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
2000 on another subtitle track",
2001 lane.label(),
2002 other.start,
2003 other.start,
2004 other.end()
2005 )
2006 .into());
2007 }
2008 self.snapshot();
2009 let subs = &mut self.lanes[i].subs;
2010 let idx = subs.partition_point(|o| o.start < sub.start);
2011 subs.insert(idx, sub);
2012 debug_assert!(subs_sorted_disjoint(subs));
2013 Ok(())
2014 }
2015
2016 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
2017 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
2018 /// refused an overlap where that one clamps to it, for
2019 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
2020 /// still and no picture under it that a landing would hide, so "as far as
2021 /// it goes" would silently be a frame nobody named.
2022 ///
2023 /// A caption *in* a group drags the group: one delta for every member --
2024 /// its clips and its other captions -- clamped to the room each of them
2025 /// has, exactly as a clip's drag always has. That is the point of putting
2026 /// a caption in a group: the words go where the picture goes.
2027 ///
2028 /// The window travels untouched: a caption dragged later says the same
2029 /// words later, exactly as a clip dragged later plays the same pictures
2030 /// later.
2031 ///
2032 /// One undo step on success; nothing changed and no step on a refusal --
2033 /// an index that is not there, a lane that is not a subtitle lane or is not
2034 /// there, and (for a caption in no group) an overlap. A drop that changes
2035 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
2036 /// up and put it back has done nothing wrong, and a front-end showing every
2037 /// `Err` would say so.
2038 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
2039 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
2040 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
2041 };
2042 if to.kind != LaneKind::Subtitle {
2043 return Err(format!(
2044 "{} is not a subtitle track: a caption cannot play on it",
2045 to.label()
2046 )
2047 .into());
2048 }
2049 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
2050 return Err(format!("there is no {} to move onto", to.label()).into());
2051 };
2052 if (here, start) == (dest, sub.start) {
2053 // A pick-up-put-back: the drag ended where it began, which is not a
2054 // mistake to name -- `Ok`, and no undo step, because nothing
2055 // changed. A refusal here would toast a hand that did nothing.
2056 return Ok(());
2057 }
2058 if start.checked_add(sub.frames).is_none() {
2059 return Err(
2060 format!("a placement at frame {start} runs past the last frame there is").into(),
2061 );
2062 }
2063 // A grouped caption carries its group, clamped to the room the whole
2064 // group has rather than refused ([`Project::move_room]) -- one drag, one
2065 // delta, one undo step.
2066 let members = self.group_of(from, idx).expect("the subtitle was found");
2067 if !members.alone() {
2068 if members
2069 .subs
2070 .iter()
2071 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
2072 {
2073 return Err(format!(
2074 "a group is one caption per track: {} already carries this group",
2075 to.label()
2076 )
2077 .into());
2078 }
2079 let want = i64::from(start) - i64::from(sub.start);
2080 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
2081 return Err(format!(
2082 "another placement already covers those frames on {}",
2083 to.label()
2084 )
2085 .into());
2086 };
2087 let delta = want.clamp(lo, hi);
2088 self.snapshot();
2089 for &(l, i) in &members.clips {
2090 let c = &mut self.lanes[l].clips[i];
2091 c.start = (i64::from(c.start) + delta) as u32;
2092 }
2093 for &(l, i) in &members.subs {
2094 let s = &mut self.lanes[l].subs[i];
2095 s.start = (i64::from(s.start) + delta) as u32;
2096 }
2097 let moved = self.lanes[here].subs.remove(idx);
2098 let subs = &mut self.lanes[dest].subs;
2099 let at = subs.partition_point(|o| o.start < moved.start);
2100 subs.insert(at, moved);
2101 debug_assert!(subs_sorted_disjoint(subs));
2102 debug_assert!(
2103 members
2104 .clips
2105 .iter()
2106 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))
2107 );
2108 return Ok(());
2109 }
2110 let moved = SubClip { start, ..sub };
2111 if let Some(other) = self.lanes[dest]
2112 .subs
2113 .iter()
2114 .enumerate()
2115 .find(|&(j, o)| {
2116 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
2117 })
2118 .map(|(_, o)| *o)
2119 {
2120 return Err(format!(
2121 "the {} subtitle at frame {} already covers [{}, {})",
2122 to.label(),
2123 other.start,
2124 other.start,
2125 other.end()
2126 )
2127 .into());
2128 }
2129 self.snapshot();
2130 self.lanes[here].subs.remove(idx);
2131 let subs = &mut self.lanes[dest].subs;
2132 let at = subs.partition_point(|o| o.start < moved.start);
2133 subs.insert(at, moved);
2134 debug_assert!(subs_sorted_disjoint(subs));
2135 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
2136 Ok(())
2137 }
2138
2139 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
2140 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
2141 /// pulling an edge past what is legal means "as far as it goes".
2142 ///
2143 /// The window follows the edge, in the seconds the frames are worth at
2144 /// `fps`: a head pulled in starts the caption later *in its track* (the
2145 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
2146 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
2147 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
2148 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
2149 /// needed here and nowhere else in this file, because a trim is the only
2150 /// edit that changes a *duration*.
2151 ///
2152 /// The walls: one frame always survives, an edge never crosses the
2153 /// neighbouring subtitle on its own lane, a head never walks back past the
2154 /// track's own start (`in_us` of 0), and a tail never runs past the last
2155 /// cue the track has -- which is the source length a media trim needs a
2156 /// caller's table for, and which this one can simply read.
2157 ///
2158 /// `Err`, with nothing changed and no undo step, for an index that is not
2159 /// there and an unusable `fps`. An edge that ends up where it already was
2160 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2161 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2162 /// reason: a drag that stops at a wall is not a mistake to report.
2163 pub fn trim_sub(
2164 &mut self,
2165 lane: Lane,
2166 idx: usize,
2167 edge: Edge,
2168 to: u32,
2169 fps: f64,
2170 ) -> crate::Result<()> {
2171 if !(fps.is_finite() && fps > 0.0) {
2172 return Err(format!("{fps} is not a frame rate to trim against").into());
2173 }
2174 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2175 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2176 };
2177 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2178 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2179 };
2180 let to = to.clamp(lo, hi);
2181 let at = match edge {
2182 Edge::Start => sub.start,
2183 Edge::End => sub.end(),
2184 };
2185 if to == at {
2186 // The edge is where it was asked to go -- either the hand did not
2187 // move it, or the clamp above stopped it at a wall it was already
2188 // standing against. Both are a drag that changed nothing: `Ok`, no
2189 // undo step, and no toast for a box that simply stopped moving.
2190 return Ok(());
2191 }
2192 self.snapshot();
2193 let members = self.group_of(lane, idx).expect("the subtitle was found");
2194 let i = self.index(lane).expect("the subtitle was found on it");
2195 let s = &mut self.lanes[i].subs[idx];
2196 match edge {
2197 // The words that stay are the words that were there, so the window
2198 // moves with the head -- a trim, not a slip.
2199 Edge::Start => {
2200 // Clamped to a window that is still a window: the walls above
2201 // are frames and the rounding between the two clocks is not
2202 // exact, and neither is a caller's hand-built placement.
2203 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2204 .clamp(0, s.out_us - 1);
2205 s.frames = s.end() - to;
2206 s.start = to;
2207 }
2208 Edge::End => {
2209 s.out_us =
2210 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2211 s.frames = to - s.start;
2212 }
2213 }
2214 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2215 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2216 // A caption in a group drags its group's edge with it, exactly as a
2217 // clip's trim does: one delta, each member clamped to its own room.
2218 // No source table to grow by, which only tightens how far a member may
2219 // follow -- never whether it may.
2220 self.follow_group(
2221 &members,
2222 &(i, idx),
2223 edge,
2224 i64::from(to) - i64::from(at),
2225 &[],
2226 );
2227 Ok(())
2228 }
2229
2230 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2231 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2232 /// drawing the box during a drag asks. `None` for an index that is not
2233 /// there.
2234 pub fn trim_sub_room(
2235 &self,
2236 lane: Lane,
2237 idx: usize,
2238 edge: Edge,
2239 fps: f64,
2240 ) -> Option<(u32, u32)> {
2241 let subs = self.sub_lane(lane);
2242 let s = *subs.get(idx)?;
2243 // How many timeline frames a stretch of the track is worth, which is
2244 // what turns its two walls -- its own start, and its last cue -- into
2245 // frames. A rate that is not a rate leaves the window where it is.
2246 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2247 true => ((us as f64) * fps / 1e6)
2248 .round()
2249 .max(0.0)
2250 .min(f64::from(u32::MAX)) as u32,
2251 false => 0,
2252 };
2253 Some(match edge {
2254 Edge::Start => (
2255 s.start
2256 .saturating_sub(frames_of(s.in_us))
2257 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2258 s.end() - 1,
2259 ),
2260 Edge::End => {
2261 // Out to the end of the track it reads, and never over the
2262 // subtitle behind it. A track the palette no longer has (or one
2263 // with no cues at all) may not grow, exactly as a source with no
2264 // entry in a media trim's table may not.
2265 let track_end = self
2266 .subtitles
2267 .get(s.track)
2268 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2269 .unwrap_or(s.out_us);
2270 (
2271 s.start + 1,
2272 s.start
2273 .saturating_add(frames_of(track_end - s.in_us).max(1))
2274 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2275 )
2276 }
2277 })
2278 }
2279
2280 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2281 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2282 /// `false` for an index that is not there (which a lane that is not a
2283 /// subtitle lane always is).
2284 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2285 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2286 return false;
2287 };
2288 self.snapshot();
2289 self.lanes[i].subs.remove(idx);
2290 true
2291 }
2292
2293 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2294 /// window of its track, clipped to that window and shifted to where the
2295 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2296 /// carried through the picture's spans -- this is its twin for a track that
2297 /// is placed on a lane of its own, and it is what a preview draws and what
2298 /// an export of the lane would write.
2299 ///
2300 /// Cut, not stretched: a cue half inside the window keeps the half that is
2301 /// inside, and a cue wholly outside it is gone -- the same rule the media
2302 /// spans follow. `fps` is the timeline's rate, needed here because a
2303 /// placement's *position* is in frames while its words are in microseconds.
2304 ///
2305 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2306 /// of their cues, no file opened), which is how a front-end asks it.
2307 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2308 if !(fps.is_finite() && fps > 0.0) {
2309 return Vec::new();
2310 }
2311 let mut out = Vec::new();
2312 for s in self.sub_lane(lane) {
2313 let Some(track) = self.subtitles.get(s.track) else {
2314 // A placement whose track was taken off the palette
2315 // ([`Project::remove_subtitles`]) shows nothing rather than
2316 // showing another track's words.
2317 continue;
2318 };
2319 // Where the placement's own first microsecond lands on the
2320 // timeline, and how many microseconds of timeline one microsecond
2321 // of the window is worth: the placement's own proportion, which a
2322 // group's re-rate changes (the frames compress, the window does
2323 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2324 // every cue lands where it always did; at 2x the words cross the
2325 // screen in half the time, cue for cue.
2326 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2327 let onto = |t: i64| {
2328 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2329 };
2330 for cue in &track.cues {
2331 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2332 if b <= a {
2333 continue; // wholly outside the window this placement keeps
2334 }
2335 out.push(SubtitleCue {
2336 start_us: onto(a),
2337 end_us: onto(b),
2338 text: cue.text.clone(),
2339 image: cue.image.clone(),
2340 });
2341 }
2342 }
2343 // The placements come in timeline order, but two lanes' worth (or a
2344 // track whose cues a window reordered) do not.
2345 out.sort_by_key(|cue| cue.start_us);
2346 out
2347 }
2348
2349 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2350 /// lanes is multiplied by on its way into the mix: the same lanes in the
2351 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2352 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2353 /// the bit-exact path.
2354 pub fn audio_gains(&self) -> Vec<f32> {
2355 self.audio_lanes()
2356 .into_iter()
2357 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2358 .collect()
2359 }
2360
2361 /// The master limiter the mix is summed through. A project setting, not a
2362 /// clip's and not a lane's: there is one mix.
2363 pub fn limiter(&self) -> Limiter {
2364 self.settings.limiter
2365 }
2366
2367 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2368 /// for a setting already in force. One undo step like every other
2369 /// project-setting pick.
2370 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2371 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2372 if self.settings.limiter == limiter {
2373 return false;
2374 }
2375 self.snapshot();
2376 self.settings.limiter = limiter;
2377 true
2378 }
2379
2380 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2381 /// plays flat (and for an index that is not there) -- what a feeder and an
2382 /// export ask before they build an [`crate::eq::EqState`].
2383 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2384 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2385 }
2386
2387 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2388 /// take them off. One undo step, like every other edit. `false` -- and no
2389 /// history -- for an index that is not there and for params holding a value
2390 /// that is not finite, which is the one thing the file format could not
2391 /// write and read back.
2392 ///
2393 /// Settings equal to ones already in the table share their entry, so a
2394 /// project that puts the same curve on twenty clips writes it once.
2395 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2396 if idx >= self.lane(lane).len() {
2397 return false;
2398 }
2399 let slot = match params {
2400 None => None,
2401 Some(params) => {
2402 if !finite(&params) {
2403 return false;
2404 }
2405 Some(match self.eq.iter().position(|p| *p == params) {
2406 Some(at) => at as u16,
2407 // corner-cut: the table is append-only within a session (see
2408 // the module docs) and `Clip::eq` is a u16, so the 65535th
2409 // *distinct* setting of one session is refused rather than
2410 // silently aliased. Upgrade path if a UI ever drags a slider
2411 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2412 // snapshot the table into the history and compact it here.
2413 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2414 None => {
2415 self.eq.push(params);
2416 (self.eq.len() - 1) as u16
2417 }
2418 })
2419 }
2420 };
2421 self.snapshot();
2422 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2423 true
2424 }
2425
2426 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2427 /// ungraded (and for an index that is not there) -- what the renderer and
2428 /// the export ask before they call [`crate::color::apply_yuv`].
2429 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2430 self.color
2431 .get(usize::from(self.lane(lane).get(idx)?.color?))
2432 }
2433
2434 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2435 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2436 /// (and no history) for an index that is not there or a value that is not
2437 /// finite, and equal settings share a table entry.
2438 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2439 self.write_color(lane, idx, params, true)
2440 }
2441
2442 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2443 /// one pointer drag, whose first write (a plain `set_color`) already took the
2444 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2445 /// not one per pixel -- and undoing it lands where the hand picked it up.
2446 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2447 self.write_color(lane, idx, params, false)
2448 }
2449
2450 fn write_color(
2451 &mut self,
2452 lane: Lane,
2453 idx: usize,
2454 params: Option<ColorParams>,
2455 snapshot: bool,
2456 ) -> bool {
2457 if idx >= self.lane(lane).len() {
2458 return false;
2459 }
2460 let slot = match params {
2461 None => None,
2462 Some(params) => {
2463 if !color_finite(&params) {
2464 return false;
2465 }
2466 Some(match self.color.iter().position(|p| *p == params) {
2467 Some(at) => at as u16,
2468 // corner-cut: the 65535th *distinct* grade of one session is
2469 // refused rather than silently aliased, exactly as `set_eq`
2470 // refuses the 65535th curve; same upgrade path.
2471 None if self.color.len() >= usize::from(u16::MAX) => return false,
2472 None => {
2473 self.color.push(params);
2474 (self.color.len() - 1) as u16
2475 }
2476 })
2477 }
2478 };
2479 if snapshot {
2480 self.snapshot();
2481 }
2482 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2483 true
2484 }
2485
2486 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2487 /// policy's own placement (and for an index that is not there) -- what the
2488 /// renderer and the export ask before they place its picture.
2489 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2490 self.transform
2491 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2492 }
2493
2494 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2495 /// step, `false` (and no history) for an index that is not there or a
2496 /// value that is not finite, and equal settings share a table entry.
2497 pub fn set_transform(
2498 &mut self,
2499 lane: Lane,
2500 idx: usize,
2501 params: Option<TransformParams>,
2502 ) -> bool {
2503 self.write_transform(lane, idx, params, true)
2504 }
2505
2506 /// [`set_transform`](Self::set_transform) without the undo step, for
2507 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2508 /// one drag on a position/scale/rotate/crop control are one undo, not one
2509 /// per pixel.
2510 pub fn set_transform_live(
2511 &mut self,
2512 lane: Lane,
2513 idx: usize,
2514 params: Option<TransformParams>,
2515 ) -> bool {
2516 self.write_transform(lane, idx, params, false)
2517 }
2518
2519 fn write_transform(
2520 &mut self,
2521 lane: Lane,
2522 idx: usize,
2523 params: Option<TransformParams>,
2524 snapshot: bool,
2525 ) -> bool {
2526 if idx >= self.lane(lane).len() {
2527 return false;
2528 }
2529 let slot = match params {
2530 None => None,
2531 Some(params) => {
2532 if !transform_finite(&params) {
2533 return false;
2534 }
2535 Some(match self.transform.iter().position(|p| *p == params) {
2536 Some(at) => at as u16,
2537 // corner-cut: the 65535th *distinct* transform of one
2538 // session is refused rather than silently aliased,
2539 // exactly as `write_color` refuses the 65535th grade;
2540 // same upgrade path.
2541 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2542 None => {
2543 self.transform.push(params);
2544 (self.transform.len() - 1) as u16
2545 }
2546 })
2547 }
2548 };
2549 if snapshot {
2550 self.snapshot();
2551 }
2552 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2553 true
2554 }
2555
2556 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2557 /// index that is not there, which is what every clip starts at anyway.
2558 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2559 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2560 }
2561
2562 /// Sets it, for the clip **and its whole group**: a link is one span on
2563 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2564 /// from its sound would be a group no save could load. One snapshot, so the
2565 /// group's change is one [`Project::undo`].
2566 ///
2567 /// The source range is untouched -- a speed says how many timeline frames
2568 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2569 /// split still address the file afterwards.
2570 ///
2571 /// Refused, changing nothing and costing no undo step, when the clip would
2572 /// grow into the one after it on its own lane: slowing a clip down makes it
2573 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2574 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2575 /// something a user can go and fix. Also for an index that is not there.
2576 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2577 self.write_speed(lane, idx, speed, true)
2578 }
2579
2580 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2581 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2582 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2583 /// not one per rate it passed through -- exactly as
2584 /// [`set_color_live`](Self::set_color_live) is for a slider.
2585 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2586 self.write_speed(lane, idx, speed, false)
2587 }
2588
2589 fn write_speed(
2590 &mut self,
2591 lane: Lane,
2592 idx: usize,
2593 speed: Speed,
2594 snapshot: bool,
2595 ) -> crate::Result<()> {
2596 let Some(members) = self.group_of(lane, idx) else {
2597 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2598 };
2599 let labels = handles(&self.lanes);
2600 // The clip the hand is holding is the group's clock: everything else
2601 // in the group, caption members included, re-times by the ratio its new
2602 // rate gives its own frames. The clips take the rate itself; a caption
2603 // has none, so it takes the *ratio* -- its span on the timeline
2604 // compresses or stretches about the held clip's head, while the words
2605 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2606 // timeline moves, the track does not).
2607 let Some(held) = self.lane(lane).get(idx).copied() else {
2608 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2609 };
2610 // The same per-member piece `speeded_playhead` builds for this op,
2611 // asked here instead of read there -- a caption's length comes from
2612 // the map's own ends (`end - start`), never `round(len * ratio)`
2613 // separately, which is what let the two answers drift apart by a
2614 // frame.
2615 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2616 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2617 let retimed = |s: SubClip| {
2618 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2619 let start = map.apply(s.start);
2620 let end = map.apply(s.end()).max(start.saturating_add(1));
2621 SubClip {
2622 start,
2623 frames: end - start,
2624 ..s
2625 }
2626 };
2627 for &(l, i) in &members.clips {
2628 let clips = &self.lanes[l].clips;
2629 let mut moved = clips[i];
2630 moved.speed = speed;
2631 if let Some(next) = clips.get(i + 1)
2632 && moved.end() > next.start
2633 {
2634 let name = labels[l].label();
2635 return Err(format!(
2636 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2637 move it along, or trim this one first",
2638 moved.end(),
2639 next.start
2640 )
2641 .into());
2642 }
2643 }
2644 // ...and the captions, against their own lanes' captions: a stretch
2645 // that runs one into its neighbour is refused for the clip arm's
2646 // reason -- a lane may not overlap itself -- and by name like it.
2647 let subs: Vec<(usize, usize, SubClip)> = members
2648 .subs
2649 .iter()
2650 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2651 .collect();
2652 for &(l, i, moved) in &subs {
2653 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2654 if j != i && moved.start < other.end() && other.start < moved.end() {
2655 return Err(format!(
2656 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2657 starts at {}: move it along, or trim this one first",
2658 labels[l].label(),
2659 self.lanes[l].subs[i].start,
2660 moved.end(),
2661 other.start
2662 )
2663 .into());
2664 }
2665 }
2666 }
2667 if snapshot {
2668 self.snapshot();
2669 }
2670 for (l, i) in members.clips {
2671 self.lanes[l].clips[i].speed = speed;
2672 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2673 }
2674 for (l, i, moved) in subs {
2675 self.lanes[l].subs[i] = moved;
2676 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2677 }
2678 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2679 Ok(())
2680 }
2681
2682 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2683 /// playhead standing at `at` -- read off the geometry **before** the
2684 /// write, because the old ends are gone after it. The question a card
2685 /// asks as its bar moves: the picture under the cursor has to stay the
2686 /// picture under the cursor, or the scene changes with the rate.
2687 ///
2688 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2689 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2690 /// a clip member keeps its own start and re-fits its length at the new
2691 /// rate -- its **old** rate against the new one, which is what the bar's
2692 /// live samples ask about as much as a first press does; a caption
2693 /// member scales about the held clip's start by the held clip's own
2694 /// proportion; and a playhead outside every member's old extent stays
2695 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2696 /// (or the room a stretch takes) absorbs the difference, not the
2697 /// playhead. `None` for an index that is not there.
2698 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2699 let members = self.group_of(lane, idx)?;
2700 let held = self.lane(lane).get(idx).copied()?;
2701 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2702 for &(l, i) in members.clips.iter().chain(&members.subs) {
2703 let (span, map) = match self.lanes[l]
2704 .clips
2705 .get(i)
2706 .filter(|_| members.clips.contains(&(l, i)))
2707 {
2708 // The clip's own span, re-fitted at its own old rate: one
2709 // piece of the map, anchored where the clip itself is. The
2710 // new length is the same *source* frames at the new rate --
2711 // len divided by it, never multiplied.
2712 Some(c) => (
2713 (c.start, c.start + c.frames()),
2714 TimelineMap::piece(
2715 (c.start, c.start + c.frames()),
2716 (c.start, c.start + (c.len() as f64 / new).round() as u32),
2717 ),
2718 ),
2719 // The caption's span, scaled about the held clip's head by
2720 // the held clip's proportion -- the offset the group keeps.
2721 None => {
2722 let s = self.lanes[l].subs.get(i)?;
2723 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2724 (
2725 (s.start, s.end()),
2726 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2727 )
2728 }
2729 };
2730 // The piece owns only its own old span: outside it the playhead
2731 // is another member's question, or nobody's.
2732 if (span.0..span.1).contains(&at) {
2733 return Some(map.apply(at));
2734 }
2735 }
2736 Some(at)
2737 }
2738
2739 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2740 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2741 /// every clip starts at anyway.
2742 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2743 self.lane(lane)
2744 .get(idx)
2745 .map_or(FitPolicy::default(), |c| c.fit)
2746 }
2747
2748 /// Sets it. One undo step like every other edit, and `false` (with no
2749 /// history) for an index that is not there. Unlike an eq or a grade there is
2750 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2751 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2752 if idx >= self.lane(lane).len() {
2753 return false;
2754 }
2755 self.snapshot();
2756 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2757 true
2758 }
2759
2760 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
2761 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
2762 /// history) for an index that is not there.
2763 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
2764 if idx >= self.lane(lane).len() {
2765 return false;
2766 }
2767 self.snapshot();
2768 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
2769 true
2770 }
2771
2772 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
2773 /// `false` (with no history) for an index that is not there, the way every
2774 /// other setter refuses.
2775 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2776 self.write_viz_paint(lane, idx, paint, true)
2777 }
2778
2779 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
2780 /// samples *inside* one pointer drag across the colour wheel, whose first
2781 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
2782 /// rolls back to. One drag is one undo, not one per sample.
2783 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2784 self.write_viz_paint(lane, idx, paint, false)
2785 }
2786
2787 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
2788 if idx >= self.lane(lane).len() {
2789 return false;
2790 }
2791 if snapshot {
2792 self.snapshot();
2793 }
2794 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
2795 true
2796 }
2797
2798 /// Timeline frames of ramp-up from silence at the start of the clip at
2799 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2800 /// that has none.
2801 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2802 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2803 }
2804
2805 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2806 /// can shrink a clip's audible middle to nothing but never ask for more
2807 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2808 /// and `false` (no history) for an index that is not there.
2809 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2810 if idx >= self.lane(lane).len() {
2811 return false;
2812 }
2813 self.snapshot();
2814 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2815 clip.fade_in = frames.min(clip.frames());
2816 true
2817 }
2818
2819 /// Timeline frames of ramp-down to silence at the end of the clip at
2820 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2821 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2822 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2823 }
2824
2825 /// Sets it. Same promises as [`Project::set_fade_in`].
2826 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2827 if idx >= self.lane(lane).len() {
2828 return false;
2829 }
2830 self.snapshot();
2831 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2832 clip.fade_out = frames.min(clip.frames());
2833 true
2834 }
2835
2836 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2837 /// into its successor, at its own end. `0` for an index that is not
2838 /// there, same as a clip that has none.
2839 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2840 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2841 }
2842
2843 /// Sets it, clamped to the clip's own length and to how many frames its
2844 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2845 /// visible middle to nothing but never ask for more than the two clips
2846 /// between them have. `false` -- no history -- unless `lane` is video,
2847 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2848 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2849 /// them. One undo step like [`Project::set_fade_out`].
2850 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2851 if lane.kind != LaneKind::Video {
2852 return false;
2853 }
2854 let clips = self.lane(lane);
2855 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2856 return false;
2857 };
2858 if a.end() != b.start {
2859 return false;
2860 }
2861 let cap = a.frames().min(b.frames());
2862 self.snapshot();
2863 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2864 true
2865 }
2866
2867 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2868 /// after it, over `frames` timeline frames: sets `idx`'s
2869 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2870 /// each clamped to its own clip's length. `false` -- no history -- unless
2871 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2872 /// adjacent: the second's [`Clip::start`] is exactly the first's
2873 /// [`Clip::end`], no gap between them.
2874 ///
2875 /// This is the whole mechanism, not a stand-in for one: a *real*
2876 /// cross-fade -- both takes heard at once, blending -- is what two clips
2877 /// **overlapping** on separate lanes already get for free from the
2878 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2879 /// This call only shapes the edges of two clips already sitting
2880 /// end-to-end on *one* lane, so the join between them fades like one did.
2881 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2882 if lane.kind != LaneKind::Audio {
2883 return false;
2884 }
2885 let clips = self.lane(lane);
2886 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2887 return false;
2888 };
2889 if a.end() != b.start {
2890 return false;
2891 }
2892 self.snapshot();
2893 let clips = self.lane_mut(lane).expect("checked above");
2894 clips[idx].fade_out = frames.min(clips[idx].frames());
2895 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2896 true
2897 }
2898
2899 /// Every frame number on every lane rewritten onto a timeline counted at
2900 /// another rate: `k` is old timeline frames per new one, `counts` is how
2901 /// long each source is on the *new* timeline (indexed as
2902 /// [`Project::sources`] is), and the edit survives as the same seconds of
2903 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2904 /// the edit list, and the only thing that touches the frame numbers without
2905 /// being an edit anyone made.
2906 ///
2907 /// Every position -- a clip's start and its end alike -- goes through the
2908 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2909 /// stays a gap, and a take's picture and its sound land on the same frame on
2910 /// their two lanes: no lane can drift against another. A clip is then only
2911 /// ever made to *fit* the room its own start and end mapped to, never to
2912 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2913 /// below is the backstop for the one case that could: a slow clip so short
2914 /// that no source range fits its new room at all).
2915 ///
2916 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2917 /// onto the new grid, so a rate picked, unpicked and picked again is within
2918 /// a frame of where it started rather than back at it. Upgrade path is
2919 /// keeping the edit list at one reference rate and conforming on the way
2920 /// out, which every frame number in this module would then be measured in.
2921 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2922 for lane in &mut self.lanes {
2923 let mut cursor = 0;
2924 for clip in &mut lane.clips {
2925 let start = k.timeline_at(clip.start).max(cursor);
2926 // The room its own end mapped to -- never zero, since a clip is
2927 // never empty even on a grid too coarse to hold it.
2928 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2929 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2930 // Its footage, held inside the file's new length: a clip whose
2931 // out-point was the last frame of its source must not come out
2932 // of this naming a frame past the end -- that is a project that
2933 // would not open again ([`crate::PlaybackSession::open_project`]
2934 // refuses one by name).
2935 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2936 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2937 clip.start = start;
2938 clip.in_frame = in_frame;
2939 clip.out_frame = in_frame + len;
2940 cursor = clip.end();
2941 }
2942 // A subtitle's *window* is in microseconds and a rate change moves
2943 // no seconds, so only where it sits is remapped -- through the same
2944 // [`Rate::timeline_at`] every clip boundary goes through, so a
2945 // caption still starts on the frame its picture does.
2946 let mut cursor = 0;
2947 for sub in &mut lane.subs {
2948 let start = k.timeline_at(sub.start).max(cursor);
2949 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2950 sub.start = start;
2951 cursor = sub.end();
2952 }
2953 }
2954 }
2955
2956 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2957 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2958 ///
2959 /// A subtitle lane counts like any other: a caption placed past the last
2960 /// picture holds the timeline open under it, exactly as an `A2` running
2961 /// past `V1` does, rather than being silently clipped away by the length
2962 /// ([`crate::export::timeline_cues`] clips cues to this).
2963 pub fn timeline_frames(&self) -> u32 {
2964 self.lanes
2965 .iter()
2966 .filter_map(|l| match l.kind {
2967 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2968 _ => l.clips.last().map(Clip::end),
2969 })
2970 .max()
2971 .unwrap_or(0)
2972 }
2973
2974 /// The same, counting the *media* alone: where the last picture or sound
2975 /// runs out, with the captions over them ignored.
2976 ///
2977 /// What an export actually writes ends here -- the picture loop walks the
2978 /// composite spans and the file stops with them -- so this is the length a
2979 /// cue has to be inside of to be written at all (what
2980 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2981 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2982 /// thing is a picture or a sound, which is every timeline that has no
2983 /// caption hanging past the end of both.
2984 pub fn media_frames(&self) -> u32 {
2985 self.lanes
2986 .iter()
2987 .filter(|l| l.kind != LaneKind::Subtitle)
2988 .filter_map(|l| l.clips.last().map(Clip::end))
2989 .max()
2990 .unwrap_or(0)
2991 }
2992
2993 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2994 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2995 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2996 self.lane_spans(Lane::V1)
2997 }
2998
2999 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
3000 // Timeline frames, not source ones: a box on a lane is as wide as the
3001 // clip is long *there*, which a speed halves or quadruples.
3002 self.lane(lane)
3003 .iter()
3004 .map(|c| (c.start, c.frames()))
3005 .collect()
3006 }
3007
3008 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
3009 /// and past the end -- [`Project::span_at`] is the version that tells those
3010 /// two apart.
3011 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
3012 let clips = self.lane(lane);
3013 let idx = at(clips, timeline_frame)?;
3014 Some((idx, source_frame(&clips[idx], timeline_frame)))
3015 }
3016
3017 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
3018 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
3019 self.map(Lane::V1, timeline_frame)
3020 }
3021
3022 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
3023 /// it, or the gap running to the next clip (or to the end of the timeline,
3024 /// which is where a lane shorter than its neighbour keeps showing black).
3025 /// `None` at or past the end of the timeline, which is the only "nothing
3026 /// left" there is.
3027 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
3028 let total = self.timeline_frames();
3029 if timeline_frame >= total {
3030 return None;
3031 }
3032 let clips = self.lane(lane);
3033 Some(match at(clips, timeline_frame) {
3034 Some(idx) => Span {
3035 start: timeline_frame,
3036 len: clips[idx].end() - timeline_frame,
3037 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
3038 speed: clips[idx].speed,
3039 },
3040 None => Span {
3041 start: timeline_frame,
3042 speed: Speed::NORMAL,
3043 // The next placement, or the end of the timeline: a gap is
3044 // bounded by what comes after it, never by its own bookkeeping.
3045 len: clips
3046 .iter()
3047 .find(|c| c.start > timeline_frame)
3048 .map_or(total, |c| c.start)
3049 - timeline_frame,
3050 from: None,
3051 },
3052 })
3053 }
3054
3055 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
3056 /// gaps included -- the whole play list, which is what an export walks.
3057 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
3058 let mut out = Vec::new();
3059 let mut t = timeline_frame;
3060 while let Some(span) = self.span_at(lane, t) {
3061 t = span.end();
3062 out.push(span);
3063 }
3064 out
3065 }
3066
3067 /// What the *composite* shows from `timeline_frame` on -- the answer
3068 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
3069 /// video lane by one rule: **the topmost lane with a clip there wins**, and
3070 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
3071 /// (the usual overlay convention). A frame no video lane covers is a gap,
3072 /// which is black however many lanes are above or below it.
3073 ///
3074 /// No blending, so exactly one lane is visible at a time and the composite
3075 /// is itself a span list -- which is why one decoder plays it, the same one
3076 /// a single-lane timeline uses, rather than N running at once.
3077 ///
3078 /// The span is cut short wherever a *higher* lane's clip starts, because
3079 /// from that frame on a different lane wins; that is what makes walking
3080 /// [`composite_spans_from`](Project::composite_spans_from) correct.
3081 ///
3082 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
3083 /// lanes would then be visible in one frame and the caller needs a decoder
3084 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
3085 /// (this same walk, per lane) feeding N decoders.
3086 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
3087 let total = self.timeline_frames();
3088 if timeline_frame >= total {
3089 return None;
3090 }
3091 let video = self.video_lanes();
3092 // The last covering lane is the winner; only the lanes above it can
3093 // interrupt what it shows.
3094 let winner = video
3095 .iter()
3096 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
3097 let (from, speed, until) = match winner {
3098 Some(i) => {
3099 let clips = self.lane(video[i]);
3100 let idx = at(clips, timeline_frame).expect("just found above");
3101 (
3102 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
3103 clips[idx].speed,
3104 clips[idx].end(),
3105 )
3106 }
3107 // Nothing covers it: black until something above the floor starts.
3108 None => (None, Speed::NORMAL, total),
3109 };
3110 let takeover = video[winner.map_or(0, |i| i + 1)..]
3111 .iter()
3112 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
3113 .map(|c| c.start)
3114 .min();
3115 Some(Span {
3116 start: timeline_frame,
3117 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
3118 from,
3119 speed,
3120 })
3121 }
3122
3123 /// The video lanes in display order, topmost last -- the order the composite
3124 /// rule counts in.
3125 fn video_lanes(&self) -> Vec<Lane> {
3126 self.lanes()
3127 .into_iter()
3128 .filter(|l| l.kind == LaneKind::Video)
3129 .collect()
3130 }
3131
3132 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
3133 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
3134 /// index on that lane. `None` over a gap and past the end. What a front-end
3135 /// asks to act on "the clip on screen" without re-deriving the rule.
3136 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
3137 let video = self.video_lanes();
3138 let winner = video
3139 .iter()
3140 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
3141 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
3142 }
3143
3144 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
3145 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
3146 /// answers "the clip on screen"; this answers it per lane, which is what
3147 /// walking the lanes for something to select needs.
3148 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
3149 at(self.lane(lane), timeline_frame)
3150 }
3151
3152 /// How the composite is graded at `timeline_frame`, so the picture playback
3153 /// converts and the one an export encodes are graded from one answer.
3154 /// `None` over a gap (black is black) and for a clip nobody has graded,
3155 /// which is the byte-identical path everywhere.
3156 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
3157 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3158 self.color_of(lane, idx)
3159 }
3160
3161 /// [`composite_color_at`](Self::composite_color_at)'s twin for
3162 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
3163 /// policy's own placement.
3164 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
3165 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3166 self.transform_of(lane, idx)
3167 }
3168
3169 /// How the composite meets the project canvas at `timeline_frame`, so the
3170 /// picture playback composes and the one an export encodes are placed from
3171 /// one answer. `Fit` over a gap, where black is already the canvas.
3172 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
3173 self.composite_clip_at(timeline_frame)
3174 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
3175 }
3176
3177 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
3178 /// over a gap / a picture that is not a visualizer.
3179 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
3180 self.composite_clip_at(timeline_frame)
3181 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
3182 .unwrap_or(0)
3183 }
3184
3185 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
3186 /// `timeline_frame`, or zero over a gap / a picture that is not a
3187 /// visualizer.
3188 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
3189 self.composite_clip_at(timeline_frame)
3190 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
3191 .unwrap_or(0)
3192 }
3193
3194 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
3195 /// viewer sees from `timeline_frame` to the end, in order. What an export
3196 /// encodes and what playback walks at a clip boundary.
3197 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
3198 let mut out = Vec::new();
3199 let mut t = timeline_frame;
3200 while let Some(span) = self.composite_span_at(t) {
3201 t = span.end();
3202 out.push(span);
3203 }
3204 out
3205 }
3206
3207 /// Split every lane at `timeline_frame`, so that frame becomes the first
3208 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
3209 /// (`false`, no change) when no lane has a clip to split there -- at a
3210 /// placement's own start, in a gap, and past the end -- all of which would
3211 /// produce an empty clip or nothing at all.
3212 ///
3213 /// Lanes' halves share an id only where they are the *same* span: the lanes
3214 /// are edited apart, so the clip being cut here may start (or end)
3215 /// somewhere else on another lane, and a group id whose clips disagree
3216 /// about their span is not one take (see [`links_are_consistent`], which
3217 /// refuses to load one).
3218 ///
3219 /// Metadata only: no mapping changes, in any lane.
3220 pub fn split(&mut self, timeline_frame: u32) -> bool {
3221 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
3222 }
3223
3224 /// [`split`](Project::split), with the snapshot optional and the lanes
3225 /// named: a batch that has already taken a snapshot
3226 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3227 /// region and must still be one undo press, and a *scoped* batch must not
3228 /// cut a lane it was told to leave alone.
3229 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3230 let cut: Vec<Option<Clip>> = self
3231 .lanes
3232 .iter()
3233 .enumerate()
3234 .map(|(i, l)| {
3235 on.contains(&i)
3236 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3237 .flatten()
3238 })
3239 .collect();
3240 // The same question on the subtitle lanes, in their own arithmetic: a
3241 // razor cuts the captions with the picture, and a frame where only a
3242 // caption can be cut is still a cut.
3243 let cut_subs: Vec<bool> = self
3244 .lanes
3245 .iter()
3246 .enumerate()
3247 .map(|(i, l)| {
3248 on.contains(&i)
3249 && l.subs
3250 .iter()
3251 .any(|s| s.start < timeline_frame && timeline_frame < s.end())
3252 })
3253 .collect();
3254 // The links the captions carry, read before the room is opened below
3255 // -- `sub_open_room` takes the id off both halves, exactly as
3256 // `open_room` does for a clip, and the split hands the halves theirs
3257 // back afterwards.
3258 let sub_orig: Vec<Option<u32>> = self
3259 .lanes
3260 .iter()
3261 .zip(&cut_subs)
3262 .map(|(l, &cut)| {
3263 cut.then(|| {
3264 l.subs
3265 .iter()
3266 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3267 .and_then(|s| s.link)
3268 })
3269 .flatten()
3270 })
3271 .collect();
3272 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3273 return false;
3274 }
3275 if snapshot {
3276 self.snapshot();
3277 }
3278 for (data, _) in self
3279 .lanes
3280 .iter_mut()
3281 .zip(&cut_subs)
3282 .filter(|&(_, &cut)| cut)
3283 {
3284 // A split is room of no width: the halves keep their windows by
3285 // proportion and nothing moves.
3286 sub_open_room(&mut data.subs, timeline_frame, 0);
3287 debug_assert!(subs_sorted_disjoint(&data.subs));
3288 }
3289 // Each side is its own question, and the answer is the group the clip
3290 // already carried: the left half *keeps* its take's id -- the take the
3291 // frames before the cut still are -- and the right halves of one take
3292 // share one fresh id of their own, clips and captions alike. A lane
3293 // holding no group (a `place`ment, a caption nobody grouped) comes out
3294 // of the cut holding none, which is what it went in with. The captions'
3295 // own links were drawn above, before the room opened.
3296 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3297 let mut distinct: Vec<u32> = Vec::new();
3298 for id in orig.iter().chain(&sub_orig).flatten() {
3299 if !distinct.contains(id) {
3300 distinct.push(*id);
3301 }
3302 }
3303 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3304 let right_of = |link: Option<u32>| {
3305 link.and_then(|id| distinct.iter().position(|&d| d == id))
3306 .map(|at| fresh[at])
3307 };
3308 for (l, data) in self.lanes.iter_mut().enumerate() {
3309 if !cut_subs[l] {
3310 continue;
3311 }
3312 // The pair the razor just made: they touch at the frame it cut.
3313 if let Some(idx) = data
3314 .subs
3315 .iter()
3316 .position(|s| s.end() == timeline_frame)
3317 .filter(|&idx| {
3318 data.subs
3319 .get(idx + 1)
3320 .is_some_and(|n| n.start == timeline_frame)
3321 })
3322 {
3323 data.subs[idx].link = sub_orig[l];
3324 data.subs[idx + 1].link = right_of(sub_orig[l]);
3325 }
3326 }
3327 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3328 // The lanes this call was not scoped to are not cut, whatever their
3329 // own clips would allow.
3330 let Some(idx) =
3331 splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some())
3332 else {
3333 continue;
3334 };
3335 let mut tail = data.clips[idx];
3336 // Where the cut lands *in the file*, which is the clip's own rate
3337 // away from where it lands on the timeline. Both halves keep the
3338 // speed, and `splittable` has already refused any frame at which
3339 // the two would not add up to the one being cut.
3340 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3341 tail.start = timeline_frame;
3342 tail.link = right_of(orig[data_i]);
3343 // A split makes a new edge for each half, and a fade is a promise
3344 // about an edge: only the half that *kept* the original edge
3345 // keeps that fade, re-clamped to its own now-shorter length (a
3346 // cut inside the ramp shortens it, never leaves it pointing past
3347 // the clip it is on); the edge the cut itself made starts, or
3348 // ends, flat -- there was no silence there to ramp out of.
3349 tail.fade_in = 0;
3350 tail.fade_out = tail.fade_out.min(tail.frames());
3351 // A dissolve is a promise about the *end* edge, same as
3352 // `fade_out`: only the half that kept the clip's original end
3353 // (the tail) keeps it, re-clamped to its own now-shorter length;
3354 // the head's new end is the cut the razor just made, which starts
3355 // flat -- there was no successor to dissolve into there.
3356 tail.transition_out = tail.transition_out.min(tail.frames());
3357 data.clips[idx].out_frame = tail.in_frame;
3358 data.clips[idx].link = orig[data_i];
3359 data.clips[idx].fade_out = 0;
3360 data.clips[idx].transition_out = 0;
3361 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3362 data.clips.insert(idx + 1, tail);
3363 }
3364 true
3365 }
3366
3367 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3368 /// at `timeline_frame` in every lane and put the result back in one group.
3369 /// Only what a split could have produced is rejoined -- the two sides must
3370 /// touch on the timeline *and* be consecutive frames of the same source --
3371 /// so the clip list comes back exactly as it was and traversal with it.
3372 /// `false` when no lane has such a pair. The rejoined placement keeps the
3373 /// **left** half's id, which is the take the split left on it: rejoining a
3374 /// cut take puts the take back, id and all.
3375 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3376 // What each lane would end up covering, if it joins here at all.
3377 let joined: Vec<Option<(u32, u32)>> = self
3378 .lanes
3379 .iter()
3380 .map(|l| {
3381 joinable(&l.clips, timeline_frame)
3382 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3383 })
3384 .collect();
3385 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3386 let join_subs: Vec<Option<usize>> = self
3387 .lanes
3388 .iter()
3389 .map(|l| sub_joinable(&l.subs, timeline_frame))
3390 .collect();
3391 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3392 return false;
3393 }
3394 self.snapshot();
3395 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3396 if let Some(idx) = sub {
3397 data.subs[idx].frames += data.subs[idx + 1].frames;
3398 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3399 data.subs.remove(idx + 1);
3400 debug_assert!(subs_sorted_disjoint(&data.subs));
3401 }
3402 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3403 continue;
3404 };
3405 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3406 data.clips.remove(idx + 1);
3407 }
3408 true
3409 }
3410
3411 /// Take the placement at `idx` of `lane` out of its group: every clip and
3412 /// every caption carrying its id -- on however many lanes -- is handed an
3413 /// id of its own, so from here on each half moves, trims and is deleted
3414 /// alone. The music video whose sound is to be cut against its picture
3415 /// starts here, and so does the caption that has to come off the picture it
3416 /// was pinned to.
3417 ///
3418 /// An id of its own rather than none at all: a half no other lane is grouped
3419 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3420 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3421 /// as detached. `None` would instead say "was never part of a take", which
3422 /// is what a one-lane [`place`](Project::place) means.
3423 ///
3424 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3425 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3426 /// the group back. Refused (`false`, nothing changed) for an index that is
3427 /// not there, a placement in no group at all, and one whose group has no
3428 /// other half -- that one is already detached, and a refusal must not cost
3429 /// an undo step.
3430 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3431 let Some(members) = self.group_of(lane, idx) else {
3432 return false;
3433 };
3434 if members.alone() {
3435 return false;
3436 }
3437 let Some(id) = self
3438 .lane(lane)
3439 .get(idx)
3440 .and_then(|c| c.link)
3441 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3442 else {
3443 return false;
3444 };
3445 self.snapshot();
3446 // Drawn before the walk: `new_link` takes the whole project, and the
3447 // walk holds the lanes.
3448 let count = members.clips.len() + members.subs.len();
3449 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3450 for data in &mut self.lanes {
3451 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3452 c.link = fresh.pop();
3453 }
3454 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3455 s.link = fresh.pop();
3456 }
3457 }
3458 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3459 true
3460 }
3461
3462 /// Put two clips on two lanes into one group, so what moves one moves the
3463 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3464 /// how a picture is regrouped with sound it was never opened with. Whatever
3465 /// either of them was grouped with comes along: those clips cover this same
3466 /// span already, so the result is one group and not two overlapping ones.
3467 ///
3468 /// Same frames or nothing: a group id names **one span** on however many
3469 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3470 /// clips that do not cover the same frames cannot be one take, and the
3471 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3472 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3473 /// mean, not the rule.
3474 ///
3475 /// Metadata only, one snapshot. The error says what is wrong, because
3476 /// `false` would not: a bad index, one lane twice (a group is at most one
3477 /// clip per lane), spans that disagree, and a pair that is already one take
3478 /// -- nothing changes, and none of them costs an undo step.
3479 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3480 if a == b {
3481 return Err(format!(
3482 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3483 a.label()
3484 )
3485 .into());
3486 }
3487 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3488 p.lane(lane)
3489 .get(idx)
3490 .copied()
3491 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3492 };
3493 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3494 if (x.start, x.end()) != (y.start, y.end()) {
3495 return Err(format!(
3496 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3497 a.label(),
3498 x.start,
3499 x.end(),
3500 b.label(),
3501 y.start,
3502 y.end()
3503 )
3504 .into());
3505 }
3506 if x.link.is_some() && x.link == y.link {
3507 return Err("those two are one take already".into());
3508 }
3509 self.snapshot();
3510 let id = self.new_link();
3511 // Every clip either of them was grouped with, by the same rule: all of
3512 // them cover this span, so one id over the lot stays consistent.
3513 let old = [x.link, y.link];
3514 for data in &mut self.lanes {
3515 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3516 if old.contains(&c.link) {
3517 c.link = Some(id);
3518 }
3519 }
3520 }
3521 // And the two themselves, which a `place` may have left in no group.
3522 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3523 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3524 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3525 Ok(())
3526 }
3527
3528 /// Put every placement the picks name into one group -- the group a hand
3529 /// builds with ctrl-click and a menu: the picture, its sound and the
3530 /// caption over it, on as many lanes as the picks name. What any of them
3531 /// was already grouped with rides along (one group, not two sharing a
3532 /// member), and the members keep their own spans: a group is one id over
3533 /// one placement per lane, and the offsets between them are what the group
3534 /// preserves -- a drag, a trim and a delete all move the members *by the
3535 /// same distance*, not to the same frames.
3536 ///
3537 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3538 /// and the refusal says which lane -- and a pick that names nothing is
3539 /// refused with its own words. At least two picks, or there is nothing to
3540 /// group.
3541 ///
3542 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3543 /// apart again. None of the refusals changes anything or costs an undo
3544 /// step.
3545 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3546 if picks.len() < 2 {
3547 return Err("a group is two placements or more: pick another one first".into());
3548 }
3549 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3550 for &(lane, idx) in picks {
3551 if seen.contains(&lane) {
3552 return Err(format!(
3553 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3554 track",
3555 lane.label()
3556 )
3557 .into());
3558 }
3559 seen.push(lane);
3560 let there = if lane.kind == LaneKind::Subtitle {
3561 idx < self.sub_lane(lane).len()
3562 } else {
3563 idx < self.lane(lane).len()
3564 };
3565 if !there {
3566 let what = if lane.kind == LaneKind::Subtitle {
3567 "subtitle"
3568 } else {
3569 "clip"
3570 };
3571 return Err(format!("there is no {what} {idx} on {}", lane.label()).into());
3572 }
3573 }
3574 let links: Vec<Option<u32>> = picks
3575 .iter()
3576 .map(|&(lane, idx)| {
3577 if lane.kind == LaneKind::Subtitle {
3578 self.sub_lane(lane)[idx].link
3579 } else {
3580 self.lane(lane)[idx].link
3581 }
3582 })
3583 .collect();
3584 // The picks are already one per lane (`seen`, above), but a pick's
3585 // *existing* group can carry a second member onto a lane another
3586 // pick (or another existing group in the merge) already occupies --
3587 // two captions on one sub lane, say, each grouped with a different
3588 // clip before this call. Merging both in would leave that lane with
3589 // two members of one id, which `links_are_consistent` may never see:
3590 // refused by name, before anything moves, rather than a group closed
3591 // broken.
3592 let labels = handles(&self.lanes);
3593 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3594 for (li, data) in self.lanes.iter().enumerate() {
3595 let n = data
3596 .clips
3597 .iter()
3598 .filter(|c| c.link.is_some() && links.contains(&c.link))
3599 .count()
3600 + data
3601 .subs
3602 .iter()
3603 .filter(|s| s.link.is_some() && links.contains(&s.link))
3604 .count();
3605 if n > 0 {
3606 per_lane.insert(li, n as u32);
3607 }
3608 }
3609 // A pick that carries no link of its own is invisible to the scan
3610 // above (there is no `Some` to match): it still claims its lane.
3611 for &(lane, _) in picks {
3612 let li = self.index(lane).expect("checked above");
3613 per_lane.entry(li).or_insert(0);
3614 if !self.lanes[li]
3615 .clips
3616 .iter()
3617 .any(|c| c.link.is_some() && links.contains(&c.link))
3618 && !self.lanes[li]
3619 .subs
3620 .iter()
3621 .any(|s| s.link.is_some() && links.contains(&s.link))
3622 {
3623 *per_lane.get_mut(&li).expect("just inserted") += 1;
3624 }
3625 }
3626 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3627 return Err(format!(
3628 "a group is one placement per lane: merging these groups would put two on {}",
3629 labels[li].label()
3630 )
3631 .into());
3632 }
3633 self.snapshot();
3634 let id = self.new_link();
3635 // Whatever any pick was grouped with comes along, for [`group`]'s
3636 // reason -- one id over the lot, not two groups sharing a member.
3637 for data in &mut self.lanes {
3638 for c in data.clips.iter_mut() {
3639 if c.link.is_some() && links.contains(&c.link) {
3640 c.link = Some(id);
3641 }
3642 }
3643 for s in data.subs.iter_mut() {
3644 if s.link.is_some() && links.contains(&s.link) {
3645 s.link = Some(id);
3646 }
3647 }
3648 }
3649 // And the picks themselves, which a `place` may have left in no group.
3650 // The lane seats are read before the walk, which holds the lanes.
3651 let seats: Vec<(usize, bool)> = picks
3652 .iter()
3653 .map(|&(lane, _)| {
3654 (
3655 self.index(lane).expect("checked above"),
3656 lane.kind == LaneKind::Subtitle,
3657 )
3658 })
3659 .collect();
3660 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3661 let _ = lane;
3662 if sub {
3663 self.lanes[at].subs[idx].link = Some(id);
3664 } else {
3665 self.lanes[at].clips[idx].link = Some(id);
3666 }
3667 }
3668 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3669 Ok(())
3670 }
3671
3672 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3673 /// lands on and leaving every other clip exactly where it is -- the
3674 /// per-lane paste. Anything already there is trimmed away (and split in two
3675 /// if `clip` lands inside it), which is what keeps the lane sorted and
3676 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3677 /// gap. Refused only for an empty `clip`.
3678 ///
3679 /// The placement belongs to no group: a clipboard clip carries the link id
3680 /// of the take it was copied from, and placing it twice -- or placing a copy
3681 /// back over the clip it came from -- would put that id on two clips of one
3682 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3683 /// `None` rather than a fresh id because a one-lane placement has nothing on
3684 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3685 /// become a group again.
3686 ///
3687 /// Refused for an empty `clip`, for a lane that is not there, and for a
3688 /// subtitle lane, which carries no picture and no sound
3689 /// ([`Project::place_sub`] is its door).
3690 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3691 if clip.out_frame <= clip.in_frame
3692 || lane.kind == LaneKind::Subtitle
3693 || self.index(lane).is_none()
3694 {
3695 return false;
3696 }
3697 self.snapshot();
3698 let clip = Clip {
3699 fade_in: 0,
3700 fade_out: 0,
3701 transition_out: 0,
3702 start: timeline_frame,
3703 link: None,
3704 ..clip
3705 };
3706 self.insert_over(lane, clip);
3707 true
3708 }
3709
3710 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3711 /// one grouped take -- what a picture let go over a further video track
3712 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3713 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3714 /// this half a file with sound landed on a layer silent, and the only way to
3715 /// hear it was to drop it a second time on an audio lane.
3716 ///
3717 /// Both halves overwrite what they land on and neither ripples, exactly as
3718 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3719 /// nothing under it moves. One history snapshot for the pair, the added lane
3720 /// included, so one [`Project::undo`] takes the whole placement back. The two
3721 /// carry one link, which is what makes them one take to a drag, a trim and a
3722 /// save.
3723 ///
3724 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3725 /// there or is not a video lane: sound placed alone is
3726 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3727 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3728 if clip.out_frame <= clip.in_frame
3729 || lane.kind != LaneKind::Video
3730 || self.index(lane).is_none()
3731 {
3732 return false;
3733 }
3734 self.snapshot();
3735 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3736 // an ord names a lane only while every ord below it does.
3737 while self.lane_count(LaneKind::Audio) <= lane.ord {
3738 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3739 }
3740 let clip = Clip {
3741 fade_in: 0,
3742 fade_out: 0,
3743 transition_out: 0,
3744 start: timeline_frame,
3745 link: Some(self.new_link()),
3746 ..clip
3747 };
3748 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3749 self.insert_over(half, clip);
3750 }
3751 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3752 true
3753 }
3754
3755 /// `clip` into `lane` at its own start, over whatever it lands on: the
3756 /// insert both placement doors make, which is what keeps a lane sorted and
3757 /// disjoint. The caller has checked that the lane is there.
3758 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3759 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3760 clear(clips, clip.start, clip.end());
3761 let idx = clips.partition_point(|c| c.start < clip.start);
3762 clips.insert(idx, clip);
3763 debug_assert!(sorted_disjoint(clips));
3764 }
3765
3766 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3767 /// frame `start`: the drag that rearranges takes, along a track and across
3768 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3769 /// was. `start` at the clip's own is the pure lane change.
3770 ///
3771 /// The whole group travels the same distance, each half on the lane it
3772 /// already sits on -- a link means "these cover one span on however many
3773 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3774 /// sound would be a group no save could load. Only the dragged half changes
3775 /// lane, and that is not a desync: a link names no lane at all.
3776 ///
3777 /// `start` is **clamped**, never refused, to the room the group has: no
3778 /// member crosses a neighbour on the lane it lands on, exactly as
3779 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3780 /// dragging past a neighbour means "as far as it goes", and butting up
3781 /// against the take next door is how clips are laid end to end. The
3782 /// tightest member's wall wins, so a sound half boxed in between two others
3783 /// holds its picture still.
3784 ///
3785 /// Refused, changing nothing and costing no undo step, for a lane that is
3786 /// not there, an index that is not there, a move across *kinds* (a picture
3787 /// cannot play on an audio lane, and the save it wrote would not open
3788 /// again), a head let go *inside* another clip or into a gap too narrow to
3789 /// hold this one -- a move that overwrote what it landed on would destroy a
3790 /// take the pointer never named, which is what [`place`](Project::place)
3791 /// may do and a drag may not -- a half let go onto the lane its own partner
3792 /// is on, and a drop that changes neither lane nor frame, which is a clip
3793 /// picked up and put back down, i.e. a click.
3794 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3795 self.move_selection(&[(from, idx)], from, idx, to, start)
3796 }
3797
3798 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
3799 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
3800 /// reads it) travels the same distance as the clip at `idx` of `from`,
3801 /// which alone changes lane, onto `to`. One clamp across the whole set
3802 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
3803 /// neighbour that boxes in *any* member narrows the delta every member
3804 /// moves by, and a member with no room at all (`lo > hi`) refuses the
3805 /// whole set rather than moving the rest and leaving that one behind.
3806 /// `move_clip` is this with a selection of one -- the dragged clip's own
3807 /// group and nothing else -- so a drag on a clip outside the selection is
3808 /// byte-identical to before this existed.
3809 pub fn move_selection(
3810 &mut self,
3811 picks: &[(Lane, usize)],
3812 from: Lane,
3813 idx: usize,
3814 to: Lane,
3815 start: u32,
3816 ) -> bool {
3817 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3818 return false;
3819 };
3820 if from.kind != to.kind {
3821 return false;
3822 }
3823 let held = self.index(from).expect("the clip was found on it");
3824 // Every pick's own group, unioned: the whole selection moves as one,
3825 // and a pick's link partners (not themselves picked) come along with
3826 // it exactly as a lone drag's do.
3827 let mut members = Members::default();
3828 for &(lane, i) in picks {
3829 let Some(group) = self.group_of(lane, i) else {
3830 continue;
3831 };
3832 for m in group.clips {
3833 if !members.clips.contains(&m) {
3834 members.clips.push(m);
3835 }
3836 }
3837 for m in group.subs {
3838 if !members.subs.contains(&m) {
3839 members.subs.push(m);
3840 }
3841 }
3842 }
3843 if !members.clips.contains(&(held, idx)) {
3844 members.clips.push((held, idx));
3845 }
3846 // The two halves of *the dragged clip's own* group would land on one
3847 // span of one lane, which is the one thing a link may never mean --
3848 // checked against that group alone, not the whole moving set: an
3849 // unlinked fellow pick already sitting on `dest` is no conflict at
3850 // all, since it travels by the same delta and `move_room` below
3851 // leaves it the room to. Refused rather than clamped: the partner
3852 // moves the same distance, so there is no room for it anywhere on
3853 // that lane.
3854 let own_group = self.group_of(from, idx).expect("the clip was found");
3855 if dest != held
3856 && own_group
3857 .clips
3858 .iter()
3859 .chain(&own_group.subs)
3860 .any(|&(l, _)| l == dest)
3861 {
3862 return false;
3863 }
3864 let want = i64::from(start) - i64::from(clip.start);
3865 // How far the group may travel, in timeline frames and signed: every
3866 // member -- the clips and any caption grouped with them -- narrows it
3867 // to the gap it is landing in, and what is left is what the pointer is
3868 // clamped to.
3869 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3870 return false;
3871 };
3872 if lo > hi {
3873 return false;
3874 }
3875 let delta = want.clamp(lo, hi);
3876 if delta == 0 && dest == held {
3877 return false;
3878 }
3879 self.snapshot();
3880 for &(l, i) in &members.clips {
3881 let c = &mut self.lanes[l].clips[i];
3882 // In range by the walls above, which are `u32` frames throughout.
3883 c.start = (i64::from(c.start) + delta) as u32;
3884 }
3885 for &(l, i) in &members.subs {
3886 let s = &mut self.lanes[l].subs[i];
3887 s.start = (i64::from(s.start) + delta) as u32;
3888 }
3889 if dest != held {
3890 let clip = self.lanes[held].clips.remove(idx);
3891 let clips = &mut self.lanes[dest].clips;
3892 let at = clips.partition_point(|c| c.start < clip.start);
3893 clips.insert(at, clip);
3894 }
3895 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3896 debug_assert!(members.clips.iter().chain(&members.subs).all(|&(l, _)| {
3897 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3898 }));
3899 true
3900 }
3901
3902 /// How far a group drag may travel, `(least, most)` in timeline frames and
3903 /// signed: every member narrows the range to the gap it is landing in --
3904 /// the clips against their lanes' clips and the captions against their
3905 /// lanes' captions -- and what is left is what the pointer is clamped to.
3906 /// `travelling` names the one member that changes lane, if any: the clip a
3907 /// hand is carrying onto another track, whose walls are read on the lane it
3908 /// is let go over at the frame the pointer named. `None` when a member has
3909 /// no gap to land in at all.
3910 fn move_room(
3911 &self,
3912 members: &Members,
3913 travelling: Option<(usize, usize, usize, u32)>,
3914 ) -> Option<(i64, i64)> {
3915 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3916 for &(l, i) in members.clips.iter().chain(&members.subs) {
3917 let sub = members.subs.contains(&(l, i));
3918 let (start, frames) = match self.lanes[l]
3919 .clips
3920 .get(i)
3921 .filter(|_| !sub)
3922 .map(|c| (c.start, c.frames()))
3923 {
3924 Some(pair) => pair,
3925 None => {
3926 let s = self.lanes[l].subs.get(i)?;
3927 (s.start, s.frames)
3928 }
3929 };
3930 let land = travelling
3931 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3932 .map_or(l, |(_, _, dest, _)| dest);
3933 // Which gap this member's walls are read off: its own place on the
3934 // lane it stays on, and the frame the pointer named on the lane it
3935 // is let go over. A clip's neighbours are the clips of the lane it
3936 // lands on and a caption's are its captions -- the two lists of one
3937 // lane never meet.
3938 let at = match travelling {
3939 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3940 _ => start,
3941 };
3942 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3943 let neighbours: Vec<(u32, u32)> = if sub {
3944 self.lanes[land]
3945 .subs
3946 .iter()
3947 .map(|s| (s.start, s.end()))
3948 .collect()
3949 } else {
3950 self.lanes[land]
3951 .clips
3952 .iter()
3953 .map(|c| (c.start, c.end()))
3954 .collect()
3955 };
3956 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3957 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3958 continue;
3959 }
3960 if *other_start <= at && at < *other_end {
3961 // A head let go inside another placement, which a clamp
3962 // has no answer for: the drop is refused.
3963 return None;
3964 }
3965 match other_end <= &at {
3966 true => wall_lo = wall_lo.max(*other_end),
3967 false => wall_hi = wall_hi.min(*other_start),
3968 }
3969 }
3970 if wall_hi - wall_lo < frames {
3971 return None;
3972 }
3973 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3974 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3975 }
3976 Some((lo, hi))
3977 }
3978
3979 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3980 /// the drag on a clip's end that makes it play more or less of its source.
3981 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3982 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3983 /// is room that was already empty. One snapshot, so a whole drag is one
3984 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3985 /// sample. Changes the timeline->source mapping: the caller must reseek.
3986 ///
3987 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3988 /// exactly what they played before, which is what makes this a trim and not
3989 /// a slip.
3990 ///
3991 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3992 /// legal means "as far as it goes", and stopping the box there is the
3993 /// affordance. The walls are: one frame of clip always survives, an edge
3994 /// never crosses the neighbouring clip on its own lane, an in-point never
3995 /// walks back past the source's first frame, and an out-point never runs
3996 /// past `source_frames[clip.source]` -- the caller's table of how long each
3997 /// source actually is ([`Project`] does not know, and a clip ending past its
3998 /// file's last frame is a save that will not open again; see
3999 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
4000 /// there may not grow at all.
4001 ///
4002 /// Linked placements trim *together*, by one delta: every member's same
4003 /// edge moves the distance the dragged one did, clamped to the room its
4004 /// own walls leave -- offsets between the members of a hand-built group
4005 /// survive the trim, exactly as they survive a drag.
4006 ///
4007 /// `false`, changing nothing and costing no undo step, for an index that is
4008 /// not there and for an edge that is already where it was asked to go.
4009 pub fn trim(
4010 &mut self,
4011 lane: Lane,
4012 idx: usize,
4013 edge: Edge,
4014 to: u32,
4015 source_frames: &[u32],
4016 ) -> bool {
4017 let (Some((lo, hi)), Some(clip)) = (
4018 self.trim_room(lane, idx, edge, source_frames),
4019 self.lane(lane).get(idx).copied(),
4020 ) else {
4021 return false;
4022 };
4023 let to = to.clamp(lo, hi);
4024 let at = match edge {
4025 Edge::Start => clip.start,
4026 Edge::End => clip.end(),
4027 };
4028 if to == at {
4029 return false;
4030 }
4031 // Worked out before anything moves: at a slow rate a room can be too
4032 // narrow to hold even one source frame ([`Speed::fit`]), and the
4033 // dragged clip refusing to fit must refuse the whole gesture rather
4034 // than be given a range wider than its room -- which is the overlap
4035 // the lane invariant exists to forbid. The walls below leave that room,
4036 // so this is the backstop for a project that came in through another
4037 // door.
4038 let room = match edge {
4039 // The frames that stay play what they played, so what survives is
4040 // measured from the *end*.
4041 Edge::Start => clip.end() - to,
4042 Edge::End => to - clip.start,
4043 };
4044 let Some(keep) = clip.speed.fit(room) else {
4045 return false;
4046 };
4047 let members = self.group_of(lane, idx).expect("checked above");
4048 self.snapshot();
4049 let still = self.is_still(&clip);
4050 let held = self.index(lane).expect("checked above");
4051 let c = &mut self.lanes[held].clips[idx];
4052 match edge {
4053 // A still has no earlier frame to walk an in-point back to --
4054 // every frame of it is the same picture -- so its head grows
4055 // *forward*: the range it plays is however long the new room is,
4056 // anchored at the source's frame 0. Bounded by `lo`, which is where
4057 // the cap in `source_frames` is applied.
4058 Edge::Start if still => {
4059 c.in_frame = 0;
4060 c.out_frame = keep;
4061 c.start = to;
4062 }
4063 Edge::Start => {
4064 // Non-negative by `lo`, which is what keeps the in-point on the
4065 // source.
4066 c.in_frame = c.out_frame - keep.min(c.out_frame);
4067 c.start = to;
4068 }
4069 // Never wider than the room the edge was clamped to: see
4070 // [`Speed::fit`].
4071 Edge::End => c.out_frame = c.in_frame + keep,
4072 }
4073 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
4074 self.follow_group(
4075 &members,
4076 &(held, idx),
4077 edge,
4078 i64::from(to) - i64::from(at),
4079 source_frames,
4080 );
4081 true
4082 }
4083
4084 /// The rest of a group after one member's `edge` has moved by `delta`:
4085 /// every other member's same edge moves the same distance, clamped to the
4086 /// room its own walls leave -- a clip's against its lane and its source,
4087 /// a caption's against its own lane, its window following by the
4088 /// placement's own proportion. The undo step is the caller's: this is the
4089 // second half of one edit, not an edit of its own.
4090 fn follow_group(
4091 &mut self,
4092 members: &Members,
4093 dragged: &(usize, usize),
4094 edge: Edge,
4095 delta: i64,
4096 source_frames: &[u32],
4097 ) {
4098 for &(l, i) in &members.clips {
4099 if (l, i) == *dragged {
4100 continue;
4101 }
4102 let c = self.lanes[l].clips[i];
4103 let at = match edge {
4104 Edge::Start => c.start,
4105 Edge::End => c.end(),
4106 };
4107 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
4108 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
4109 if to == at {
4110 continue;
4111 }
4112 let room = match edge {
4113 Edge::Start => c.end() - to,
4114 Edge::End => to - c.start,
4115 };
4116 let Some(keep) = c.speed.fit(room) else {
4117 continue;
4118 };
4119 let still = self.is_still(&self.lanes[l].clips[i]);
4120 let c = &mut self.lanes[l].clips[i];
4121 match edge {
4122 Edge::Start if still => {
4123 c.in_frame = 0;
4124 c.out_frame = keep;
4125 c.start = to;
4126 }
4127 Edge::Start => {
4128 c.in_frame = c.out_frame - keep.min(c.out_frame);
4129 c.start = to;
4130 }
4131 Edge::End => c.out_frame = c.in_frame + keep,
4132 }
4133 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4134 }
4135 for &(l, i) in &members.subs {
4136 if (l, i) == *dragged {
4137 continue;
4138 }
4139 let s = self.lanes[l].subs[i];
4140 let at = match edge {
4141 Edge::Start => s.start,
4142 Edge::End => s.end(),
4143 };
4144 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
4145 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
4146 if to == at {
4147 continue;
4148 }
4149 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
4150 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4151 }
4152 }
4153
4154 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
4155 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
4156 /// What a front-end drawing the box *during* a drag asks, so the live width
4157 /// is the width the release will commit and an edge stops under the pointer
4158 /// rather than snapping back. The **clip's own** walls: the rest of its
4159 /// group follows by the same delta within their own ([`follow_group`]), so
4160 /// what is drawn for the dragged edge is what its own clip will commit.
4161 /// `None` for an index that is not there.
4162 pub fn trim_room(
4163 &self,
4164 lane: Lane,
4165 idx: usize,
4166 edge: Edge,
4167 source_frames: &[u32],
4168 ) -> Option<(u32, u32)> {
4169 let l = self.index(lane)?;
4170 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
4171 }
4172
4173 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
4174 /// its lane's storage index: the one wall computation, asked for the clip
4175 /// itself and for each member a group trim carries.
4176 fn clip_room(&self, l: usize, i: usize, edge: Edge, source_frames: &[u32]) -> (u32, u32) {
4177 let clips = &self.lanes[l].clips;
4178 let c = clips[i];
4179 let (lo, hi) = match edge {
4180 Edge::Start => (
4181 // Back to the source's own first frame -- as many *timeline*
4182 // frames as that head is worth at the clip's rate, which at
4183 // real time is the head itself -- and never over the clip in
4184 // front of it. Saturating because a clip may hold *more*
4185 // head than the timeline has room for -- a ripple delete
4186 // slides a clip back to frame 0 with its in-point wherever
4187 // the cut left it -- and frame 0 is the other wall.
4188 //
4189 // A still is measured from its *tail* instead: it has no
4190 // in-point worth the name (every frame the same picture), so
4191 // its head reaches exactly as far as its tail does -- out to
4192 // the length the caller's table gives it, whole. Measured
4193 // from the in-point it would have no head room at all, which
4194 // is a placed picture whose left edge cannot be dragged out.
4195 // No entry in the table means no growth, as it does at the
4196 // other end.
4197 if self.is_still(&c) {
4198 c.end().saturating_sub(
4199 c.speed
4200 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
4201 )
4202 } else {
4203 c.start.saturating_sub(c.speed.room(c.in_frame))
4204 }
4205 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
4206 // One *frame of clip* always survives, and at a rate below
4207 // real time one frame of clip is several frames of timeline
4208 // ([`Speed::room`]): an edge dragged closer than that would
4209 // ask for a range no source frame fits in. At real time this
4210 // is `end - 1`, unchanged.
4211 c.end() - c.speed.room(1),
4212 ),
4213 Edge::End => (
4214 // ...and the same wall from the other end: the shortest this
4215 // clip can be is the room one source frame of it takes.
4216 c.start + c.speed.room(1),
4217 // Out to whatever is left of the source -- again in timeline
4218 // frames, at this clip's rate -- and never over the clip
4219 // behind it.
4220 c.start
4221 .saturating_add(
4222 c.speed.room(
4223 source_frames
4224 .get(c.source)
4225 .copied()
4226 .unwrap_or(c.out_frame)
4227 .saturating_sub(c.in_frame),
4228 ),
4229 )
4230 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
4231 ),
4232 };
4233 // `hi.max(lo)`: for a clip the invariants hold for, the range always
4234 // contains the edge's own place, and a caller's wrong `source_frames`
4235 // must not become an empty range (or a panicking `clamp`) here.
4236 (lo, hi.max(lo))
4237 }
4238
4239 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
4240 /// every frame is the same picture, so which frame of it a clip's in-point
4241 /// names is not a question -- what [`Project::trim`] lets grow at either
4242 /// end. `false` for a source that is not there.
4243 fn is_still(&self, clip: &Clip) -> bool {
4244 self.sources
4245 .get(clip.source)
4246 .is_some_and(|s| crate::is_image(&s.path))
4247 }
4248
4249 /// The placements that move as one with the one at `idx` of `lane` --
4250 /// itself and whatever carries its link, on the media lanes and the
4251 /// subtitle ones alike. `None` for an index that is not there.
4252 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
4253 let sub = lane.kind == LaneKind::Subtitle;
4254 let link = if sub {
4255 self.sub_lane(lane).get(idx)?.link
4256 } else {
4257 self.lane(lane).get(idx)?.link
4258 };
4259 let mut members = Members::default();
4260 match link {
4261 Some(link) => {
4262 for (l, data) in self.lanes.iter().enumerate() {
4263 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
4264 members.clips.push((l, i));
4265 }
4266 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
4267 members.subs.push((l, i));
4268 }
4269 }
4270 }
4271 None => {
4272 let l = self.index(lane).expect("the placement was found on it");
4273 if sub {
4274 members.subs.push((l, idx));
4275 } else {
4276 members.clips.push((l, idx));
4277 }
4278 }
4279 }
4280 Some(members)
4281 }
4282
4283 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4284 /// new group, pushing everything from there on later by its length in
4285 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4286 /// the clip it lands in is split around it; past the end of the timeline it
4287 /// goes down where it was asked for, with black in front of it -- which is
4288 /// what a library row let go on the open bed means, and what the ghost under
4289 /// the pointer promised. A clipboard means "put it here", not "here and
4290 /// black in front", and clamps to the end at its own door
4291 /// ([`crate::PlaybackSession::paste_at`]).
4292 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4293 ///
4294 /// `V1` and `A1` and no other lane, because a take is one picture and one
4295 /// sound: copying it onto every lane there is would play the same audio
4296 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4297 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4298 /// video lane it is a clip that decodes to nothing, and a save carrying one
4299 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4300 /// `V1` only, for the mirror of that reason. The room is still opened on
4301 /// every media lane, or the lanes it was not inserted into would slide out
4302 /// of step with the ones it was -- and the subtitle lanes are left alone:
4303 /// the words keep their own clock, and a caption that should travel with a
4304 /// clip is what a group is for.
4305 ///
4306 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4307 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4308 /// an empty `clip` and for one naming a source that is not there (both of
4309 /// which the public fields let a caller build), and for a paste whose ripple
4310 /// would push a clip past the last frame there is -- nothing is changed by
4311 /// any of them.
4312 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4313 let Some(source) = self.sources.get(clip.source) else {
4314 return false;
4315 };
4316 if clip.out_frame <= clip.in_frame {
4317 return false;
4318 }
4319 let audio_only = crate::is_audio(&source.path);
4320 // ...and its mirror: a still is a picture and no sound, so a copy of one
4321 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4322 // worker tries to demux -- which silences the *whole session*, not just
4323 // that clip -- and a save the engine's own `open_project` then refuses.
4324 let picture_only = crate::is_image(&source.path);
4325 // The frame it was asked for and no other: a row let go on the empty
4326 // bed past the last clip lands *there*, under the ghost that promised
4327 // it, with black in front. Clamping to the end here made every drop on
4328 // open bed an append -- the clipboard's rule, applied to a hand that
4329 // had named a place.
4330 let at = timeline_frame;
4331 // The room it takes on the timeline, which its speed decides -- not the
4332 // source range it reads.
4333 let len = clip.frames();
4334 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4335 // hand-written file may hold a clip that ends at the very last frame
4336 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4337 // rather than wrapped there -- a wrapped start lands *behind* the clip
4338 // it belongs after, which is an overlap no save will read back.
4339 if at.checked_add(len).is_none()
4340 || self
4341 .lanes
4342 .iter()
4343 .flat_map(|l| &l.clips)
4344 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4345 {
4346 return false;
4347 }
4348 // ...and room *to open*: the paste splits whatever it lands inside of,
4349 // and a speeded clip can only be cut where its own rate has a source
4350 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4351 // of one, which is the overlap a lane may never hold. At real time every
4352 // frame answers, so this cannot refuse an unspeeded paste.
4353 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4354 if self
4355 .lanes
4356 .iter()
4357 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4358 {
4359 return false;
4360 }
4361 self.snapshot();
4362 let clip = Clip {
4363 fade_in: 0,
4364 fade_out: 0,
4365 transition_out: 0,
4366 start: at,
4367 link: Some(self.new_link()),
4368 ..clip
4369 };
4370 // Only lanes that can play the source: a file with no picture belongs on
4371 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4372 // it for an import. On a video lane it would decode to nothing, and the
4373 // save it wrote would not open again.
4374 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4375 (true, _) => &[LaneKind::Audio],
4376 (_, true) => &[LaneKind::Video],
4377 _ => &[LaneKind::Video, LaneKind::Audio],
4378 };
4379 let takes: Vec<usize> = kinds
4380 .iter()
4381 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4382 .collect();
4383 for (i, data) in self.lanes.iter_mut().enumerate() {
4384 open_room(&mut data.clips, at, len);
4385 // The subtitle lanes are NOT touched: a paste inserts media, and
4386 // the words keep their own clock. Opening room here used to split
4387 // a caption the paste landed inside and slide the rest behind it
4388 // -- "a caption that stayed put while the picture moved on no
4389 // longer says the same thing" -- but a caption pinned to nothing
4390 // (and a video arriving on a timeline of words alone) has no
4391 // picture to follow, and the split did to the words what no hand
4392 // asked for. A caption that should travel with a clip is what a
4393 // group is for, and a group moves as one.
4394 if takes.contains(&i) {
4395 let idx = data.clips.partition_point(|c| c.start < at);
4396 data.clips.insert(idx, clip);
4397 }
4398 debug_assert!(sorted_disjoint(&data.clips));
4399 debug_assert!(subs_sorted_disjoint(&data.subs));
4400 }
4401 true
4402 }
4403
4404 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
4405 /// `items` lands on the lane it names, its head moved by the offset every
4406 /// other item moves by too -- `at` less the earliest `start` among them,
4407 /// so the set's own gaps and lane assignment survive the trip from
4408 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
4409 /// way a lone clip's copy does.
4410 ///
4411 /// All-or-nothing, and **refused** rather than opening room or splitting
4412 /// a neighbour the way [`paste`](Project::paste) does for one clip:
4413 /// a set-paste never ripples the bed, so a landing that overlaps so much
4414 /// as one existing clip on its own lane refuses the whole set, changing
4415 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
4416 /// clamps instead of refusing, but a paste has no drag to clamp against,
4417 /// and a landing moved off the frame asked for is not what a paste means.
4418 /// `items` empty, naming a lane or a source that is not there, or a clip
4419 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
4420 ///
4421 /// Exactly one history snapshot for the whole set, so one
4422 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
4423 /// on every lane an item lands on: the caller must reseek.
4424 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
4425 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
4426 return false;
4427 };
4428 // Resolved once, up front, off the lanes as they stand now: a lane or
4429 // source that is not there, or a landing that would overlap a
4430 // neighbour, refuses the whole set before any of it is written.
4431 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
4432 for &(lane, clip) in items {
4433 let Some(li) = self.index(lane) else {
4434 return false;
4435 };
4436 if self.sources.get(clip.source).is_none() || clip.out_frame <= clip.in_frame {
4437 return false;
4438 }
4439 let delta = i64::from(clip.start) - i64::from(anchor);
4440 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
4441 return false;
4442 };
4443 let Some(end) = start.checked_add(clip.frames()) else {
4444 return false;
4445 };
4446 if self.lanes[li]
4447 .clips
4448 .iter()
4449 .any(|c| c.start < end && start < c.end())
4450 {
4451 return false;
4452 }
4453 landings.push((li, Clip { start, ..clip }));
4454 }
4455 self.snapshot();
4456 for (li, mut clip) in landings {
4457 clip.link = Some(self.new_link());
4458 clip.fade_in = 0;
4459 clip.fade_out = 0;
4460 clip.transition_out = 0;
4461 let clips = &mut self.lanes[li].clips;
4462 let idx = clips.partition_point(|c| c.start < clip.start);
4463 clips.insert(idx, clip);
4464 }
4465 true
4466 }
4467
4468 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4469 /// silence, and nothing else moves. Refused only for an out-of-range index
4470 /// (which a lane that is not there always is) -- lifting the last placement
4471 /// there is leaves an *empty* timeline, which is a state the project holds
4472 /// like any other and an undo brings back.
4473 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4474 if idx >= self.lane(lane).len() {
4475 return false;
4476 }
4477 self.snapshot();
4478 self.lane_mut(lane).expect("checked above").remove(idx);
4479 true
4480 }
4481
4482 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4483 /// the hole: everything after slides back by `len`. The rippling delete --
4484 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4485 /// empty range; a delete that leaves nothing behind empties the timeline,
4486 /// which is a state like any other and one undo away.
4487 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4488 if len == 0 {
4489 return false;
4490 }
4491 // Nothing reaches past `at`: there is nothing to cut and nothing to
4492 // slide back, and a delete that changes nothing must not cost an undo
4493 // step (see [`snapshot`](Project::snapshot)).
4494 if !self
4495 .lanes
4496 .iter()
4497 .flat_map(|l| &l.clips)
4498 .any(|c| c.end() > at)
4499 {
4500 return false;
4501 }
4502 self.snapshot();
4503 let on = all_lanes(&self.lanes);
4504 ripple(&mut self.lanes, &on, at, len);
4505 true
4506 }
4507
4508 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
4509 /// a right-click on empty bench space names before offering to close it.
4510 /// `None` when `frame` sits inside a placement, or past the last one: the
4511 /// open end of a lane is not a gap, since there is nothing after it to slide
4512 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
4513 /// the media [`Clip`] list they deliberately never hold.
4514 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
4515 let data = self.index(lane).map(|i| &self.lanes[i])?;
4516 match data.kind {
4517 LaneKind::Subtitle => gap(&data.subs, frame),
4518 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
4519 }
4520 }
4521
4522 /// How many bounded holes `lane` holds. The open end after the last
4523 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
4524 /// it would move nothing.
4525 pub fn gap_count(&self, lane: Lane) -> usize {
4526 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
4527 return 0;
4528 };
4529 match data.kind {
4530 LaneKind::Subtitle => gaps(&data.subs).len(),
4531 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
4532 }
4533 }
4534
4535 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4536 /// together to keep sync -- what a right-click on empty bench space asks
4537 /// before the menu offers to close it, and what widens
4538 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
4539 /// named to the whole take the gap might be half of.
4540 ///
4541 /// A clip bordering the gap on `lane` -- the one ending where it starts,
4542 /// the one starting where it ends -- carries a link when it is one take
4543 /// with a clip on another lane. That lane joins the scope only when the
4544 /// *exact same* stretch is empty there too (same start, same length): the
4545 /// ripple then removes nothing but silence, on every lane it touches, and
4546 /// both halves stay the length they always were. A link whose partner
4547 /// lane is not empty there -- a gap of a different length, or none at all
4548 /// -- is named back to the caller rather than silently widened past
4549 /// (which would cut real media out of a lane nothing asked to touch) or
4550 /// silently left out (which is the defect this closes: a per-lane ripple
4551 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
4552 /// to refuse it after the fact, on the very half this could have carried
4553 /// along).
4554 ///
4555 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
4556 /// partner clip sits on another lane -- the unlinked case, untouched.
4557 ///
4558 /// Subtitle lanes have no media take halves to inspect. A caption can be
4559 /// hand-grouped with clips, but it is not the imported A/V take this method
4560 /// widens for, so a subtitle gap stays scoped to its own lane; the later
4561 /// scoped cut still refuses an explicit group split.
4562 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4563 let Some(li) = self.index(lane) else {
4564 return Err("no track to work on".into());
4565 };
4566 let labels = handles(&self.lanes);
4567 let end = start + frames;
4568 let mut scope = vec![lane];
4569 for c in self.lanes[li]
4570 .clips
4571 .iter()
4572 .filter(|c| c.end() == start || c.start == end)
4573 {
4574 let Some(id) = c.link else { continue };
4575 for (j, data) in self.lanes.iter().enumerate() {
4576 if j == li {
4577 continue;
4578 }
4579 let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else {
4580 continue;
4581 };
4582 match gap(&data.clips, start) {
4583 Some((s, f)) if s == start && f == frames => {
4584 let other = labels[j];
4585 if !scope.contains(&other) {
4586 scope.push(other);
4587 }
4588 }
4589 _ => {
4590 return Err(format!(
4591 "the {} clip at frame {} is one take with the {} clip at frame {}: \
4592 closing this gap alone would pull the take out of sync -- close {}'s \
4593 gap there too, or detach them first",
4594 labels[li].label(),
4595 c.start,
4596 labels[j].label(),
4597 half.start,
4598 labels[j].label()
4599 )
4600 .into());
4601 }
4602 }
4603 }
4604 }
4605 Ok(scope)
4606 }
4607
4608 /// Close every bounded gap on `lane`, as one undo step, without making the
4609 /// lane's scope global. Media lanes use the same take-safety widening
4610 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
4611 /// halves ride along only when their matching lane is empty over that exact
4612 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
4613 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
4614 /// halves of an imported A/V take, so the media take-widening rule has
4615 /// nothing to add there.
4616 ///
4617 /// The walk is back-to-front. Closing a gap shifts everything after it, so
4618 /// later holes must be consumed while their measured starts are still true;
4619 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
4620 /// only before the first successful close, so an all-skipped sweep is not an
4621 /// undo step.
4622 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4623 let Some(i) = self.index(lane) else {
4624 return Err("no track to work on".into());
4625 };
4626 if self.lanes[i].kind == LaneKind::Subtitle {
4627 return Ok(self.close_all_subtitle_gaps_on_lane(i));
4628 }
4629 let mut report = GapSweep::default();
4630 let mut snapshot = false;
4631 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
4632 match self.gap_take_scope(lane, start, frames).and_then(|scope| {
4633 let on = self.scoped(&scope)?;
4634 self.scope_holds_takes_whole(&on, start)?;
4635 Ok(on)
4636 }) {
4637 Ok(on) => {
4638 if !snapshot {
4639 self.snapshot();
4640 snapshot = true;
4641 }
4642 ripple(&mut self.lanes, &on, start, frames);
4643 report.closed += 1;
4644 }
4645 Err(e) => report.skipped.push(GapSkip {
4646 start,
4647 reason: e.to_string(),
4648 }),
4649 }
4650 }
4651 report.skipped.reverse();
4652 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4653 Ok(report)
4654 }
4655
4656 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
4657 /// take-scope widening: a caption is not one half of an A/V take. Explicit
4658 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
4659 /// so a grouped caption is refused rather than pulled away from its group.
4660 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
4661 let mut report = GapSweep::default();
4662 let mut snapshot = false;
4663 let on = [i];
4664 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
4665 match self.scope_holds_takes_whole(&on, start) {
4666 Ok(()) => {
4667 if !snapshot {
4668 self.snapshot();
4669 snapshot = true;
4670 }
4671 ripple(&mut self.lanes, &on, start, frames);
4672 report.closed += 1;
4673 }
4674 Err(e) => report.skipped.push(GapSkip {
4675 start,
4676 reason: e.to_string(),
4677 }),
4678 }
4679 }
4680 report.skipped.reverse();
4681 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4682 report
4683 }
4684
4685 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4686 /// out of the lanes in `scope` and close each hole, as one edit: the
4687 /// jumpcut a silence scan asks for ([`crate::silence`]).
4688 ///
4689 /// A lane that is not in `scope` **does not move**, which is the whole
4690 /// point of the parameter: the silences of a podcast track come out
4691 /// without the music track under it sliding. `scope` is an arbitrary set of
4692 /// lanes and not a kind or a range, so a caller with its own idea of what
4693 /// is selected (a take, a track, everything) says it in lanes and nothing
4694 /// here has to learn about selection.
4695 ///
4696 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4697 /// reason this exists rather than a caller's loop over
4698 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4699 /// undo press, not forty. Cut back to front, so a region's frames still
4700 /// mean what the caller measured while the ones before it are cut.
4701 ///
4702 /// The list is sorted and overlapping entries are merged before anything is
4703 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4704 /// other's frames. Refused, with no undo step, for an empty list, for a
4705 /// scope naming no lane that is there, and -- by name -- when the scope
4706 /// would take one half of a take with it
4707 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4708 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4709 let regions = tidy(regions);
4710 let on = self.scoped(scope)?;
4711 let Some(&(first, _)) = regions.first() else {
4712 return Err("nothing to cut".into());
4713 };
4714 self.scope_holds_takes_whole(&on, first)?;
4715 self.snapshot();
4716 for &(at, len) in regions.iter().rev() {
4717 ripple(&mut self.lanes, &on, at, len);
4718 }
4719 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4720 Ok(())
4721 }
4722
4723 /// The storage indices of `scope`, which is what every batch below walks.
4724 /// `Err` for a scope that names nothing there rather than a silent no-op:
4725 /// an edit asked for on a lane that is not there did not happen, and the
4726 /// caller has to hear so.
4727 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4728 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4729 match on.is_empty() {
4730 true => Err("no track to work on".into()),
4731 false => Ok(on),
4732 }
4733 }
4734
4735 /// The law a scoped ripple lives under: **a group travels as one**, so a
4736 /// batch that moves one half of a take and not the other would leave the
4737 /// halves disagreeing about where they stand -- an offset no hand asked
4738 /// for, and the reason the take's lanes have to be scoped together.
4739 ///
4740 /// Refused by name rather than widened silently. Widening would edit a
4741 /// track the user did not scope, which is exactly the surprise scoping
4742 /// exists to end; a front-end that wants the take is free to *say* the
4743 /// take's lanes, and to name them in what it tells the user afterwards.
4744 ///
4745 /// Only from `from` on: a take sitting entirely before the first cut does
4746 /// not move, so it is not this rule's business.
4747 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4748 let labels = handles(&self.lanes);
4749 // The halves of a group are on either of a lane's lists, and the
4750 // refusal names whichever sits outside the scope -- a clip like it
4751 // always has, and a caption now that a group may hold one.
4752 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4753 let Some(id) = link else {
4754 return Ok(());
4755 };
4756 for (j, data) in self.lanes.iter().enumerate() {
4757 if on.contains(&j) {
4758 continue;
4759 }
4760 let clip = data.clips.iter().find(|o| o.link == Some(id));
4761 let sub = data.subs.iter().find(|s| s.link == Some(id));
4762 if let Some(half) = clip {
4763 return Err(format!(
4764 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4765 moving one track of a take would pull it apart -- take the whole take, \
4766 or detach them first",
4767 labels[j].label(),
4768 half.start
4769 )
4770 .into());
4771 }
4772 if let Some(half) = sub {
4773 return Err(format!(
4774 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4775 moving one track of a take would pull it apart -- take the whole take, \
4776 or detach them first",
4777 labels[j].label(),
4778 half.start
4779 )
4780 .into());
4781 }
4782 }
4783 Ok(())
4784 };
4785 for &i in on {
4786 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4787 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4788 }
4789 // A caption before the first cut does not move, so it is not this
4790 // rule's business -- exactly the clip test's own line.
4791 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4792 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4793 }
4794 }
4795 Ok(())
4796 }
4797
4798 /// Play every one of `regions` at `speed` instead of cutting it: each is
4799 /// split out of whatever covers it, re-rated, and the room it no longer
4800 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4801 /// does not ripple, and a hole where a silence shrank is the one thing this
4802 /// must not leave. One snapshot for the lot, like
4803 /// [`cut_regions`](Project::cut_regions).
4804 ///
4805 /// The rate is **absolute**, not a multiplier on what is there: running it
4806 /// twice over the same stretch leaves it at `speed`, not at `speed`
4807 /// squared, so a second pass over an already-cut timeline changes nothing.
4808 ///
4809 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4810 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4811 ///
4812 /// Refused by name, with nothing changed and no undo step, when:
4813 ///
4814 /// * the scope would take one half of a take with it
4815 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4816 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4817 /// shrink by different amounts and the ripple would pull them apart,
4818 /// which is what cutting does not suffer and why delete mode has no such
4819 /// refusal;
4820 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4821 /// piece could not be split out exactly;
4822 /// * two lanes' pieces would end up different lengths, which is a group
4823 /// whose halves disagree about their span (the refusal
4824 /// [`write_speed`](Project::write_speed) already makes, in its words);
4825 /// * the region would grow rather than shrink, i.e. it already plays faster
4826 /// than `speed`.
4827 pub fn speed_regions(
4828 &mut self,
4829 regions: &[(u32, u32)],
4830 speed: Speed,
4831 scope: &[Lane],
4832 ) -> crate::Result<()> {
4833 let regions = tidy(regions);
4834 let on = self.scoped(scope)?;
4835 let Some(&(first, _)) = regions.first() else {
4836 return Err("nothing to speed up".into());
4837 };
4838 self.scope_holds_takes_whole(&on, first)?;
4839 let labels = handles(&self.lanes);
4840 // Before anything is touched, because this is the refusal a person can
4841 // act on: a clip that laps over the edge of a silence has to be trimmed
4842 // (or the silences cut instead), and saying so after a rollback would
4843 // be saying it about a timeline that already looks different.
4844 for &(at, len) in &regions {
4845 for &l in &on {
4846 for c in &self.lanes[l].clips {
4847 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4848 {
4849 return Err(format!(
4850 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4851 speeding it up would pull the lanes apart -- trim it first, or cut the \
4852 silences out instead",
4853 labels[l].label(),
4854 c.start,
4855 at + len
4856 )
4857 .into());
4858 }
4859 }
4860 }
4861 }
4862 // The rest is checked as it is built: a split's own arithmetic is what
4863 // says whether a rate can address an edge. So the snapshot is taken
4864 // first and *rolled back* on a refusal -- one undo either way, and a
4865 // refusal still costs no step (`undo` pops the one just pushed).
4866 self.snapshot();
4867 for &(at, len) in regions.iter().rev() {
4868 self.write_split(at, false, &on);
4869 self.write_split(at + len, false, &on);
4870 let mut room: Option<(Lane, u32)> = None;
4871 let mut refused = None;
4872 for &l in &on {
4873 let clips = &self.lanes[l].clips;
4874 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4875 if (c.start, c.end()) != (at, at + len) {
4876 // *Which* edge did not come off: a rate that cannot
4877 // address the end of the silence is not a rate that
4878 // cannot address its start, and naming the wrong frame
4879 // sends the user looking in the wrong place.
4880 let edge = match c.start == at {
4881 true => at + len,
4882 false => at,
4883 };
4884 refused = Some(format!(
4885 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4886 detach it, or put it back to 1.00x first",
4887 labels[l].label(),
4888 c.start,
4889 c.speed
4890 ));
4891 continue;
4892 }
4893 let after = speed.frames(c.len());
4894 match room {
4895 None => room = Some((labels[l], after)),
4896 Some((first, n)) if n != after => {
4897 refused = Some(format!(
4898 "at {speed} the {} half of the silence at frame {at} would cover \
4899 {after} frames and the {} half {n}: they are one take and a take \
4900 is one span -- detach them first",
4901 labels[l].label(),
4902 first.label()
4903 ));
4904 }
4905 Some(_) => {}
4906 }
4907 }
4908 }
4909 let shrunk = match (refused, room) {
4910 (Some(e), _) => {
4911 self.undo();
4912 return Err(e.into());
4913 }
4914 // A gap on every lane: nothing to re-rate, and nothing to close.
4915 (None, None) => continue,
4916 (None, Some((_, after))) => after,
4917 };
4918 // The region's new length, on every scoped lane alike.
4919 let after = shrunk;
4920 let Some(delta) = len.checked_sub(shrunk) else {
4921 self.undo();
4922 return Err(format!(
4923 "the silence at frame {at} already plays faster than {speed}: \
4924 at that rate it would be {shrunk} frames instead of {len}"
4925 )
4926 .into());
4927 };
4928 for &l in &on {
4929 for c in &mut self.lanes[l].clips {
4930 if c.start == at && c.end() == at + len {
4931 c.speed = speed;
4932 } else if c.start >= at + len {
4933 c.start -= delta;
4934 }
4935 }
4936 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4937 // The captions on a scoped lane travel with the region's time:
4938 // a piece inside it plays in `after` frames instead of `len`
4939 // -- same words on less timeline, its window untouched, for
4940 // [`write_speed`]'s reason -- and everything behind the region
4941 // slides up by what the region gave back.
4942 //
4943 // The pieces inside re-time by their *boundaries*, not each
4944 // on its own: rounding one piece's start and its neighbour's
4945 // start apart can land both on the same frame (two one-frame
4946 // cues of a thirty-frame region at 2x both want frame 15), so
4947 // the mapped boundaries are walked in order and forced apart
4948 // -- each piece at least one frame, none past the region's own
4949 // new end, where the first follower lands exactly. A rounding
4950 // artifact is clamped, not refused: nothing about the words
4951 // asked for an overlap.
4952 let share = f64::from(after) / f64::from(len).max(1.);
4953 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4954 let mut prev = at;
4955 let subs = &mut self.lanes[l].subs;
4956 for i in 0..subs.len() {
4957 let s = subs[i];
4958 if s.start >= at + len {
4959 subs[i].start = s.start - delta;
4960 } else if s.start >= at && s.end() <= at + len {
4961 let mut start = map(s.start).max(prev);
4962 let end = map(s.end()).max(start + 1).min(at + after);
4963 start = start.min(end - 1);
4964 subs[i].start = start;
4965 subs[i].frames = end - start;
4966 prev = end;
4967 }
4968 }
4969 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4970 }
4971 }
4972 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4973 Ok(())
4974 }
4975
4976 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4977 /// -- the whole-group delete a single-lane front-end means. `false` for a
4978 /// bad index. Changes the mapping: the caller must reseek.
4979 pub fn delete(&mut self, idx: usize) -> bool {
4980 self.delete_in(Lane::V1, idx)
4981 }
4982
4983 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4984 /// in no group (or a group of one, which is the same thing to a delete) is
4985 /// what it always was: its own span cut out of *every* lane, so the
4986 /// timeline closes up under it. A clip in a group takes the group with it,
4987 /// each member by its **own** span and on its **own** lane -- the members
4988 /// keep their offsets, so their spans may disagree, and the lanes may end
4989 /// up out of step with each other, which is inherent to a hand-built group
4990 /// and one undo away. Every member -- clips and captions alike -- goes by
4991 /// the same law: its own span out of its own lane, hole closed; a caption
4992 /// in no group keeps the lift that leaves a gap, which is its own door's
4993 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4994 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4995 /// index, and for a lane that is not there. Changes the mapping: the
4996 /// caller must reseek.
4997 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4998 let Some(members) = self.group_of(lane, idx) else {
4999 return false;
5000 };
5001 if !members.alone() {
5002 return self.delete_members(&members);
5003 }
5004 let Some(clip) = self.lane(lane).get(idx).copied() else {
5005 return false;
5006 };
5007 self.ripple_delete(clip.start, clip.frames())
5008 }
5009
5010 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
5011 /// caption in no group lifts, exactly as its own key always made it
5012 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
5013 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
5014 /// span out of its own lane, hole closed, captions and clips alike.
5015 /// `false` for a bad index.
5016 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
5017 let Some(members) = self.group_of(lane, idx) else {
5018 return false;
5019 };
5020 if !members.alone() {
5021 return self.delete_members(&members);
5022 }
5023 self.lift_sub(lane, idx)
5024 }
5025
5026 /// The one whole-group delete both doors land in: every member's own span
5027 /// cut out of its own lane and the hole closed there -- clips and
5028 /// captions by the same law -- and nothing else on another lane moves,
5029 /// which is what keeps one member's ripple from dragging another
5030 /// member's lane out from under it. One snapshot, one undo step.
5031 fn delete_members(&mut self, members: &Members) -> bool {
5032 self.snapshot();
5033 for &(l, i) in &members.clips {
5034 let c = self.lanes[l].clips[i];
5035 ripple(&mut self.lanes, &[l], c.start, c.frames());
5036 }
5037 // The captions go by the same law their clip siblings do -- the span
5038 // out of its own lane, the hole closed -- and not by the lift a
5039 // *lone* caption's delete is: deleted with its group, the words after
5040 // it slide up with everything else, or the lane the group emptied is
5041 // the one lane the delete left a hole in. `ripple` is the one
5042 // mechanism (it clears the span and shifts the rest, clips and
5043 // captions alike); a sub lane holds no clips, so its other list is
5044 // untouched.
5045 for &(l, i) in &members.subs {
5046 let s = self.lanes[l].subs[i];
5047 ripple(&mut self.lanes, &[l], s.start, s.frames);
5048 }
5049 debug_assert!(links_are_consistent(&self.lanes).is_ok());
5050 true
5051 }
5052
5053 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
5054 #[cfg(test)]
5055 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
5056 self.lane(lane)
5057 }
5058
5059 /// How many undo steps are stacked: what the sweep asks so "one op, one
5060 /// snapshot" is a count and not a guess.
5061 #[cfg(test)]
5062 pub(crate) fn history_len(&self) -> usize {
5063 self.history.len()
5064 }
5065
5066 /// How many redo steps are stacked: what the sweep asks to check `undo`
5067 /// left a branch behind, and that a fresh edit clears it.
5068 #[cfg(test)]
5069 pub(crate) fn redo_len(&self) -> usize {
5070 self.redo.len()
5071 }
5072
5073 /// The project's own settings as they stand ([`ProjectSettings`]) -- what an
5074 /// undo entry holds beside the lanes, and what the session reads back after
5075 /// one is restored ([`crate::PlaybackSession::undo`]).
5076 pub(crate) fn settings_now(&self) -> ProjectSettings {
5077 self.settings.clone()
5078 }
5079
5080 /// One undo step for a change to the project's own settings: `from` is the
5081 /// state the change is from and `now` the one it leaves behind. The entry
5082 /// pushed holds `from`, while the copy kept here is `now` -- so the next
5083 /// lane edit's own entry carries the canvas and the rate really in force
5084 /// rather than the ones before the pick. The lanes the entry holds are the
5085 /// ones in place at the call: a settings door leaves them alone and may
5086 /// take this step after its change, and one that moves them
5087 /// ([`Project::retime`] on a rate change) takes it before, with `now` equal
5088 /// to `from`, mirroring the new state afterwards
5089 /// ([`Project::mirror_settings`]).
5090 pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) {
5091 self.settings = from;
5092 self.snapshot();
5093 self.settings = now;
5094 }
5095
5096 /// Keeps `now` as this project's copy of its own settings, without a step:
5097 /// the second half of a settings door that had to take its step before the
5098 /// change.
5099 pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) {
5100 self.settings = now;
5101 }
5102
5103 /// Every part of the project that an edit can change, as comparable
5104 /// values: what the sweep's undo round-trip asks "byte identical?" of.
5105 #[cfg(test)]
5106 pub(crate) fn parts(&self) -> SweepParts {
5107 SweepParts(
5108 self.sources.len(),
5109 self.lanes
5110 .iter()
5111 .map(|l| (l.kind, l.clips.clone()))
5112 .collect(),
5113 self.lanes.iter().map(|l| l.subs.clone()).collect(),
5114 self.subtitles.clone(),
5115 self.settings.clone(),
5116 )
5117 }
5118
5119 /// Restore everything from before the last successful edit -- the lanes,
5120 /// the subtitle palette and the project's own settings. `false` when there
5121 /// is nothing left to undo. Pushes what was just left onto the redo stack,
5122 /// so [`Project::redo`] can walk forward again.
5123 pub fn undo(&mut self) -> bool {
5124 match self.history.pop() {
5125 Some(prev) => {
5126 self.redo.push(Snapshot {
5127 lanes: std::mem::replace(&mut self.lanes, prev.lanes),
5128 subtitles: self.subtitles.clone(),
5129 settings: self.settings.clone(),
5130 });
5131 self.subtitles = prev.subtitles;
5132 self.settings = prev.settings;
5133 true
5134 }
5135 None => false,
5136 }
5137 }
5138
5139 /// Restore everything from before the last [`Project::undo`] -- the
5140 /// mirror of `undo`, walking the redo stack it fills. `false` when there
5141 /// is nothing left to redo, which is also true after any fresh edit: a
5142 /// new [`Project::snapshot`] clears the branch `undo` left behind.
5143 pub fn redo(&mut self) -> bool {
5144 match self.redo.pop() {
5145 Some(next) => {
5146 self.history.push(Snapshot {
5147 lanes: std::mem::replace(&mut self.lanes, next.lanes),
5148 subtitles: self.subtitles.clone(),
5149 settings: self.settings.clone(),
5150 });
5151 self.subtitles = next.subtitles;
5152 self.settings = next.settings;
5153 true
5154 }
5155 None => false,
5156 }
5157 }
5158
5159 /// The project an export renders from: everything a render reads, with the
5160 /// undo history left behind. An export never walks the history back, and
5161 /// cloning it costs a copy of every lane list in the session -- this is
5162 /// taken on the UI thread, so it clones the lanes and the sources alone.
5163 pub fn export_snapshot(&self) -> Self {
5164 Self {
5165 sources: self.sources.clone(),
5166 lanes: self.lanes.clone(),
5167 eq: self.eq.clone(),
5168 color: self.color.clone(),
5169 transform: self.transform.clone(),
5170 history: Vec::new(),
5171 redo: Vec::new(),
5172 next_link: self.next_link,
5173 subtitles: self.subtitles.clone(),
5174 settings: self.settings.clone(),
5175 }
5176 }
5177
5178 /// Half-open `(source, start, end)` segments in *source* seconds, from
5179 /// `timeline_frame` to the end of the timeline -- the play list for the
5180 /// audio worker, read off **`A1`**. A `None` source is a gap: the
5181 /// worker synthesises that many seconds of silence, which is what keeps the
5182 /// audio master clock counting across a hole instead of stalling on it.
5183 /// The first entry is partial when the position is mid-clip. Empty when the
5184 /// position is past the end or `fps` is not usable.
5185 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
5186 self.lane_segments_from(Lane::A1, timeline_frame, fps)
5187 }
5188
5189 /// [`segments_from`](Project::segments_from) for a named lane.
5190 pub fn lane_segments_from(
5191 &self,
5192 lane: Lane,
5193 timeline_frame: u32,
5194 fps: f64,
5195 ) -> Vec<(Option<usize>, f64, f64)> {
5196 if !(fps.is_finite() && fps > 0.0) {
5197 return Vec::new();
5198 }
5199 self.spans_from(lane, timeline_frame)
5200 .iter()
5201 .map(|span| match span.from {
5202 // A clip's window is in *source* seconds: where in the file it
5203 // reads from, which a delete before it never shifts. How many
5204 // source frames that is, is the span's own arithmetic -- at a
5205 // speed it is not the timeline length ([`Span::source_len`]).
5206 Some((source, in_frame)) => (
5207 Some(source),
5208 f64::from(in_frame) / fps,
5209 f64::from(in_frame + span.source_len()) / fps,
5210 ),
5211 // A gap has no file, so all it can say is how long it is.
5212 None => (None, 0.0, f64::from(span.len) / fps),
5213 })
5214 .collect()
5215 }
5216
5217 /// One play list per audio lane that *holds* something, in display order --
5218 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
5219 /// what an export asks how many lanes it would have to mix.
5220 ///
5221 /// Never empty: a timeline whose audio lanes are all empty (or which has no
5222 /// audio lane at all) still yields one all-gap list, so it plays silence
5223 /// against a master clock exactly as it did before there were lanes to
5224 /// count. Lanes with nothing on them are left out rather than mixed in as
5225 /// silence: they would cost a decode thread each and add zero.
5226 pub fn audio_segments_from(
5227 &self,
5228 timeline_frame: u32,
5229 fps: f64,
5230 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
5231 self.audio_lanes()
5232 .into_iter()
5233 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
5234 .collect()
5235 }
5236
5237 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
5238 /// builds a play list for, in the same order. Public because everything
5239 /// asked per audio lane -- which clip a segment's equalizer belongs to,
5240 /// which lane an mp4 export would copy -- has to read the very list the
5241 /// sound comes off, or the two answers drift apart (which is exactly how an
5242 /// `A2`-only project once exported silently, ledger).
5243 pub fn audio_lanes(&self) -> Vec<Lane> {
5244 let lanes: Vec<Lane> = self
5245 .lanes()
5246 .into_iter()
5247 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
5248 .collect();
5249 match lanes.is_empty() {
5250 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
5251 // no sound still plays silence against the master clock.
5252 true => vec![Lane::A1],
5253 false => lanes,
5254 }
5255 }
5256
5257 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
5258 /// segments plays at, and how long the timeline gives it: the same lanes in
5259 /// the same order, one entry per segment, `None` for a segment at real time
5260 /// -- which is every segment of a project nobody has speeded, and the path
5261 /// the audio worker leaves bit-identical.
5262 ///
5263 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
5264 /// the segment tuple is what every opener and a dozen tests speak, and a
5265 /// rate is not part of *which samples* a segment names.
5266 ///
5267 /// The seconds are what makes a resample exact: a segment's own window
5268 /// resolves to whole source frames, and dividing that by the rate would
5269 /// leave each clip a fraction of a frame short or long -- a drift that grows
5270 /// clip by clip. Told how much timeline it owes, the worker pads or trims
5271 /// the last few samples of each segment instead, so the sound stays locked
5272 /// to the picture however many speeded cuts it walks through.
5273 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
5274 self.audio_lanes()
5275 .into_iter()
5276 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
5277 .collect()
5278 }
5279
5280 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
5281 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5282 /// same walk, same `fps` refusal.
5283 pub fn lane_speeds_from(
5284 &self,
5285 lane: Lane,
5286 timeline_frame: u32,
5287 fps: f64,
5288 ) -> Vec<Option<Stretch>> {
5289 if !(fps.is_finite() && fps > 0.0) {
5290 return Vec::new();
5291 }
5292 self.spans_from(lane, timeline_frame)
5293 .iter()
5294 .map(|span| {
5295 (!span.speed.is_normal()).then(|| Stretch {
5296 step: span.speed.as_f64(),
5297 timeline_secs: f64::from(span.len) / fps,
5298 })
5299 })
5300 .collect()
5301 }
5302
5303 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
5304 /// segments plays through: the same lanes in the same order, one entry per
5305 /// segment, `None` where the segment is a gap or its clip plays flat.
5306 ///
5307 /// A parallel list rather than a fourth element of the segment tuple: that
5308 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
5309 /// and an effect is not part of *which samples* a segment names. A short
5310 /// list therefore means "flat from here on" rather than a length mismatch --
5311 /// see [`crate::AudioSession::open_mixed_streams_eq`].
5312 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
5313 self.audio_lanes()
5314 .into_iter()
5315 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
5316 .collect()
5317 }
5318
5319 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
5320 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5321 /// same walk, same `fps` refusal, so the two lists cannot come out different
5322 /// lengths.
5323 pub fn lane_eqs_from(
5324 &self,
5325 lane: Lane,
5326 timeline_frame: u32,
5327 fps: f64,
5328 ) -> Vec<Option<EqParams>> {
5329 if !(fps.is_finite() && fps > 0.0) {
5330 return Vec::new();
5331 }
5332 self.spans_from(lane, timeline_frame)
5333 .iter()
5334 // A span off a clip covers that clip's frames and no others, so its
5335 // own start names the clip -- the index a [`Span`] does not carry.
5336 .map(|span| {
5337 self.map(lane, span.start)
5338 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
5339 })
5340 .collect()
5341 }
5342
5343 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
5344 /// segments plays through: the same lanes in the same order, one entry per
5345 /// segment, `None` where the segment is a gap or its clip has neither a
5346 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
5347 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
5348 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
5349 self.audio_lanes()
5350 .into_iter()
5351 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
5352 .collect()
5353 }
5354
5355 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
5356 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
5357 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
5358 if !(fps.is_finite() && fps > 0.0) {
5359 return Vec::new();
5360 }
5361 self.spans_from(lane, timeline_frame)
5362 .iter()
5363 .map(|span| {
5364 let (idx, _) = self.map(lane, span.start)?;
5365 let clip = self.lane(lane).get(idx)?;
5366 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
5367 // `span.len` is the clip's own remaining frames from
5368 // `span.start` on -- shorter than `clip.frames()` only
5369 // when this is the first span of a seek mid-clip.
5370 elapsed: clip.frames().saturating_sub(span.len),
5371 fade_in: clip.fade_in,
5372 fade_out: clip.fade_out,
5373 total: clip.frames(),
5374 })
5375 })
5376 .collect()
5377 }
5378
5379 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
5380 /// it has decided it will succeed -- a refusal must not cost an undo step.
5381 /// Clears the redo stack: a fresh edit branches off from here, so whatever
5382 /// `undo` had left to redo is no longer where this edit leads back to.
5383 fn snapshot(&mut self) {
5384 if self.history.len() == HISTORY_CAP {
5385 self.history.remove(0);
5386 }
5387 self.history.push(Snapshot {
5388 lanes: self.lanes.clone(),
5389 subtitles: self.subtitles.clone(),
5390 settings: self.settings.clone(),
5391 });
5392 self.redo.clear();
5393 }
5394
5395 fn new_link(&mut self) -> u32 {
5396 let id = self.next_link;
5397 self.next_link = self.next_link.saturating_add(1);
5398 id
5399 }
5400}
5401
5402/// The handle of every lane, in storage order -- the one definition of what
5403/// [`Lane::ord`] counts.
5404fn handles(lanes: &[LaneData]) -> Vec<Lane> {
5405 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
5406 lanes
5407 .iter()
5408 .map(|l| match l.kind {
5409 LaneKind::Video => {
5410 video += 1;
5411 Lane::new(LaneKind::Video, video - 1)
5412 }
5413 LaneKind::Audio => {
5414 audio += 1;
5415 Lane::new(LaneKind::Audio, audio - 1)
5416 }
5417 LaneKind::Subtitle => {
5418 subtitle += 1;
5419 Lane::new(LaneKind::Subtitle, subtitle - 1)
5420 }
5421 })
5422 .collect()
5423}
5424
5425/// The one law a caption re-time scales by: frame `f` moves about the held
5426/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
5427/// commits it, [`Project::speeded_playhead`] previews it -- both build their
5428/// [`TimelineMap`] piece from this single answer so the two cannot drift
5429/// apart by a frame the way they once did.
5430fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
5431 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
5432 .round()
5433 .clamp(0., f64::from(u32::MAX)) as u32
5434}
5435
5436/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
5437/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
5438/// a speed cannot be applied twice or forgotten in one of them.
5439fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
5440 // Clamped inside the clip's own range: rounding at a slow rate can put the
5441 // last timeline frame of a clip a frame past its out-point, and a source
5442 // frame outside the range is one the next clip owns.
5443 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
5444}
5445
5446/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
5447/// finder generic makes the subtitle path use the same bounded-hole rules as
5448/// media lanes without teaching the media-specific take logic about captions.
5449trait GapPlacement {
5450 fn start_frame(&self) -> u32;
5451 fn end_frame(&self) -> u32;
5452}
5453
5454impl GapPlacement for Clip {
5455 fn start_frame(&self) -> u32 {
5456 self.start
5457 }
5458
5459 fn end_frame(&self) -> u32 {
5460 self.end()
5461 }
5462}
5463
5464impl GapPlacement for SubClip {
5465 fn start_frame(&self) -> u32 {
5466 self.start
5467 }
5468
5469 fn end_frame(&self) -> u32 {
5470 self.end()
5471 }
5472}
5473
5474/// Index of the placement covering `frame`, or `None` for a gap or past the
5475/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
5476fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
5477 let idx = items
5478 .partition_point(|item| item.start_frame() <= frame)
5479 .checked_sub(1)?;
5480 (frame < items[idx].end_frame()).then_some(idx)
5481}
5482
5483/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
5484/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
5485/// invariant like [`at`]: the first placement whose start is past `frame` is
5486/// the far wall, and the last one that ends at or before `frame` (or the
5487/// timeline's own head, `0`, when there is none) is the near one.
5488fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
5489 if at(items, frame).is_some() {
5490 return None;
5491 }
5492 let idx = items.partition_point(|item| item.start_frame() <= frame);
5493 let next = items.get(idx)?;
5494 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
5495 Some((start, next.start_frame() - start))
5496}
5497
5498/// Every bounded hole in `items`, left to right. The tail after the last
5499/// placement is deliberately absent: there is no later placement for a ripple
5500/// to bring back.
5501fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
5502 let mut out = Vec::new();
5503 let mut next = 0;
5504 for item in items {
5505 if item.start_frame() > next {
5506 out.push((next, item.start_frame() - next));
5507 }
5508 next = item.end_frame();
5509 }
5510 out
5511}
5512
5513/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
5514/// there would cut in two. A placement's own first frame is not inside it.
5515fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
5516 let idx = at(clips, frame)?;
5517 // ...and, on a speeded clip, one its rate can actually address
5518 // ([`Speed::split_at`]): a cut between two showings of one source frame
5519 // would leave halves that no longer add up to the clip that was cut.
5520 (frame > clips[idx].start)
5521 .then_some(idx)
5522 .filter(|&idx| split_source(&clips[idx], frame).is_some())
5523}
5524
5525/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
5526/// rate cannot address that frame.
5527fn split_source(c: &Clip, frame: u32) -> Option<u32> {
5528 c.speed
5529 .split_at(c.len(), frame - c.start)
5530 .map(|src| c.in_frame + src)
5531}
5532
5533/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
5534/// rejoin: they must touch there, and be consecutive frames of one source.
5535fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
5536 let idx = clips.iter().position(|c| c.end() == frame)?;
5537 let next = clips.get(idx + 1)?;
5538 let joined = clips[idx].len() + next.len();
5539 (next.start == frame
5540 && next.source == clips[idx].source
5541 && next.in_frame == clips[idx].out_frame
5542 // ...at one rate, and one that puts the rejoined clip back in exactly
5543 // the room the two took up: what a split could have produced, which is
5544 // all this undoes.
5545 && next.speed == clips[idx].speed
5546 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
5547 .then_some(idx)
5548}
5549
5550/// The lane invariant: sorted by `start`, no two placements overlapping, no
5551/// empty placement. Checked at every constructor and asserted after every
5552/// mutation -- the offset model is only tractable while it holds.
5553/// The one thing an equalizer setting may not be: a value the text format
5554/// cannot write and read back as itself. Checked wherever params come in, so
5555/// what an edit produces is always what a save writes and a load reads.
5556fn finite(params: &EqParams) -> bool {
5557 params
5558 .bands
5559 .iter()
5560 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
5561}
5562
5563/// The same for a colour grade: [`crate::color`] itself falls back to identity
5564/// on a non-finite value, but a value that cannot be written and read back as
5565/// itself has no business reaching the model.
5566fn color_finite(p: &ColorParams) -> bool {
5567 p.brightness.is_finite()
5568 && p.contrast.is_finite()
5569 && p.saturation.is_finite()
5570 && p.tint.is_finite()
5571}
5572
5573/// The same for a transform: [`crate::scale`] clamps a non-finite value to
5574/// identity at read time, but a value that cannot round-trip has no business
5575/// reaching the model.
5576fn transform_finite(p: &TransformParams) -> bool {
5577 p.pos_x.is_finite()
5578 && p.pos_y.is_finite()
5579 && p.scale.is_finite()
5580 && p.rotate.is_finite()
5581 && p.crop_l.is_finite()
5582 && p.crop_r.is_finite()
5583 && p.crop_t.is_finite()
5584 && p.crop_b.is_finite()
5585}
5586
5587fn sorted_disjoint(clips: &[Clip]) -> bool {
5588 clips.iter().all(|c| c.out_frame > c.in_frame)
5589 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
5590}
5591
5592/// The very same invariant on a subtitle lane, in that lane's own two units:
5593/// sorted by `start`, no two placements overlapping, no empty placement at
5594/// either end. Asserted after every mutation, exactly as its twin is.
5595fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
5596 subs.iter()
5597 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
5598 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
5599}
5600
5601/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
5602/// the one conversion between a lane's clock and a cue's, and `0` for a rate
5603/// that is not one (every caller of this has already refused such a rate).
5604fn us_of(frames: i64, fps: f64) -> i64 {
5605 match fps.is_finite() && fps > 0.0 {
5606 true => ((frames as f64) / fps * 1e6).round() as i64,
5607 false => 0,
5608 }
5609}
5610
5611/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5612/// dropping what is inside the hole, splitting what straddles it and trimming
5613/// what overlaps an edge. The windows follow the cut by proportion
5614/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5615fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5616 let mut out = Vec::with_capacity(subs.len() + 1);
5617 for s in subs.drain(..) {
5618 if s.end() <= start || s.start >= end {
5619 out.push(s);
5620 continue;
5621 }
5622 if s.start < start {
5623 out.push(SubClip {
5624 frames: start - s.start,
5625 out_us: s.window_at(start),
5626 // Both pieces lose the group id, for [`clear`]'s reason: one
5627 // id on two boxes of one lane is the one thing it may never
5628 // mean.
5629 link: None,
5630 ..s
5631 });
5632 }
5633 if s.end() > end {
5634 out.push(SubClip {
5635 start: end,
5636 frames: s.end() - end,
5637 in_us: s.window_at(end),
5638 link: None,
5639 ..s
5640 });
5641 }
5642 }
5643 *subs = out;
5644}
5645
5646/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5647/// `len`, splitting a placement that straddles `at` so the two halves end up on
5648/// either side of the hole. A `len` of 0 is that split alone, which is what a
5649/// [`Project::split`] over a subtitle lane is.
5650fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5651 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5652 let s = subs[idx];
5653 let cut = s.window_at(at);
5654 subs[idx] = SubClip {
5655 frames: at - s.start,
5656 out_us: cut,
5657 link: None,
5658 ..s
5659 };
5660 subs.insert(
5661 idx + 1,
5662 SubClip {
5663 start: at,
5664 frames: s.end() - at,
5665 in_us: cut,
5666 link: None,
5667 ..s
5668 },
5669 );
5670 }
5671 for s in subs.iter_mut().filter(|s| s.start >= at) {
5672 s.start += len;
5673 }
5674}
5675
5676/// [`joinable`] for a subtitle lane: the first of the two placements a
5677/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5678/// produced and nothing else -- they touch on the timeline, they read the same
5679/// track, and the second one's window carries on where the first's stopped.
5680fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5681 let idx = subs.iter().position(|s| s.end() == frame)?;
5682 let next = subs.get(idx + 1)?;
5683 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5684 .then_some(idx)
5685}
5686
5687/// How far one `edge` of the caption at `idx` may travel against its own lane's
5688/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5689/// rate, which a caption *following* a group's trim does not have to be exact
5690/// about -- its own walls, its own one surviving frame, and nothing that needs
5691/// a clock.
5692fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5693 let s = &subs[idx];
5694 match edge {
5695 Edge::Start => (idx.checked_sub(1).map_or(0, |p| subs[p].end()), s.end() - 1),
5696 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5697 }
5698}
5699
5700/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5701/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5702/// forwards and backwards. The caption a group's trim is carrying has no rate
5703/// of its own and needs none: what one frame of it is worth in microseconds is
5704/// the window it already shows over the frames it already takes.
5705fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5706 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5707 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5708 match edge {
5709 Edge::Start => {
5710 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5711 s.frames = s.end() - to;
5712 s.start = to;
5713 }
5714 Edge::End => {
5715 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5716 s.frames = to - s.start;
5717 }
5718 }
5719 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5720}
5721
5722/// The grouping invariant, checked in release at [`Project::from_parts`] and
5723/// asserted by the tests after every edit: a link id names **at most one**
5724/// placement per lane -- a clip on a media lane or a caption on a subtitle
5725/// one, whichever carries it. That is all "these move together" can mean now
5726/// that a group is assembled by hand: the members keep their own spans and
5727/// their own offsets, and what binds them is the id alone.
5728///
5729/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5730/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5731/// placements of one group may cover different frames -- the offset-preserving
5732/// group a hand builds with [`Project::group_all`], which a drag moves by one
5733/// delta rather than by one span.
5734///
5735/// A link no other lane carries is legal and is not an error: lifting one half
5736/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5737/// timeline has to load again.
5738/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5739/// asked by the sweep suite's universal law.
5740#[cfg(test)]
5741pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5742 links_are_consistent(&p.lanes)
5743}
5744
5745fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5746 let handles = handles(lanes);
5747 for (data, lane) in lanes.iter().zip(&handles) {
5748 for (i, c) in data.clips.iter().enumerate() {
5749 let Some(id) = c.link else { continue };
5750 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5751 return Err(
5752 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5753 );
5754 }
5755 }
5756 // ...and the same for the captions, in their own list on the same lane:
5757 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5758 // id could be doubled on.
5759 for (i, s) in data.subs.iter().enumerate() {
5760 let Some(id) = s.link else { continue };
5761 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5762 return Err(
5763 format!("link {id} names two captions in the {} lane", lane.label()).into(),
5764 );
5765 }
5766 }
5767 }
5768 Ok(())
5769}
5770
5771/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5772/// it go, one straddling it is split in two, one overlapping an edge is
5773/// trimmed. Source frames follow the trim, so what is left plays what it always
5774/// played. Leaves the lane sorted and disjoint.
5775///
5776/// A piece the hole cut is no longer the take its group id names -- and both
5777/// halves of a straddled placement carrying that id would be the same id twice
5778/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5779fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5780 let mut out = Vec::with_capacity(clips.len() + 1);
5781 for c in clips.drain(..) {
5782 // Disjoint from the hole: untouched.
5783 if c.end() <= start || c.start >= end {
5784 out.push(c);
5785 continue;
5786 }
5787 // The head that survives in front of the hole -- as much source as fits
5788 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5789 // which at real time is that room itself. Never *more*: a head that
5790 // outgrew its room would reach into the hole it is being cut out of,
5791 // which is exactly the overlap a slow clip punched at a frame its rate
5792 // cannot address used to leave (at 0.25x a single source frame is four
5793 // timeline frames, and three frames of room hold none of it). `None`
5794 // there means no remainder at all, and the piece simply goes.
5795 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5796 && c.start < start
5797 {
5798 out.push(Clip {
5799 fade_in: 0,
5800 fade_out: 0,
5801 transition_out: 0,
5802 out_frame: c.in_frame + keep.min(c.len()),
5803 link: None,
5804 ..c
5805 });
5806 }
5807 // ...and the tail behind it, which keeps reading up to where it would
5808 // have: measured from its out-point for the head's reason, so what it
5809 // occupies still ends where the whole clip did -- and dropped whole on
5810 // the same `None`.
5811 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5812 && c.end() > end
5813 {
5814 out.push(Clip {
5815 fade_in: 0,
5816 fade_out: 0,
5817 transition_out: 0,
5818 start: end,
5819 in_frame: c.out_frame - keep.min(c.len()),
5820 link: None,
5821 ..c
5822 });
5823 }
5824 }
5825 *clips = out;
5826}
5827
5828/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5829/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5830/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5831/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5832/// the caller.
5833fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5834 for &i in on {
5835 let clips = &mut lanes[i].clips;
5836 clear(clips, at, at + len);
5837 for c in clips.iter_mut().filter(|c| c.start >= at) {
5838 c.start -= len;
5839 }
5840 debug_assert!(sorted_disjoint(clips));
5841 // The subtitle lanes close the hole with everything else: a caption
5842 // left standing where the picture it belongs to was cut out is the
5843 // desync a lane model exists to make impossible.
5844 let subs = &mut lanes[i].subs;
5845 sub_clear(subs, at, at + len);
5846 for s in subs.iter_mut().filter(|s| s.start >= at) {
5847 s.start -= len;
5848 }
5849 debug_assert!(subs_sorted_disjoint(subs));
5850 }
5851}
5852
5853/// Every lane, as the index list the two above take: what "the whole timeline"
5854/// is spelled as, and the scope [`Project::ripple_delete`] and
5855/// [`Project::split`] have always had.
5856fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5857 (0..lanes.len()).collect()
5858}
5859
5860/// A caller's region list as a batch may use it: sorted by start, empty entries
5861/// dropped, and touching or overlapping entries merged into one.
5862///
5863/// Overlapping regions are the one thing a batch cannot take -- cutting the
5864/// second would cut frames the first already moved -- and a detector handing
5865/// back two that touch means one silence, not two cuts. Merged rather than
5866/// refused: this is arithmetic on a preview, not a user's mistake.
5867fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5868 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5869 sorted.sort_by_key(|&(at, _)| at);
5870 let mut out: Vec<(u32, u32)> = Vec::new();
5871 for (at, len) in sorted {
5872 let end = at.saturating_add(len);
5873 match out.last_mut() {
5874 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5875 _ => out.push((at, len)),
5876 }
5877 }
5878 out
5879}
5880
5881/// Slides everything from `at` on later by `len`, splitting a placement that
5882/// straddles `at` so the two halves end up on either side of the hole. The
5883/// insert half of a rippling paste. The two halves lose the group id for the
5884/// reason [`clear`] gives.
5885fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5886 if let Some(idx) = splittable(clips, at) {
5887 let mut tail = clips[idx];
5888 // The cut in *source* frames, at the clip's own rate. `splittable` has
5889 // already refused a frame the rate cannot address, which is why
5890 // [`Project::paste`] refuses one too rather than opening room inside a
5891 // clip that cannot be cut there.
5892 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5893 tail.start = at;
5894 tail.link = None;
5895 clips[idx].out_frame = tail.in_frame;
5896 clips[idx].link = None;
5897 clips.insert(idx + 1, tail);
5898 }
5899 for c in clips.iter_mut().filter(|c| c.start >= at) {
5900 c.start += len;
5901 }
5902}
5903
5904/// Absolute, symlink-resolved when the file is reachable; the path as given
5905/// when it is not -- an unreadable path still deserves an index, it simply
5906/// dedups by spelling.
5907pub(crate) fn canonical(path: &Path) -> PathBuf {
5908 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5909}
5910
5911#[cfg(test)]
5912mod tests {
5913 use super::*;
5914
5915 const FPS: f64 = 30.0;
5916 /// Never opened -- `Project` is pure data, so a path that does not exist is
5917 /// simply a path that dedups by spelling.
5918 const FILE: &str = "/nonexistent/a.mp4";
5919 const FILE2: &str = "/nonexistent/b.mp4";
5920
5921 /// A contiguous placement, group id ignored: what most assertions compare.
5922 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5923 Clip {
5924 fade_in: 0,
5925 fade_out: 0,
5926 transition_out: 0,
5927 visualizer: 0,
5928 viz_paint: 0,
5929 start,
5930 in_frame,
5931 out_frame,
5932 source,
5933 link: None,
5934 eq: None,
5935 color: None,
5936 transform: None,
5937 fit: FitPolicy::default(),
5938 speed: Speed::NORMAL,
5939 }
5940 }
5941
5942 /// A caption placement for pure timeline tests: the track window is the
5943 /// same duration as the placement, so assertions can stay in frames.
5944 fn caption(start: u32, frames: u32) -> SubClip {
5945 SubClip {
5946 start,
5947 frames,
5948 track: 0,
5949 in_us: 0,
5950 out_us: i64::from(frames) * 1_000_000,
5951 link: None,
5952 }
5953 }
5954
5955 /// A subtitle palette row for tests that place captions on lanes.
5956 fn subtitle_track() -> SubtitleTrack {
5957 SubtitleTrack {
5958 path: FILE.into(),
5959 track: None,
5960 language: "eng".into(),
5961 name: String::new(),
5962 label: "eng".into(),
5963 cues: Vec::new(),
5964 bitmap: false,
5965 refused: None,
5966 }
5967 }
5968
5969 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5970 /// apart -- which is what makes the table's dedup and its prune visible.
5971 fn band_at(n: u32) -> EqParams {
5972 EqParams {
5973 bands: vec![crate::eq::Band {
5974 freq_hz: 1000.0,
5975 gain_db: f64::from(n) as f32 * 1.5,
5976 q: 0.707,
5977 kind: crate::eq::BandKind::Peak,
5978 }],
5979 }
5980 }
5981
5982 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5983 /// for the colour table.
5984 fn grade_at(n: u32) -> ColorParams {
5985 ColorParams {
5986 brightness: f64::from(n) as f32 * 0.05,
5987 ..Default::default()
5988 }
5989 }
5990
5991 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5992 /// twin for the transform table.
5993 fn transform_at(n: u32) -> TransformParams {
5994 TransformParams {
5995 pos_x: f64::from(n) as f32 * 0.05,
5996 ..Default::default()
5997 }
5998 }
5999
6000 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
6001 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
6002 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
6003 }
6004
6005 /// Every lane with its group ids blanked, for comparing shape.
6006 fn shape(p: &Project) -> Vec<Vec<Clip>> {
6007 p.lanes()
6008 .into_iter()
6009 .map(|l| {
6010 p.lane(l)
6011 .iter()
6012 .map(|c| Clip { link: None, ..*c })
6013 .collect()
6014 })
6015 .collect()
6016 }
6017
6018 /// The *source frame* every timeline frame reads, per lane -- the traversal
6019 /// a player performs. Deliberately not the clip index: a split changes which
6020 /// clip a frame belongs to, and nothing else.
6021 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
6022 (0..p.timeline_frames() + 2)
6023 .map(|f| {
6024 p.lanes()
6025 .into_iter()
6026 .map(|l| p.map(l, f).map(|(_, source)| source))
6027 .collect()
6028 })
6029 .collect()
6030 }
6031
6032 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
6033 /// fixture. Built through `split` so the constructor path is exercised too.
6034 fn three() -> Project {
6035 let mut p = Project::single(FILE, 9);
6036 assert!(p.split(3));
6037 assert!(p.split(5));
6038 assert_eq!(
6039 shape(&p),
6040 [
6041 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
6042 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
6043 ]
6044 );
6045 p
6046 }
6047
6048 #[test]
6049 fn single_is_the_whole_file_on_both_lanes() {
6050 let p = Project::single(FILE, 150);
6051 assert_eq!(p.clips().len(), 1);
6052 assert_eq!(p.lane(Lane::A1).len(), 1);
6053 assert_eq!(p.timeline_frames(), 150);
6054 assert_eq!(p.clip_spans(), vec![(0, 150)]);
6055 // grouped: video and audio carry the same link
6056 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
6057 assert!(p.clips()[0].link.is_some());
6058 // degenerate mapping: timeline == source
6059 assert_eq!(p.map_timeline(0), Some((0, 0)));
6060 assert_eq!(p.map_timeline(149), Some((0, 149)));
6061 assert_eq!(p.map_timeline(150), None);
6062 // never-empty invariant survives a bogus frame count
6063 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
6064 }
6065
6066 #[test]
6067 fn split_cuts_every_lane_and_regroups_it_back() {
6068 let mut p = Project::single(FILE, 9);
6069 let before = traversal(&p);
6070 let before_shape = shape(&p);
6071
6072 assert!(p.split(4));
6073 for l in p.lanes() {
6074 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
6075 }
6076 // The two sides are two groups, one per side, matching across the lanes.
6077 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
6078 assert_eq!(v[0].link, a[0].link);
6079 assert_eq!(v[1].link, a[1].link);
6080 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
6081 // A split changes no mapping, in either lane.
6082 assert_eq!(traversal(&p), before, "a split moves nothing");
6083
6084 assert!(p.regroup(4), "the inverse rejoins them");
6085 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
6086 assert_eq!(traversal(&p), before);
6087 assert_eq!(
6088 p.lane(Lane::V1)[0].link,
6089 p.lane(Lane::A1)[0].link,
6090 "and the rejoined clip is one group again"
6091 );
6092 }
6093
6094 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
6095 /// the very first frame of a fade-in, unity at its last, equal-power
6096 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
6097 /// at all.
6098 #[test]
6099 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
6100 let f = Fade {
6101 elapsed: 0,
6102 fade_in: 10,
6103 fade_out: 10,
6104 total: 40,
6105 };
6106 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
6107 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
6108 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
6109 assert!(
6110 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
6111 "equal-power midpoint is sin(pi/4)"
6112 );
6113 assert_eq!(
6114 f.gain_at(20),
6115 1.0,
6116 "unchanged in the body, past either ramp"
6117 );
6118 // The fade-out is the same curve, mirrored, counting down from the
6119 // clip's end: unity at the frame the ramp starts, the same
6120 // equal-power midpoint, and -- since `total` itself is one past the
6121 // clip's last valid frame -- the very last frame is one step short of
6122 // the silence a fade-in's own frame `0` lands on exactly.
6123 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
6124 assert!(
6125 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
6126 "the fade-out's own equal-power midpoint"
6127 );
6128 assert!(
6129 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
6130 "one step short of silence at the clip's last playable frame"
6131 );
6132 }
6133
6134 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
6135 /// not adjacent, and otherwise sets the shared edge's fades and nothing
6136 /// else.
6137 #[test]
6138 fn crossfade_only_joins_adjacent_audio_clips() {
6139 let mut p = Project::single(FILE, 20);
6140 assert!(p.split(10));
6141 assert!(!p.crossfade(Lane::V1, 0, 5), "video is not an audio lane");
6142 assert!(!p.crossfade(Lane::A1, 1, 5), "there is no clip after idx 1");
6143 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
6144 let a = p.lane(Lane::A1);
6145 assert_eq!(a[0].fade_out, 5);
6146 assert_eq!(a[1].fade_in, 5);
6147 assert_eq!(a[0].fade_in, 0);
6148 assert_eq!(a[1].fade_out, 0);
6149
6150 // A gap between two clips is not adjacency, even on an audio lane.
6151 let mut p2 = Project::single(FILE, 1);
6152 let a2 = p2.add_lane(LaneKind::Audio);
6153 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
6154 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
6155 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
6156 }
6157
6158 /// The rule [`Project::write_split`] follows for the edge the razor makes:
6159 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
6160 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
6161 /// mirror image.
6162 #[test]
6163 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
6164 let mut p = Project::single(FILE, 20);
6165 assert!(p.set_fade_in(Lane::V1, 0, 15));
6166 assert!(p.set_fade_out(Lane::V1, 0, 15));
6167 assert!(p.split(5));
6168 let v = p.lane(Lane::V1);
6169 assert_eq!(
6170 v[0].fade_in, 5,
6171 "the left half's kept fade-in, clamped to 5 frames"
6172 );
6173 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
6174 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
6175 assert_eq!(
6176 v[1].fade_out, 15,
6177 "the right half's kept fade-out, unclamped: 15 frames fit in 15"
6178 );
6179 }
6180
6181 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
6182 /// no successor, and two clips that do not touch, and otherwise clamps
6183 /// the dissolve to the shorter of the two clips it spans.
6184 #[test]
6185 fn set_transition_out_only_dissolves_adjacent_video_clips() {
6186 let mut p = Project::single(FILE, 20);
6187 assert!(p.split(15), "a short 5-frame tail to clamp against");
6188 assert!(
6189 !p.set_transition_out(Lane::A1, 0, 5),
6190 "audio is not a video lane"
6191 );
6192 assert!(
6193 !p.set_transition_out(Lane::V1, 1, 5),
6194 "there is no clip after idx 1"
6195 );
6196 assert!(
6197 p.set_transition_out(Lane::V1, 0, 100),
6198 "the two halves are adjacent"
6199 );
6200 assert_eq!(
6201 p.transition_out_of(Lane::V1, 0),
6202 5,
6203 "clamped to the shorter neighbour's 5 frames"
6204 );
6205
6206 // A gap between two clips is not adjacency, even on the video lane.
6207 let mut p2 = Project::single(FILE, 1);
6208 let v2 = p2.add_lane(LaneKind::Video);
6209 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
6210 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
6211 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
6212 }
6213
6214 /// The two transition doors' bool is the WEAK shape, stated here as
6215 /// behaviour rather than left as something a front-end has to know: both
6216 /// answer "these two clips are adjacent", and both snapshot and clamp --
6217 /// so a write that lands the value the join already carries is still
6218 /// reported as a write, and still spends an undo step. This is the fact
6219 /// `Player::transition_edges`'s before/after comparison exists to cover,
6220 /// and the fact a UI test can only reach through a source scan: driving
6221 /// the front-end needs a window this crate has no harness for, so the
6222 /// door's own answer is pinned here, where it can be run.
6223 #[test]
6224 fn a_transition_door_says_yes_to_a_write_that_moved_nothing() {
6225 let mut p = Project::single(FILE, 20);
6226 assert!(p.split(10), "two halves to join");
6227 assert!(p.set_transition_out(Lane::V1, 0, 5), "the dissolve lands");
6228 assert!(p.crossfade(Lane::A1, 0, 5), "the crossfade lands");
6229 let history = p.history.len();
6230
6231 // The very same numbers again: nothing moved, and both doors report a
6232 // write anyway.
6233 assert!(
6234 p.set_transition_out(Lane::V1, 0, 5),
6235 "set_transition_out answers 'the clips are adjacent', not 'the \
6236 dissolve moved', so a no-op reads as a write"
6237 );
6238 assert!(
6239 p.crossfade(Lane::A1, 0, 5),
6240 "crossfade answers the same way for the same reason"
6241 );
6242 assert_eq!(
6243 p.history.len(),
6244 history + 2,
6245 "and each spent an undo step saying so, which is why the \
6246 front-end compares the join's own edges before it arms"
6247 );
6248
6249 // What did not move -- the comparison the front-end makes: both edges
6250 // a crossfade writes, and the dissolve itself.
6251 let a = p.lane(Lane::A1);
6252 assert_eq!((a[0].fade_out, a[1].fade_in), (5, 5), "unchanged");
6253 assert_eq!(p.transition_out_of(Lane::V1, 0), 5, "unchanged");
6254
6255 // And a refusal still answers no, so the arm is not simply always on:
6256 // the last clip has no successor to dissolve into.
6257 assert!(
6258 !p.set_transition_out(Lane::V1, 1, 5),
6259 "no neighbour end to end"
6260 );
6261 }
6262
6263 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
6264 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
6265 /// only the half that kept the clip's original *end* keeps the dissolve,
6266 /// re-clamped to its own now-shorter length; the head the cut just made
6267 /// has no successor to dissolve into and starts flat.
6268 #[test]
6269 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
6270 let mut p = Project::single(FILE, 20);
6271 assert!(
6272 !p.set_transition_out(Lane::V1, 0, 0),
6273 "one clip on the lane, no successor to dissolve into yet"
6274 );
6275 // Give the clip a dissolve by hand, then cut it in two.
6276 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
6277 assert!(p.split(5));
6278 let v = p.lane(Lane::V1);
6279 assert_eq!(
6280 v[0].transition_out, 0,
6281 "the cut edge it made has no successor"
6282 );
6283 assert_eq!(
6284 v[1].transition_out, 15,
6285 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
6286 );
6287 }
6288
6289 /// The music video's own path: the take comes apart into halves that carry
6290 /// ids of their own, one undo puts it back, and two clips over the same
6291 /// frames become one take again by hand.
6292 #[test]
6293 fn a_take_comes_apart_and_goes_back_together() {
6294 let mut p = Project::single(FILE, 9);
6295 let one = p.clips()[0].link.expect("a fresh project is one take");
6296 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
6297
6298 // A third lane in the same group -- and the merge case with it: a
6299 // placement is in no group, and grouping it in leaves *one* group.
6300 let v2 = p.add_lane(LaneKind::Video);
6301 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6302 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
6303 p.group(Lane::V1, 0, v2, 0)
6304 .expect("the same frames, one lane over");
6305 let id = p.clips()[0].link.expect("still a group");
6306 assert!(
6307 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6308 "one id over the three, not two groups sharing a span"
6309 );
6310 links_are_consistent(&p.lanes).expect("one id, one span");
6311
6312 // Detached by the sound: every half of the group, not only the two.
6313 assert!(p.ungroup(Lane::A1, 0));
6314 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
6315 assert!(
6316 ids.iter().all(Option::is_some),
6317 "a half keeps an id of its own"
6318 );
6319 assert!(
6320 ids.iter()
6321 .enumerate()
6322 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
6323 "and no two halves are the same group any more: {ids:?}"
6324 );
6325 links_are_consistent(&p.lanes).expect("a lone id is legal");
6326
6327 // One snapshot for the whole detach.
6328 assert!(p.undo());
6329 assert!(
6330 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6331 "one undo puts the whole group back"
6332 );
6333
6334 // And back together by hand: the two the pointer named, and only them.
6335 assert!(p.ungroup(Lane::V1, 0));
6336 p.group(Lane::V1, 0, Lane::A1, 0)
6337 .expect("both cover [0, 9)");
6338 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
6339 assert_ne!(
6340 p.lane(v2)[0].link,
6341 p.lane(Lane::V1)[0].link,
6342 "the third half stayed detached"
6343 );
6344 links_are_consistent(&p.lanes).expect("one id, one span");
6345 }
6346
6347 /// What a group may not be, and what a detach has nothing to take apart --
6348 /// none of which may cost an undo step.
6349 #[test]
6350 fn a_group_is_one_span_and_one_clip_per_lane() {
6351 let mut p = three();
6352 let before = shape(&p);
6353 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
6354
6355 assert!(
6356 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
6357 "two clips of one lane are never one take"
6358 );
6359 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
6360 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
6361 assert!(
6362 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
6363 "{spans}"
6364 );
6365 assert!(
6366 spans.contains("trim them to matching bounds first"),
6367 "{spans}"
6368 );
6369 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
6370
6371 // A half nothing else is grouped with is already detached, a placement
6372 // is in no group at all, and an index that is not there has nothing to
6373 // detach either.
6374 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
6375 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
6376 assert!(p.lift(Lane::A1, 0));
6377 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
6378 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
6379
6380 // Two undos, one per edit: not one of the refusals pushed a snapshot.
6381 assert!(p.undo());
6382 assert!(p.undo());
6383 assert_eq!(shape(&p), before);
6384 }
6385
6386 /// Where a re-rate puts a playhead: the scene under the cursor stays the
6387 /// scene under the cursor, measured the way a viewer would -- the source
6388 /// frame playing at the playhead is the same frame after the write, at
6389 /// every playhead position the re-rate can catch one.
6390 #[test]
6391 fn a_re_rate_keeps_the_frame_under_the_playhead() {
6392 let caption = |start: u32, frames: u32| SubClip {
6393 start,
6394 frames,
6395 track: 0,
6396 in_us: 0,
6397 out_us: i64::from(frames) * 1_000_000,
6398 link: None,
6399 };
6400 let track = || SubtitleTrack {
6401 path: FILE.into(),
6402 track: None,
6403 language: "eng".into(),
6404 name: String::new(),
6405 label: "eng".into(),
6406 cues: Vec::new(),
6407 bitmap: false,
6408 refused: None,
6409 };
6410 // A group of a 300-frame clip and a caption offset 30 frames into it.
6411 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
6412 let s1 = p.add_lane(LaneKind::Subtitle);
6413 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
6414 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6415
6416 // The frame playing at `at`: which clip, and which source frame of it.
6417 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
6418 p.span_at(Lane::V1, at)
6419 .and_then(|s| s.from.map(|(source, from)| (source, from)))
6420 };
6421
6422 // Inside the held clip: the source frame under the playhead is the
6423 // same one after the re-rate, at 2x and at half speed both.
6424 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
6425 let at = 120;
6426 let before = playing(&p, at).expect("a clip under the playhead");
6427 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
6428 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
6429 .expect("room for it");
6430 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
6431 assert_eq!(before, after, "{what}: the same source frame plays");
6432 // ...and the write itself is untouched by the question.
6433 assert!(p.undo(), "{what}: one step back");
6434 }
6435
6436 // Past the group -- the clip ends at 300 and the caption at 270, so
6437 // from 300 on nothing is re-timed under the playhead: unmoved.
6438 for at in [300u32, 301, 1_000] {
6439 assert_eq!(
6440 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
6441 Some(at),
6442 "at {at}: outside every member, unmoved"
6443 );
6444 }
6445 // The boundary is exact: the held clip's own last frame (299) maps
6446 // to its new one (149 -- the last frame inside [0, 150), where the
6447 // shrunken clip's last source frame plays), and its first stays put.
6448 assert_eq!(
6449 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
6450 Some(149)
6451 );
6452 assert_eq!(
6453 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
6454 Some(0)
6455 );
6456 // A spot the caption shares with the clip maps by the clip (it is
6457 // what is *playing* there): the held clip's own proportion, which on
6458 // this fixture is also its head.
6459 assert_eq!(
6460 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
6461 Some(45),
6462 "the clip under the caption owns the spot"
6463 );
6464 }
6465
6466 /// A playhead inside another clip member of the group: that member keeps
6467 /// its own head, so the mapping is by its proportion and not the held
6468 /// clip's -- and the frame under the cursor is still the frame that was.
6469 #[test]
6470 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
6471 let mut p = Project::single(FILE, 300);
6472 // A second clip, grouped with the first but starting 300 later: the
6473 // head the group shares and its own differ by exactly that.
6474 let v2 = p.add_lane(LaneKind::Video);
6475 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
6476 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
6477 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
6478
6479 let at = 450; // inside the second member, 150 past its head
6480 let before = p.span_at(v2, at).and_then(|s| s.from);
6481 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
6482 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6483 .expect("room for it");
6484 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
6485 assert_eq!(before, after, "the second member's own frame plays");
6486 // ...and the mapping itself: 150 past its head halves, the head stays.
6487 assert_eq!(mapped, Some(375));
6488 }
6489
6490 /// The link counter a load seeds sits past every id the file names,
6491 /// captions included: a hand-grouped caption may carry the highest id there
6492 /// is, and a counter that read the clips alone would hand it to the next
6493 /// group that asked -- silently grouping the caption with clips it never
6494 /// met.
6495 #[test]
6496 fn the_link_counter_sits_past_a_caption_only_id() {
6497 let track = || SubtitleTrack {
6498 path: FILE.into(),
6499 track: None,
6500 language: "eng".into(),
6501 name: String::new(),
6502 label: "eng".into(),
6503 cues: Vec::new(),
6504 bitmap: false,
6505 refused: None,
6506 };
6507 let mut p = Project::single(FILE, 9);
6508 p.add_lane(LaneKind::Subtitle);
6509 let caption = SubClip {
6510 start: 0,
6511 frames: 6,
6512 track: 0,
6513 in_us: 0,
6514 out_us: 6_000_000,
6515 // The highest id in the file, and only a caption carries it.
6516 link: Some(1),
6517 };
6518 let mut p = p
6519 .with_subtitles(vec![track()])
6520 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
6521 .expect("a caption may carry the file's highest id");
6522
6523 // A new group on lanes the caption is not on mints the next id -- which
6524 // must not be the caption's.
6525 let v2 = p.add_lane(LaneKind::Video);
6526 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6527 p.group_all(&[(Lane::V1, 0), (v2, 0)])
6528 .expect("the clips group");
6529 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
6530 assert_ne!(minted, 1, "the caption's id is not re-issued to clips");
6531 assert_eq!(
6532 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
6533 Some(1),
6534 "the caption keeps its own group"
6535 );
6536 assert!(links_are_consistent(&p.lanes).is_ok());
6537 }
6538
6539 /// A rate re-times the caption members of the group by the ratio it gives
6540 /// the held clip: the span on the timeline compresses about the held clip's
6541 /// head, the words' own window untouched -- and one undo puts it back.
6542 #[test]
6543 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
6544 let caption = |start: u32, frames: u32| SubClip {
6545 start,
6546 frames,
6547 track: 0,
6548 in_us: 0,
6549 out_us: i64::from(frames) * 1_000_000,
6550 link: None,
6551 };
6552 let track = || SubtitleTrack {
6553 path: FILE.into(),
6554 track: None,
6555 language: "eng".into(),
6556 name: String::new(),
6557 label: "eng".into(),
6558 cues: Vec::new(),
6559 bitmap: false,
6560 refused: None,
6561 };
6562 let grouped = || {
6563 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6564 let s1 = p.add_lane(LaneKind::Subtitle);
6565 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6566 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6567 (p, s1)
6568 };
6569
6570 // An aligned take, doubled: the caption plays in half the frames.
6571 let (mut p, s1) = grouped();
6572 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6573 .expect("room for it");
6574 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
6575 let s = p.sub_lane(s1)[0];
6576 assert_eq!(
6577 (s.start, s.frames),
6578 (0, 45),
6579 "same words, half the timeline"
6580 );
6581 assert_eq!(
6582 (s.in_us, s.out_us),
6583 (0, 90_000_000),
6584 "the window is untouched"
6585 );
6586 assert!(links_are_consistent(&p.lanes).is_ok());
6587 assert!(p.undo());
6588 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
6589
6590 // An offset group, slowed to half: the caption's *offset from the held
6591 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
6592 // 0.5x, and still ends where the clip does.
6593 let (mut p, s1) = grouped();
6594 p.lift_sub(s1, 0);
6595 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
6596 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6597 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
6598 .expect("room for it");
6599 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
6600 let s = p.sub_lane(s1)[0];
6601 assert_eq!(
6602 (s.start, s.frames),
6603 (60, 120),
6604 "the offset doubles with the clip"
6605 );
6606 assert_eq!(
6607 s.end(),
6608 p.lane(Lane::V1)[0].end(),
6609 "still ends with the clip"
6610 );
6611
6612 // A stretch that runs the caption into its neighbour is refused, by
6613 // lane and frame, and costs no undo step.
6614 let (mut p, s1) = grouped();
6615 p.lift_sub(s1, 0);
6616 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6617 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
6618 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6619 let history = p.history.len();
6620 let err = p
6621 .set_speed(Lane::V1, 0, Speed::from_permille(500))
6622 .unwrap_err()
6623 .to_string();
6624 assert!(
6625 err.contains(
6626 "the S1 caption at frame 0 would run to frame 180 and the next starts at 95"
6627 ),
6628 "{err}"
6629 );
6630 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
6631 }
6632
6633 /// The silence scan's speed-up re-times the captions on a scoped lane with
6634 /// everything else: the piece inside the region plays in the region's new
6635 /// frames, and what sits behind the region slides up with the clips.
6636 #[test]
6637 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
6638 let caption = |start: u32, frames: u32| SubClip {
6639 start,
6640 frames,
6641 track: 0,
6642 in_us: 0,
6643 out_us: i64::from(frames) * 1_000_000,
6644 link: None,
6645 };
6646 let track = || SubtitleTrack {
6647 path: FILE.into(),
6648 track: None,
6649 language: "eng".into(),
6650 name: String::new(),
6651 label: "eng".into(),
6652 cues: Vec::new(),
6653 bitmap: false,
6654 refused: None,
6655 };
6656 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6657 let s1 = p.add_lane(LaneKind::Subtitle);
6658 // Words over the region [30, 60) and words behind it.
6659 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6660 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
6661
6662 // The region [30, 60) plays at 4x: 30 frames become 8, everything
6663 // behind slides up 22.
6664 // The scope is what the card's Take row says, caption lane included.
6665 p.speed_regions(
6666 &[(30, 30)],
6667 Speed::from_permille(4000),
6668 &[Lane::V1, Lane::A1, s1],
6669 )
6670 .expect("the region speeds up");
6671 let subs = p.sub_lane(s1);
6672 assert_eq!(
6673 (subs[0].start, subs[0].frames),
6674 (30, 8),
6675 "the piece inside plays in the region's new frames"
6676 );
6677 assert_eq!(
6678 (subs[1].start, subs[1].frames),
6679 (38, 30),
6680 "the piece behind slides up by what the region gave back"
6681 );
6682 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
6683 }
6684
6685 /// [`Project::speeded_playhead`]'s caption arm fires only when the
6686 /// playhead is inside a caption member and outside every clip member --
6687 /// a shape every other fixture avoids by keeping its caption inside the
6688 /// held clip. Here the caption overhangs the clip's tail, and the
6689 /// playhead standing in that overhang is answered by the caption's own
6690 /// piece: it scales about the held clip's head by the held clip's own
6691 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
6692 #[test]
6693 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
6694 let caption = |start: u32, frames: u32| SubClip {
6695 start,
6696 frames,
6697 track: 0,
6698 in_us: 0,
6699 out_us: i64::from(frames) * 1_000_000,
6700 link: None,
6701 };
6702 let track = || SubtitleTrack {
6703 path: FILE.into(),
6704 track: None,
6705 language: "eng".into(),
6706 name: String::new(),
6707 label: "eng".into(),
6708 cues: Vec::new(),
6709 bitmap: false,
6710 refused: None,
6711 };
6712 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6713 let s1 = p.add_lane(LaneKind::Subtitle);
6714 // The caption spans [80, 100) -- ten frames past the clip's own end
6715 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6716 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6717 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6718 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6719 // no clip member's old span reaches, is the caption's own question:
6720 // half of 95 is 47.5, rounded to 48.
6721 assert_eq!(
6722 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6723 Some(48),
6724 "the overhang frame answers through the caption's own piece"
6725 );
6726 }
6727
6728 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6729 /// map ([`map`]'s architecture law): a caption's landed span comes from
6730 /// the map's own ends, and the playhead standing at the caption's own
6731 /// last frame before the write has to land exactly where the write put
6732 /// it -- across clip lengths and rates that round differently, and an
6733 /// odd-length caption straddling the clip's own tail edge, the corner
6734 /// where `write_speed` used to answer a frame short.
6735 #[test]
6736 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6737 let caption = |start: u32, frames: u32| SubClip {
6738 start,
6739 frames,
6740 track: 0,
6741 in_us: 0,
6742 out_us: i64::from(frames) * 1_000_000,
6743 link: None,
6744 };
6745 let track = || SubtitleTrack {
6746 path: FILE.into(),
6747 track: None,
6748 language: "eng".into(),
6749 name: String::new(),
6750 label: "eng".into(),
6751 cues: Vec::new(),
6752 bitmap: false,
6753 refused: None,
6754 };
6755 for &len in &[90u32, 91, 177, 300, 301] {
6756 for &permille in &[500u16, 2000, 2500, 3000] {
6757 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6758 let s1 = p.add_lane(LaneKind::Subtitle);
6759 // An odd-length caption straddling the clip's tail edge: its
6760 // own last frame lands past the held clip.
6761 let c_start = len.saturating_sub(3);
6762 p.place_sub(s1, c_start, caption(c_start, 7))
6763 .expect("placed");
6764 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6765 let speed = Speed::from_permille(permille);
6766 let last = c_start + 7 - 1;
6767 let mapped = p
6768 .speeded_playhead(Lane::V1, 0, speed, last)
6769 .expect("the caption is there");
6770 if p.set_speed(Lane::V1, 0, speed).is_err() {
6771 continue; // a refusal changes nothing: not this law's cell
6772 }
6773 let landed = p.sub_lane(s1)[0];
6774 if permille >= 1000 {
6775 // A speed-up compresses the timeline: many old frames
6776 // share one new frame, so the caption's own last old
6777 // frame lands flush with the write's own boundary --
6778 // the exact law [`write_speed`]'s worked drift-fix case
6779 // is stated against.
6780 assert_eq!(
6781 mapped,
6782 landed.end() - 1,
6783 "len {len} permille {permille}: the playhead at the caption's own \
6784 last frame lands where the write actually put it"
6785 );
6786 } else {
6787 // A slow-down expands it: one old frame becomes several
6788 // new ones, and `apply` answers where that frame's own
6789 // block *starts*, not where the caption's last new
6790 // frame (the end of that same block) sits -- a
6791 // one-frame gap inherent to the piece's own semantics,
6792 // not a drift between the two callers. Both still have
6793 // to agree the answer sits inside the caption the write
6794 // actually landed.
6795 assert!(
6796 (landed.start..landed.end()).contains(&mapped),
6797 "len {len} permille {permille}: the playhead lands inside the \
6798 caption the write actually put ({landed:?}), got {mapped}"
6799 );
6800 }
6801 }
6802 }
6803 }
6804
6805 /// A grouped caption's cues re-time with its clip: the placement's window
6806 /// crossed the timeline at its own proportion before any rate, and a
6807 /// re-rate changes that proportion (the frames compress, the window does
6808 /// not). A cue eight seconds into a window played at 2x crosses the screen
6809 /// four seconds in -- and at unity every cue lands exactly where it always
6810 /// did, byte for byte.
6811 #[test]
6812 fn a_grouped_captions_cues_re_time_with_its_clip() {
6813 let track = SubtitleTrack {
6814 path: FILE.into(),
6815 track: None,
6816 language: "eng".into(),
6817 name: String::new(),
6818 label: "eng".into(),
6819 cues: vec![crate::subtitle::Cue {
6820 start_us: 8_000_000,
6821 end_us: 9_000_000,
6822 text: "late line".into(),
6823 image: None,
6824 }],
6825 bitmap: false,
6826 refused: None,
6827 };
6828 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6829 let s1 = p.add_lane(LaneKind::Subtitle);
6830 // Ten seconds of the track over ten seconds of timeline: unity.
6831 p.place_sub(
6832 s1,
6833 0,
6834 SubClip {
6835 start: 0,
6836 frames: 300,
6837 track: 0,
6838 in_us: 0,
6839 out_us: 10_000_000,
6840 link: None,
6841 },
6842 )
6843 .expect("placed");
6844
6845 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6846 let unity = p.sub_lane_cues(s1, FPS);
6847 assert_eq!(
6848 unity
6849 .iter()
6850 .map(|c| (c.start_us, c.end_us, &*c.text))
6851 .collect::<Vec<_>>(),
6852 [(8_000_000, 9_000_000, "late line")],
6853 "a unity placement maps exactly as it always did"
6854 );
6855
6856 // Grouped with the clip and re-rated to 2x: the same window now crosses
6857 // in half the time, so the cue at 8s of it lands 4s in.
6858 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6859 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6860 .expect("room for it");
6861 let re_timed = p.sub_lane_cues(s1, FPS);
6862 assert_eq!(
6863 re_timed
6864 .iter()
6865 .map(|c| (c.start_us, c.end_us))
6866 .collect::<Vec<_>>(),
6867 [(4_000_000, 4_500_000)],
6868 "the cue crosses with the clip's new rate"
6869 );
6870 }
6871
6872 /// A video arriving on a timeline of words mutates none of them: the
6873 /// import's rippling insert used to open room on the subtitle lanes too,
6874 /// splitting a caption it landed inside and sliding the rest behind the
6875 /// video -- the hand asked for an add, and got a cut it never made. The
6876 /// words keep their own clock; co-travel is what a group is for.
6877 #[test]
6878 fn an_arriving_clip_never_touches_the_captions() {
6879 let caption = |start: u32, frames: u32| SubClip {
6880 start,
6881 frames,
6882 track: 0,
6883 in_us: i64::from(start) * 1_000_000 / 30,
6884 out_us: i64::from(start + frames) * 1_000_000 / 30,
6885 link: None,
6886 };
6887 let track = || SubtitleTrack {
6888 path: FILE.into(),
6889 track: None,
6890 language: "eng".into(),
6891 name: String::new(),
6892 label: "eng".into(),
6893 cues: Vec::new(),
6894 bitmap: false,
6895 refused: None,
6896 };
6897 // A timeline of words alone: 60 frames of caption, no media clips.
6898 let mut p = Project::single(FILE, 60).with_subtitles(vec![track()]);
6899 for l in [Lane::V1, Lane::A1] {
6900 while !p.lane(l).is_empty() {
6901 p.lift(l, 0);
6902 }
6903 }
6904 let s1 = p.add_lane(LaneKind::Subtitle);
6905 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6906 let before = p.sub_lane(s1).to_vec();
6907
6908 // The video lands BEFORE the caption's span: nothing moves.
6909 let vid = clip(0, 0, 30, 0);
6910 assert!(p.paste(0, vid), "the video goes down at the head");
6911 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6912
6913 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6914 // byte the placement the hand made.
6915 assert!(p.paste(15, vid), "a second video lands inside the caption");
6916 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6917 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6918 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6919 assert!(links_are_consistent(&p.lanes).is_ok());
6920 }
6921
6922 /// The region's caption pieces re-time by mapped boundaries forced apart:
6923 /// rounding start and length independently can land two cues on one frame,
6924 /// and the artifact is clamped -- one frame each, in order, none past the
6925 /// region's new end -- never an overlap on the lane.
6926 #[test]
6927 fn a_regions_caption_pieces_never_round_onto_one_another() {
6928 let caption = |start: u32, frames: u32| SubClip {
6929 start,
6930 frames,
6931 track: 0,
6932 in_us: 0,
6933 out_us: i64::from(frames) * 1_000_000,
6934 link: None,
6935 };
6936 let track = |n| SubtitleTrack {
6937 path: FILE.into(),
6938 track: None,
6939 language: "eng".into(),
6940 name: String::new(),
6941 label: format!("eng{n}"),
6942 cues: Vec::new(),
6943 bitmap: false,
6944 refused: None,
6945 };
6946 // Three lanes, one repro shape each: adjacent one-frame cues, a
6947 // three-frame pair, and the region's last cue against the first
6948 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6949 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6950 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6951 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6952 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6953 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6954 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6955 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6956 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6957
6958 let mut scope = vec![Lane::V1, Lane::A1];
6959 scope.extend(lanes.iter().copied());
6960 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6961 .expect("the region speeds up");
6962 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6963 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6964 p.sub_lane(lane)
6965 .iter()
6966 .map(|s| (s.start, s.frames))
6967 .collect()
6968 };
6969 assert_eq!(
6970 spans(&p, lanes[0]),
6971 [(5, 1), (6, 1)],
6972 "one frame each, in order"
6973 );
6974 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6975 // and the walk pushes the second to where the first ends.
6976 assert_eq!(
6977 spans(&p, lanes[1]),
6978 [(3, 1), (4, 2)],
6979 "forced apart, kept in order"
6980 );
6981 // The last cue of the region ends exactly where the region now does
6982 // (frame 15), and the caption behind it lands on that same frame:
6983 // touching, never overlapping.
6984 assert_eq!(
6985 spans(&p, lanes[2]),
6986 [(14, 1), (15, 15)],
6987 "the cue ends with the region"
6988 );
6989 for &lane in &lanes {
6990 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6991 }
6992 }
6993
6994 /// The scope law names a caption half too: a scoped cut that would move one
6995 // track of a group whose caption sits outside the scope is refused.
6996 #[test]
6997 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6998 let caption = |start: u32, frames: u32| SubClip {
6999 start,
7000 frames,
7001 track: 0,
7002 in_us: 0,
7003 out_us: i64::from(frames) * 1_000_000,
7004 link: None,
7005 };
7006 let track = || SubtitleTrack {
7007 path: FILE.into(),
7008 track: None,
7009 language: "eng".into(),
7010 name: String::new(),
7011 label: "eng".into(),
7012 cues: Vec::new(),
7013 bitmap: false,
7014 refused: None,
7015 };
7016 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7017 let s1 = p.add_lane(LaneKind::Subtitle);
7018 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
7019 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7020
7021 // The subtitle lane is not in the scope, so the group's caption half
7022 // sits outside it: refused, in the law's own words.
7023 let err = p
7024 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
7025 .unwrap_err()
7026 .to_string();
7027 assert!(
7028 err.contains("is one take with the S1 caption at frame 0"),
7029 "{err}"
7030 );
7031
7032 // ...and with the caption's lane in the scope, the cut carries it:
7033 // the words over the hole go, and the words behind slide up.
7034 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
7035 .expect("the whole group is in the scope");
7036 let subs = p.sub_lane(s1);
7037 assert_eq!(
7038 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
7039 [(0, 10), (10, 75)],
7040 "the caption is cut and shifted with the clips"
7041 );
7042 }
7043
7044 /// The caption a hand groups: `group_all` over clips *and* a caption, the
7045 /// mates riding along, the offsets kept, the refusals in words.
7046 #[test]
7047 fn a_hand_built_group_holds_clips_and_a_caption() {
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 v2 = p.add_lane(LaneKind::Video);
7068 let s1 = p.add_lane(LaneKind::Subtitle);
7069 // A layer at its own offset, and a caption over the head of the take.
7070 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
7071 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
7072
7073 // Too few, one lane twice, and an index that is not there: words, no
7074 // snapshot.
7075 let history = p.history.len();
7076 assert!(
7077 p.group_all(&[])
7078 .unwrap_err()
7079 .to_string()
7080 .contains("two placements or more")
7081 );
7082 assert!(
7083 p.group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
7084 .unwrap_err()
7085 .to_string()
7086 .contains("V1 is picked twice")
7087 );
7088 assert!(
7089 p.group_all(&[(Lane::V1, 0), (s1, 9)])
7090 .unwrap_err()
7091 .to_string()
7092 .contains("no subtitle 9")
7093 );
7094 assert_eq!(p.history.len(), history, "refusals cost no undo step");
7095
7096 // The group: the picture, the layer, and the caption -- and the sound
7097 // the picture was already grouped with comes along unasked.
7098 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
7099 .expect("three picks, three lanes");
7100 let id = p.lane(Lane::V1)[0].link.expect("grouped");
7101 for lane in [Lane::V1, Lane::A1, v2] {
7102 assert_eq!(
7103 p.lane(lane)[0].link,
7104 Some(id),
7105 "{} rides along",
7106 lane.label()
7107 );
7108 }
7109 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
7110 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
7111 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
7112 assert!(links_are_consistent(&p.lanes).is_ok());
7113 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
7114
7115 // ...and one undo takes it apart again.
7116 assert!(p.undo());
7117 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
7118
7119 // Detach names a caption like it names a clip: every member an id of
7120 // its own, which is never `None` (see `ungroup`).
7121 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
7122 assert!(p.ungroup(s1, 0));
7123 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
7124 assert!(loose_sub.is_some() && loose_clip.is_some());
7125 assert_ne!(loose_sub, loose_clip);
7126 assert!(links_are_consistent(&p.lanes).is_ok());
7127 }
7128
7129 /// Two captions on one sub lane, each already grouped with a *different*
7130 /// clip: `group_all` over both those clips would merge the two existing
7131 /// groups into one id and leave both captions on `s1` carrying it --
7132 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
7133 /// group closes. Refused by name, and nothing moves.
7134 #[test]
7135 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
7136 let caption = |start: u32, frames: u32| SubClip {
7137 start,
7138 frames,
7139 track: 0,
7140 in_us: 0,
7141 out_us: i64::from(frames) * 1_000_000,
7142 link: None,
7143 };
7144 let track = || SubtitleTrack {
7145 path: FILE.into(),
7146 track: None,
7147 language: "eng".into(),
7148 name: String::new(),
7149 label: "eng".into(),
7150 cues: Vec::new(),
7151 bitmap: false,
7152 refused: None,
7153 };
7154 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7155 let v2 = p.add_lane(LaneKind::Video);
7156 let s1 = p.add_lane(LaneKind::Subtitle);
7157 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
7158 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
7159 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
7160 // V1 grouped with the first caption, v2 with the second -- two
7161 // separate groups, each already one member per lane.
7162 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7163 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
7164 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
7165
7166 let history = p.history.len();
7167 let err = p
7168 .group_all(&[(Lane::V1, 0), (v2, 0)])
7169 .unwrap_err()
7170 .to_string();
7171 assert!(err.contains("one placement per lane"), "{err}");
7172 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
7173 assert_eq!(
7174 p.lane(Lane::V1)[0].link,
7175 v1_link,
7176 "the first group untouched"
7177 );
7178 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
7179 assert!(links_are_consistent(&p.lanes).is_ok());
7180 }
7181
7182 /// A split hands the caption of a group the same ids it hands the clips:
7183 /// the left halves keep the group, the right halves share a fresh one.
7184 #[test]
7185 fn a_split_cuts_a_grouped_caption_with_its_clips() {
7186 let caption = |start: u32, frames: u32| SubClip {
7187 start,
7188 frames,
7189 track: 0,
7190 in_us: 0,
7191 out_us: i64::from(frames) * 1_000_000,
7192 link: None,
7193 };
7194 let track = || SubtitleTrack {
7195 path: FILE.into(),
7196 track: None,
7197 language: "eng".into(),
7198 name: String::new(),
7199 label: "eng".into(),
7200 cues: Vec::new(),
7201 bitmap: false,
7202 refused: None,
7203 };
7204 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7205 let s1 = p.add_lane(LaneKind::Subtitle);
7206 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
7207 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7208 let take = p.lane(Lane::V1)[0].link.expect("the group id");
7209
7210 assert!(p.split(4));
7211 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
7212 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
7213 assert_eq!(left.frames, 4);
7214 assert_eq!(
7215 right.link,
7216 p.lane(Lane::V1)[1].link,
7217 "the caption's tail shares the clips' fresh id"
7218 );
7219 assert_ne!(right.link, Some(take));
7220 assert!(links_are_consistent(&p.lanes).is_ok());
7221
7222 // Regroup at the seam restores the take, caption included.
7223 assert!(p.regroup(4));
7224 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
7225 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
7226 }
7227
7228 /// Deleting a member of a hand-built group takes the group: every
7229 /// member's own span out of its own lane, hole closed -- the lanes may
7230 /// end up out of step, which is what one undo restores together.
7231 #[test]
7232 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
7233 let caption = |start: u32, frames: u32| SubClip {
7234 start,
7235 frames,
7236 track: 0,
7237 in_us: 0,
7238 out_us: i64::from(frames) * 1_000_000,
7239 link: None,
7240 };
7241 let track = || SubtitleTrack {
7242 path: FILE.into(),
7243 track: None,
7244 language: "eng".into(),
7245 name: String::new(),
7246 label: "eng".into(),
7247 cues: Vec::new(),
7248 bitmap: false,
7249 refused: None,
7250 };
7251 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7252 let s1 = p.add_lane(LaneKind::Subtitle);
7253 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7254 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7255 // A neighbour on a lane the group does not touch.
7256 let v2 = p.add_lane(LaneKind::Video);
7257 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
7258
7259 // By the picture or by the caption, the same whole-group delete.
7260 assert!(p.delete_sub_in(s1, 0));
7261 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
7262 assert!(
7263 p.sub_lane(s1).is_empty(),
7264 "the caption's span left its lane"
7265 );
7266 assert_eq!(
7267 p.lane(v2)[0].start,
7268 10,
7269 "a lane the group does not touch stays"
7270 );
7271 assert!(links_are_consistent(&p.lanes).is_ok());
7272 assert!(p.undo(), "one step puts the group back");
7273 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
7274 }
7275
7276 /// The delete law, one statement for every anchor: a caption deleted
7277 /// WITH its group ripples its lane exactly as its clip siblings do --
7278 /// the hole closes and what follows slides up -- while a caption lifted
7279 /// alone leaves its gap, as it always has. And the delete of a grouped
7280 /// clip takes the group from whichever member was clicked.
7281 #[test]
7282 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
7283 let caption = |start: u32, frames: u32| SubClip {
7284 start,
7285 frames,
7286 track: 0,
7287 in_us: 0,
7288 out_us: i64::from(frames) * 1_000_000,
7289 link: None,
7290 };
7291 let track = || SubtitleTrack {
7292 path: FILE.into(),
7293 track: None,
7294 language: "eng".into(),
7295 name: String::new(),
7296 label: "eng".into(),
7297 cues: Vec::new(),
7298 bitmap: false,
7299 refused: None,
7300 };
7301 // V+A+S grouped, with a second caption BEHIND the group's caption:
7302 // closing the hole is what the second caption's position says.
7303 let group = || {
7304 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7305 let s1 = p.add_lane(LaneKind::Subtitle);
7306 p.place_sub(s1, 30, caption(30, 30))
7307 .expect("the group's caption");
7308 p.place_sub(s1, 90, caption(90, 30))
7309 .expect("the caption behind");
7310 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7311 (p, s1)
7312 };
7313
7314 // Deleted by the picture: all three lanes close.
7315 let (mut p, s1) = group();
7316 assert!(p.delete_in(Lane::V1, 0));
7317 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
7318 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
7319 assert_eq!(
7320 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
7321 [60],
7322 "the caption's lane closed by its own span: the follower slid up"
7323 );
7324 assert!(p.undo(), "one step");
7325 assert_eq!(
7326 p.sub_lane(s1).len(),
7327 2,
7328 "both captions back, offsets and all"
7329 );
7330
7331 // By the sound: the same whole-group delete.
7332 let (mut p, s1) = group();
7333 assert!(p.delete_in(Lane::A1, 0));
7334 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7335 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
7336
7337 // By the caption itself: the same again.
7338 let (mut p, s1) = group();
7339 assert!(p.delete_sub_in(s1, 0));
7340 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7341 assert_eq!(
7342 p.sub_lane(s1)[0].start,
7343 60,
7344 "closed from the caption's own door"
7345 );
7346 assert!(links_are_consistent(&p.lanes).is_ok());
7347
7348 // A caption lifted ALONE still leaves its gap: the ungrouped law,
7349 // unchanged.
7350 let (mut p, s1) = group();
7351 assert!(p.ungroup(s1, 0), "the caption stands alone");
7352 assert!(p.lift_sub(s1, 0));
7353 assert_eq!(
7354 p.sub_lane(s1)[0].start,
7355 90,
7356 "the follower stayed put: a lone caption's lift is a gap"
7357 );
7358 }
7359
7360 /// Dragging a grouped caption carries its clips, one delta for all of them
7361 /// -- and a caption in no group refuses an overlap exactly as it always did.
7362 #[test]
7363 fn dragging_a_grouped_caption_carries_its_group() {
7364 let caption = |start: u32, frames: u32| SubClip {
7365 start,
7366 frames,
7367 track: 0,
7368 in_us: 0,
7369 out_us: i64::from(frames) * 1_000_000,
7370 link: None,
7371 };
7372 let track = || SubtitleTrack {
7373 path: FILE.into(),
7374 track: None,
7375 language: "eng".into(),
7376 name: String::new(),
7377 label: "eng".into(),
7378 cues: Vec::new(),
7379 bitmap: false,
7380 refused: None,
7381 };
7382 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7383 let s1 = p.add_lane(LaneKind::Subtitle);
7384 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7385 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7386
7387 // Same lane, further along: everyone moves by the same eight frames.
7388 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
7389 assert_eq!(p.sub_lane(s1)[0].start, 10);
7390 assert_eq!(
7391 p.lane(Lane::V1)[0].start,
7392 8,
7393 "the clip follows by the delta"
7394 );
7395 assert!(links_are_consistent(&p.lanes).is_ok());
7396
7397 // ...and an ungrouped caption is the caption it always was.
7398 assert!(p.ungroup(s1, 0));
7399 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
7400 let s1 = q.add_lane(LaneKind::Subtitle);
7401 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
7402 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
7403 assert!(
7404 q.move_sub(s1, 0, s1, 3)
7405 .unwrap_err()
7406 .to_string()
7407 .contains("already covers")
7408 );
7409 }
7410
7411 /// A trim carries a group's caption by the same delta as its clips, clamped
7412 /// to the caption's own walls -- the offsets between the members survive.
7413 #[test]
7414 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
7415 let caption = |start: u32, frames: u32| SubClip {
7416 start,
7417 frames,
7418 track: 0,
7419 in_us: 0,
7420 out_us: i64::from(frames) * 1_000_000,
7421 link: None,
7422 };
7423 let track = || SubtitleTrack {
7424 path: FILE.into(),
7425 track: None,
7426 language: "eng".into(),
7427 name: String::new(),
7428 label: "eng".into(),
7429 cues: Vec::new(),
7430 bitmap: false,
7431 refused: None,
7432 };
7433 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7434 let s1 = p.add_lane(LaneKind::Subtitle);
7435 // The caption sits two frames into the take and ends one early. The
7436 // source runs past the clip, or there is no tail to pull out.
7437 let src = &[20];
7438 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
7439 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7440
7441 // The tail goes out by three: the clip to 12, the caption to 11.
7442 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
7443 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
7444 assert_eq!(
7445 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
7446 (2, 11),
7447 "the caption follows by the delta"
7448 );
7449 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
7450
7451 // The head comes in by two: everyone's start moves two along.
7452 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
7453 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
7454 assert!(links_are_consistent(&p.lanes).is_ok());
7455 }
7456
7457 #[test]
7458 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
7459 let mut p = three();
7460 let before = shape(&p);
7461 assert!(!p.split(0), "timeline 0 has nothing before it");
7462 assert!(!p.split(3), "existing boundary");
7463 assert!(!p.split(5), "existing boundary");
7464 assert!(!p.split(9), "one past the last frame");
7465 assert!(!p.split(1_000));
7466 assert_eq!(shape(&p), before);
7467 // one undo lands before the *second* split, so the refusals pushed nothing
7468 assert!(p.undo());
7469 assert_eq!(p.clips().len(), 2, "refused splits push no history");
7470
7471 // ...and a frame that is a gap in both lanes has nothing to split.
7472 let mut p = three();
7473 assert!(p.lift(Lane::V1, 1));
7474 assert!(p.lift(Lane::A1, 1));
7475 assert!(!p.split(4), "a gap is not a clip");
7476 }
7477
7478 #[test]
7479 fn regroup_refuses_what_a_split_could_not_have_made() {
7480 let mut p = three();
7481 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
7482 assert!(p.regroup(5));
7483 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
7484 // A boundary with a gap on one side, and one where the sources do not
7485 // meet, are both refused.
7486 let mut p = three();
7487 assert!(p.lift(Lane::V1, 1));
7488 assert!(p.lift(Lane::A1, 1));
7489 assert!(!p.regroup(3), "nothing starts at 3 any more");
7490 let mut p = three();
7491 for l in p.lanes() {
7492 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
7493 }
7494 assert!(!p.regroup(3), "source 100 does not follow source 3");
7495 assert!(!p.regroup(0), "nothing ends at 0");
7496 assert!(!p.regroup(1_000));
7497 }
7498
7499 #[test]
7500 fn map_and_spans_sweep_every_boundary() {
7501 let p = three();
7502 assert_eq!(p.timeline_frames(), 9);
7503 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
7504 // contiguous source here, so the clip index is what actually moves
7505 let expect = [
7506 (0, (0, 0)),
7507 (1, (0, 1)),
7508 (2, (0, 2)),
7509 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
7510 (4, (1, 4)),
7511 (5, (2, 5)),
7512 (6, (2, 6)),
7513 (7, (2, 7)),
7514 (8, (2, 8)),
7515 ];
7516 for (t, want) in expect {
7517 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
7518 }
7519 assert_eq!(p.map_timeline(9), None);
7520 // A span is the rest of the clip from where it was asked about.
7521 assert_eq!(
7522 p.span_at(Lane::V1, 6),
7523 Some(Span {
7524 start: 6,
7525 len: 3,
7526 from: Some((0, 6)),
7527 speed: Speed::NORMAL
7528 })
7529 );
7530 assert_eq!(p.span_at(Lane::V1, 9), None);
7531 }
7532
7533 /// The fit policy is one byte *in* the clip rather than an index into a
7534 /// table like the eq and the grade: there is nothing for a table to share.
7535 /// It costs the clip nothing at all -- the fields before it (a `usize`
7536 /// source and two `Option<u16>`s) already left the struct padded to 40
7537 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
7538 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
7539 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
7540 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
7541 /// words after it pads out to the next multiple of 8: 56 bytes total.
7542 /// The transform index is a third `Option<u16>`, same reason as the eq and
7543 /// colour ones before it -- it lands in bytes already spent on padding, so
7544 /// the struct still costs 56.
7545 /// The visualizer look is the first field whose own width outgrows the
7546 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
7547 /// the clip's own four), so the words after it come to 60 and the
7548 /// alignment rounds them to 64 -- one word more than a clip used to cost.
7549 /// This is the assert that says so: a clip that grows a word grows every
7550 /// undo snapshot and every clipboard copy with it.
7551 #[test]
7552 fn a_fit_policy_costs_the_clip_no_word() {
7553 assert_eq!(
7554 std::mem::size_of::<Clip>(),
7555 64,
7556 "Clip changed size: {} bytes",
7557 std::mem::size_of::<Clip>()
7558 );
7559 }
7560
7561 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
7562 /// anything in `three()` so it is recognisable wherever it lands.
7563 const PASTED: Clip = Clip {
7564 fade_in: 0,
7565 fade_out: 0,
7566 transition_out: 0,
7567 visualizer: 0,
7568 viz_paint: 0,
7569 start: 0,
7570 in_frame: 100,
7571 out_frame: 102,
7572 source: 0,
7573 link: None,
7574 eq: None,
7575 color: None,
7576 transform: None,
7577 fit: FitPolicy::Fit,
7578 speed: Speed::NORMAL,
7579 };
7580
7581 #[test]
7582 fn paste_mid_clip_splits_around_it() {
7583 let mut p = three();
7584 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
7585 assert_eq!(p.timeline_frames(), 11);
7586 assert_eq!(
7587 shape(&p)[0],
7588 vec![
7589 clip(0, 0, 3, 0),
7590 clip(3, 3, 5, 0),
7591 clip(5, 5, 6, 0),
7592 clip(6, 100, 102, 0),
7593 clip(8, 6, 9, 0),
7594 ]
7595 );
7596 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
7597 // The pasted frames are exactly where they were asked for, and the
7598 // split-off remainder resumes after them.
7599 assert_eq!(p.map_timeline(6), Some((3, 100)));
7600 assert_eq!(p.map_timeline(7), Some((3, 101)));
7601 assert_eq!(p.map_timeline(8), Some((4, 6)));
7602 }
7603
7604 #[test]
7605 fn paste_at_boundary_zero_and_end() {
7606 let mut p = three();
7607 assert!(p.paste(3, PASTED), "existing boundary: no split");
7608 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
7609 assert_eq!(p.map_timeline(3), Some((1, 100)));
7610
7611 let mut p = three();
7612 assert!(p.paste(0, PASTED));
7613 assert_eq!(p.map_timeline(0), Some((0, 100)));
7614 assert_eq!(p.map_timeline(2), Some((1, 0)));
7615
7616 // At the end: appended, there being nothing in front to leave black.
7617 let mut p = three();
7618 assert!(p.paste(9, PASTED));
7619 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
7620 // Past it: down on the frame it was asked for, black in front of it --
7621 // a row let go on the open bed lands under the ghost that promised it.
7622 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
7623 assert!(p.paste(1_000, PASTED));
7624 assert_eq!(p.timeline_frames(), 1_002);
7625 assert_eq!(
7626 p.lane(Lane::V1).last().expect("the pasted clip").start,
7627 1_000
7628 );
7629 assert_eq!(
7630 p.lane(Lane::A1).last().expect("its other half").start,
7631 1_000
7632 );
7633
7634 // An empty clip is the one thing refused, and it pushes no history.
7635 let mut p = three();
7636 assert!(!p.paste(4, clip(0, 7, 7, 0)));
7637 assert_eq!(p.clips().len(), 3);
7638 }
7639
7640 /// The data-loss paste: a clip of a source with no picture used to land on
7641 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
7642 /// carried it was refused on the way back in ("a box with a larger size").
7643 #[test]
7644 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
7645 let mut p = three();
7646 let wav = p.import("/nonexistent/song.wav", 0);
7647 let copied = Clip {
7648 fade_in: 0,
7649 fade_out: 0,
7650 transition_out: 0,
7651 visualizer: 0,
7652 viz_paint: 0,
7653 source: wav,
7654 ..PASTED
7655 };
7656 assert!(p.paste(3, copied));
7657 // The room is opened on every lane, or the two would slide apart...
7658 assert_eq!(p.timeline_frames(), 11);
7659 assert_eq!(
7660 shape(&p)[0],
7661 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
7662 "the video lane got room and nothing else"
7663 );
7664 // ...but the clip itself only reaches the lane that can play it.
7665 assert_eq!(
7666 shape(&p)[1],
7667 vec![
7668 clip(0, 0, 3, 0),
7669 clip(3, 100, 102, wav),
7670 clip(5, 3, 5, 0),
7671 clip(7, 5, 9, 0)
7672 ]
7673 );
7674 // A source with a picture is unchanged: still the grouped pair.
7675 let mut p = three();
7676 assert!(p.paste(3, PASTED));
7677 assert_eq!(shape(&p)[0], shape(&p)[1]);
7678 }
7679
7680 /// A hand-written file may hold a clip that ends at the very last frame
7681 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
7682 /// to wrap its start round to the front of the lane: an overlap in debug, a
7683 /// project no reload would accept in release.
7684 #[test]
7685 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
7686 let far = clip(u32::MAX - 90, 0, 90, 0);
7687 let parts = |c: Clip| {
7688 Project::from_parts(
7689 vec![Source::new(FILE, 0)],
7690 two(vec![c], vec![c]),
7691 Vec::new(),
7692 Vec::new(),
7693 Vec::new(),
7694 )
7695 .expect("valid parts")
7696 };
7697 let mut p = parts(far);
7698 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
7699 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
7700 assert!(!p.undo(), "...and pushes no history either");
7701 assert!(
7702 !p.paste(u32::MAX, PASTED),
7703 "appending has nowhere to go either: the timeline ends at the last frame"
7704 );
7705 // With room for exactly those frames the same paste is taken.
7706 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
7707 assert!(p.paste(0, PASTED));
7708 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
7709 }
7710
7711 #[test]
7712 fn paste_undoes_in_one_step() {
7713 let mut p = three();
7714 let before = shape(&p);
7715 assert!(p.paste(6, PASTED));
7716 assert!(p.undo());
7717 assert_eq!(shape(&p), before, "a paste is one undo step");
7718 }
7719
7720 #[test]
7721 fn a_copy_outlives_the_clip_it_came_from() {
7722 let mut p = three();
7723 let copied = p.clips()[1]; // [3,5)
7724 assert!(p.delete(1));
7725 // Just a frame range: the source is still on disk either way.
7726 assert!(p.paste(0, copied));
7727 assert_eq!(p.map_timeline(0), Some((0, 3)));
7728 assert_eq!(p.timeline_frames(), 9);
7729 }
7730
7731 #[test]
7732 fn delete_closes_the_gap_on_both_lanes() {
7733 let mut p = three();
7734 assert!(p.delete(1));
7735 assert_eq!(p.timeline_frames(), 7);
7736 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
7737 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
7738 // timeline 3 used to be source 3; the gap closed so it is source 5 now
7739 assert_eq!(p.map_timeline(3), Some((1, 5)));
7740 assert_eq!(p.map_timeline(6), Some((1, 8)));
7741 assert_eq!(p.map_timeline(7), None);
7742 }
7743
7744 #[test]
7745 fn delete_first_last_and_only() {
7746 let mut p = three();
7747 assert!(p.delete(0));
7748 assert_eq!(p.map_timeline(0), Some((0, 3)));
7749 assert_eq!(p.timeline_frames(), 6);
7750
7751 let mut p = three();
7752 assert!(p.delete(2));
7753 assert_eq!(p.timeline_frames(), 5);
7754 assert_eq!(p.map_timeline(4), Some((1, 4)));
7755
7756 assert!(!p.delete(2), "index past the end");
7757 assert!(p.delete(1));
7758 assert!(p.delete(0), "and the last remaining clip goes too");
7759 assert_eq!(p.clips().len(), 0);
7760 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
7761 assert!(!p.delete(0), "there is nothing left to delete");
7762 assert!(p.undo(), "one gesture, one undo");
7763 assert_eq!(p.clips().len(), 1);
7764 }
7765
7766 /// The offset model's point: one lane loses a clip, the other does not move.
7767 #[test]
7768 fn a_lift_leaves_a_gap_and_moves_nothing() {
7769 let mut p = three();
7770 let video_before = shape(&p)[0].clone();
7771 assert!(p.lift(Lane::A1, 1));
7772 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7773 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7774 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7775 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7776 assert_eq!(p.map(Lane::A1, 4), None);
7777 assert_eq!(
7778 p.span_at(Lane::A1, 3),
7779 Some(Span {
7780 start: 3,
7781 len: 2,
7782 from: None,
7783 speed: Speed::NORMAL
7784 })
7785 );
7786 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7787 assert!(p.undo());
7788 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7789 }
7790
7791 #[test]
7792 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7793 let mut p = three();
7794 assert!(p.lift(Lane::A1, 2));
7795 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7796 assert_eq!(
7797 p.span_at(Lane::A1, 5),
7798 Some(Span {
7799 start: 5,
7800 len: 4,
7801 from: None,
7802 speed: Speed::NORMAL
7803 }),
7804 "the audio lane holds silence to the end of the picture"
7805 );
7806 assert_eq!(p.span_at(Lane::A1, 9), None);
7807 // Every lane covers the timeline exactly, gaps included.
7808 for l in p.lanes() {
7809 let spans = p.spans_from(l, 0);
7810 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7811 assert_eq!(spans[0].start, 0);
7812 }
7813 }
7814
7815 /// The timeline is emptiable: the last placement comes off like any other,
7816 /// the project holds "nothing on any lane" as a state, and one undo per
7817 /// gesture brings it back.
7818 #[test]
7819 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7820 let mut p = Project::single(FILE, 9);
7821 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7822 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7823 assert_eq!(p.timeline_frames(), 0);
7824 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7825 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7826 assert!(!p.lift(Lane::A1, 0), "index past the end");
7827 assert!(p.undo(), "and the last lift comes back");
7828 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7829 // A saved-and-loaded empty timeline is a project like any other, and it
7830 // still names the file its frame rate came from.
7831 assert!(p.lift(Lane::V1, 0));
7832 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7833 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7834 let back = Project::from_parts(sources, lanes, eq, color, Vec::new())
7835 .expect("an empty project loads");
7836 assert_eq!(back.timeline_frames(), 0);
7837 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7838 }
7839
7840 /// What a keyboard selection walks: one answer per lane, gaps included --
7841 /// the composite's own answer is one lane's and cannot say what the audio
7842 /// lane holds under the same playhead.
7843 #[test]
7844 fn lane_clip_at_answers_for_each_lane_separately() {
7845 let mut p = Project::single(FILE, 9);
7846 assert!(p.split(3), "both lanes split");
7847 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7848 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7849 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7850 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7851 // A gap on one lane leaves the other's clip selectable there.
7852 assert!(p.lift(Lane::A1, 0));
7853 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7854 assert_eq!(
7855 p.lane_clip_at(Lane::A1, 3),
7856 Some(0),
7857 "indices moved with it"
7858 );
7859 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7860 // A lane that is not there is not a panic.
7861 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7862 }
7863
7864 #[test]
7865 fn place_overwrites_only_its_own_lane() {
7866 let mut p = three();
7867 let audio_before = shape(&p)[1].clone();
7868 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7869 // is trimmed, nothing shifts.
7870 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7871 assert_eq!(
7872 shape(&p)[0],
7873 vec![
7874 clip(0, 0, 3, 0),
7875 clip(3, 3, 4, 0),
7876 clip(4, 100, 102, 0),
7877 clip(6, 6, 9, 0),
7878 ]
7879 );
7880 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7881 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7882
7883 // Placed inside one clip, it splits it in two.
7884 let mut p = Project::single(FILE, 9);
7885 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7886 assert_eq!(
7887 shape(&p)[0],
7888 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7889 );
7890 // ...and placed past the end it makes a gap, which is the whole point.
7891 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7892 assert_eq!(p.timeline_frames(), 22);
7893 assert_eq!(
7894 p.span_at(Lane::V1, 9),
7895 Some(Span {
7896 start: 9,
7897 len: 11,
7898 from: None,
7899 speed: Speed::NORMAL
7900 })
7901 );
7902 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7903 }
7904
7905 /// A file with sound let go over a further video track: both halves go down,
7906 /// on the same frames, and the audio row is added when the `+ V` button left
7907 /// the project without one. One undo takes the lane and both clips back.
7908 #[test]
7909 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7910 let mut p = three();
7911 let v2 = p.add_lane(LaneKind::Video);
7912 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7913
7914 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7915 let a2 = Lane::new(LaneKind::Audio, 1);
7916 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7917 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7918 assert_eq!(p.lane(v2)[0].start, 4);
7919 assert_eq!(p.lane(v2)[0].end(), 6);
7920 assert_eq!(
7921 p.lane(v2)[0].link,
7922 p.lane(a2)[0].link,
7923 "one take, not two placements"
7924 );
7925 assert!(p.lane(v2)[0].link.is_some());
7926 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7927 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7928
7929 // The pair overwrites its own two lanes and nothing else, exactly as a
7930 // one-lane place does.
7931 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7932 assert_eq!(p.lane(v2), p.lane(a2));
7933 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7934 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7935
7936 assert!(p.undo(), "one step for the second pair");
7937 assert_eq!(p.lane(v2).len(), 1);
7938 assert!(p.undo(), "one step for the first pair *and* its lane");
7939 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7940 assert!(p.lane(v2).is_empty());
7941
7942 // Refusals cost nothing: sound placed alone is `place`'s door.
7943 assert!(
7944 !p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)),
7945 "audio lane"
7946 );
7947 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7948 assert!(
7949 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7950 "a lane that is not there"
7951 );
7952 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7953 }
7954
7955 /// The drag between tracks: let go at the frames it already covers the clip
7956 /// keeps them, one undo takes it back, and every way it can be refused
7957 /// leaves the project untouched.
7958 #[test]
7959 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7960 let v2 = Lane::new(LaneKind::Video, 1);
7961 let mut p = three();
7962 assert_eq!(p.add_lane(LaneKind::Video), v2);
7963 let before = shape(&p);
7964
7965 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7966 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7967 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7968 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7969 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7970 // One snapshot: a single undo, and the lane list survives it.
7971 assert!(p.undo());
7972 assert_eq!(shape(&p), before);
7973
7974 // A lane that is not there, the lane and frame it is already at, an
7975 // index that is not there, and a move across kinds: all refused,
7976 // nothing changed.
7977 let history = p.history.len();
7978 for (from, idx, to, start) in [
7979 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7980 (Lane::V1, 1, Lane::V1, 3),
7981 (Lane::V1, 9, v2, 3),
7982 (Lane::V1, 1, Lane::A1, 3),
7983 (Lane::A1, 1, v2, 3),
7984 ] {
7985 assert!(
7986 !p.move_clip(from, idx, to, start),
7987 "{from:?} {idx} -> {to:?} at {start}"
7988 );
7989 }
7990 assert_eq!(shape(&p), before);
7991 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7992
7993 // Landing on another clip is refused rather than overwriting it: the
7994 // pointer named the lane, never the take already sitting there.
7995 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7996 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7997 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7998 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7999 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
8000 }
8001
8002 /// The drag *along* a track, which is the one every other editor has: the
8003 /// clip lands on the frame the pointer let it go at, and stops dead against
8004 /// the neighbour rather than overwriting it.
8005 #[test]
8006 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
8007 let sources = vec![Source::new(FILE, 0)];
8008 let lanes = vec![
8009 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
8010 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
8011 ];
8012 let mut p =
8013 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
8014 let before = shape(&p);
8015
8016 // Into the gap, exactly where it was let go -- nothing else moves.
8017 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
8018 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
8019 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
8020 // Dragged past the clip in front of it: clamped to its wall, laid end
8021 // to end with it, never over it.
8022 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
8023 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
8024 // One undo per drag, and both of them together are the state it started
8025 // in -- the frames each clip plays never changed.
8026 assert!(p.undo() && p.undo());
8027 assert_eq!(shape(&p), before);
8028
8029 // A drop that changes nothing is a click, not an edit.
8030 let history = p.history.len();
8031 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
8032 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
8033 }
8034
8035 /// A drag carries the whole take: the sound half travels exactly as far as
8036 /// the picture does, and the tighter of their two walls stops both.
8037 #[test]
8038 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
8039 let mut p = three();
8040 assert!(
8041 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
8042 "room to the right"
8043 );
8044 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
8045 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
8046 // Something in the sound's way, and nothing at all in the picture's.
8047 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
8048 let before = shape(&p);
8049
8050 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
8051 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
8052 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
8053 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8054 assert!(p.undo());
8055 assert_eq!(shape(&p), before, "one undo for the whole take");
8056 }
8057
8058 /// The drag that does both at once -- another lane *and* another frame --
8059 /// which is what a pointer let go over a lane always names.
8060 #[test]
8061 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
8062 let v2 = Lane::new(LaneKind::Video, 1);
8063 let mut p = three();
8064 assert_eq!(p.add_lane(LaneKind::Video), v2);
8065
8066 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
8067 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
8068 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
8069 assert_eq!(
8070 p.lane(Lane::A1)[2].start,
8071 20,
8072 "its sound travelled the same distance"
8073 );
8074 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8075 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
8076 }
8077
8078 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
8079 /// [`three`] cuts up all nine of its frames.
8080 const SRC: &[u32] = &[9];
8081
8082 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
8083 /// else on the lane moves, and every wall stops the edge rather than
8084 /// refusing the gesture.
8085 #[test]
8086 fn trimming_the_tail_stops_at_every_wall() {
8087 let mut p = three();
8088
8089 // Pulled in: a gap opens behind it and the clip after it stays put.
8090 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
8091 assert_eq!(
8092 shape(&p)[0],
8093 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
8094 );
8095 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
8096 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
8097
8098 // ...and back out, no further than the clip behind it.
8099 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
8100 assert_eq!(
8101 shape(&p)[0][1],
8102 clip(3, 3, 5, 0),
8103 "stopped at the neighbour"
8104 );
8105 assert!(
8106 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
8107 "already at the wall"
8108 );
8109
8110 // One frame of clip always survives, however far back the pointer went.
8111 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
8112 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
8113
8114 // The last clip has no neighbour, so what stops it is the file: nine
8115 // frames is nine frames.
8116 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
8117 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
8118 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
8119 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
8120 // A source nobody told us the length of may not grow at all -- an
8121 // out-point past the end of a file is a save that will not open again.
8122 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
8123 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
8124 }
8125
8126 /// The head pulled in takes the in-point with it -- what stays plays what it
8127 /// always played -- and stops at the source's own first frame.
8128 #[test]
8129 fn trimming_the_head_moves_the_in_point() {
8130 let mut p = three();
8131 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
8132 assert_eq!(
8133 shape(&p)[0][0],
8134 clip(2, 2, 3, 0),
8135 "two frames off the front"
8136 );
8137 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
8138 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
8139 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
8140 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
8141 // One frame survives here too.
8142 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
8143 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
8144
8145 // A clip that does not begin at its source's first frame: its head goes
8146 // back to source frame 0 and not one frame further.
8147 let mut p = Project::single(FILE, 9);
8148 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
8149 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
8150 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
8151 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
8152 }
8153
8154 /// A clip whose in-point is *past* its own start -- what a ripple delete
8155 /// leaves, the piece in front of it gone and this one slid back to frame 0
8156 /// carrying the in-point the cut gave it. Its head has more source behind it
8157 /// than the timeline has room for, and the timeline's own first frame is the
8158 /// wall: asking is not an overflow, and the answer is 0.
8159 #[test]
8160 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
8161 let mut p = Project::single(FILE, 9);
8162 assert!(p.split(5));
8163 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
8164 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
8165
8166 assert_eq!(
8167 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
8168 Some((0, 3)),
8169 "back to frame 0 at most, and one frame of clip always survives"
8170 );
8171 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
8172 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
8173 assert_eq!(
8174 shape(&p)[0],
8175 vec![clip(2, 7, 9, 0)],
8176 "the in-point followed"
8177 );
8178 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
8179 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
8180 }
8181
8182 /// A still is trimmed from its head exactly as it is from its tail: it has
8183 /// no earlier frame to walk an in-point back to, so the wall is the length
8184 /// the caller's table allows it, measured back from the tail. Measured from
8185 /// the in-point -- which a placed picture has at 0 -- its left edge could
8186 /// never be dragged outwards at all.
8187 #[test]
8188 fn a_stills_head_stretches_out_like_its_tail() {
8189 const STILL: &str = "/nonexistent/card.png";
8190 /// What a still is held to, as `PlaybackSession` fills the table in.
8191 const CAP: &[u32] = &[60];
8192
8193 let mut p = Project::single(STILL, 20);
8194 assert!(p.lift(Lane::A1, 0), "a picture is silent");
8195 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
8196 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
8197
8198 // A source with no entry in the table may not grow, here as at the tail.
8199 assert_eq!(
8200 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
8201 Some((100, 119)),
8202 "a length nobody told us buys no head room"
8203 );
8204 assert_eq!(
8205 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
8206 Some((60, 119)),
8207 "back to a whole cap's worth, one frame of clip surviving"
8208 );
8209 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
8210 assert_eq!(
8211 shape(&p)[0][0],
8212 clip(80, 0, 40, 0),
8213 "twenty frames longer, and still read from the source's first frame"
8214 );
8215 // Past the cap is clamped, exactly as the tail is -- not refused.
8216 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
8217 assert_eq!(
8218 shape(&p)[0][0],
8219 clip(60, 0, 60, 0),
8220 "a cap's worth, no more"
8221 );
8222 // ...and the clip in front is the nearer wall of the two: no head trim
8223 // may open an overlap.
8224 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
8225 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
8226 assert_eq!(
8227 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
8228 Some((85, 119)),
8229 "up to the neighbour's last frame and not over it"
8230 );
8231 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
8232 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
8233 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
8234 }
8235
8236 /// Linked halves trim as one: a link is one span on however many lanes, so
8237 /// the sound follows the picture's edge -- and the tightest wall of the two
8238 /// is what stops both.
8239 #[test]
8240 fn linked_halves_trim_together() {
8241 let mut p = three();
8242 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
8243 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
8244
8245 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
8246 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
8247 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
8248 assert!(
8249 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
8250 "either half drags it"
8251 );
8252 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
8253 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8254
8255 // Something in the way on the *audio* lane stops the picture's tail as
8256 // well: the group can only go as far as its tightest member.
8257 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
8258 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
8259 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
8260 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
8261 links_are_consistent(&p.lanes).expect("still one span");
8262 }
8263
8264 /// A whole drag is one undo step -- the front-end commits once, at the
8265 /// release -- and an edge asked to stay where it is costs none at all.
8266 #[test]
8267 fn a_trim_is_one_undo_step() {
8268 let mut p = three();
8269 let before = shape(&p);
8270 let history = p.history.len();
8271
8272 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
8273 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
8274 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
8275 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
8276 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
8277 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
8278
8279 assert!(p.undo());
8280 assert_eq!(shape(&p), before, "both halves back, in one step");
8281 }
8282
8283 /// A moved half stays in its group: a link names a span, not a lane, so the
8284 /// picture on `V2` is still the same take as the sound under it on `A1`.
8285 #[test]
8286 fn move_clip_keeps_the_group() {
8287 let v2 = Lane::new(LaneKind::Video, 1);
8288 let mut p = three();
8289 p.add_lane(LaneKind::Video);
8290 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
8291 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
8292 assert!(p.move_clip(Lane::V1, 1, v2, 3));
8293 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
8294 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8295 assert_eq!(
8296 p.lane(v2)[0].start,
8297 p.lane(Lane::A1)[1].start,
8298 "and still covers the same span as its sound"
8299 );
8300 }
8301
8302 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
8303 /// head of a lane, between two clips, inside a clip, past the last one,
8304 /// and on a lane holding nothing at all.
8305 #[test]
8306 fn gap_at_finds_the_hole_a_frame_sits_in() {
8307 let mut p = Project::single(FILE, 1);
8308 let v = p.add_lane(LaneKind::Video);
8309 // Empty lane: nothing before and nothing after -- not a gap, since
8310 // there is nothing to ripple toward.
8311 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
8312
8313 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
8314 // Before the only clip: the gap runs from the timeline's own head.
8315 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
8316 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
8317 // Inside the clip: not a gap.
8318 assert_eq!(p.gap_at(v, 5), None);
8319 assert_eq!(p.gap_at(v, 7), None);
8320 // Past the only clip: the open end of the lane, not a gap -- there is
8321 // nothing after it to slide back.
8322 assert_eq!(p.gap_at(v, 8), None);
8323 assert_eq!(p.gap_at(v, 100), None);
8324
8325 assert!(
8326 p.place(v, 12, clip(12, 0, 2, 0)),
8327 "a second clip at [12,14)"
8328 );
8329 // Between the two: the gap [8,12).
8330 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
8331 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
8332 assert_eq!(p.gap_at(v, 14), None, "still the open end");
8333
8334 assert!(
8335 p.place(v, 8, clip(8, 0, 4, 0)),
8336 "fills [8,12) exactly, meeting both neighbours"
8337 );
8338 assert_eq!(
8339 p.gap_at(v, 8),
8340 None,
8341 "adjacent clips leave no frame to name a gap"
8342 );
8343 assert_eq!(p.gap_at(v, 11), None);
8344 }
8345
8346 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
8347 /// menu named: the clip after the gap slides back on that lane, a clip on
8348 /// another lane at the very same frame range does not move, and the whole
8349 /// close is one press of undo.
8350 #[test]
8351 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
8352 let mut p = Project::single(FILE, 1);
8353 let v = p.add_lane(LaneKind::Video);
8354 let a = p.add_lane(LaneKind::Audio);
8355 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
8356 assert!(
8357 p.place(a, 0, clip(0, 0, 3, 0)),
8358 "A clip at [0,3) -- outside the video lane's gap and this scope"
8359 );
8360 let before = shape(&p);
8361 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
8362 assert_eq!((start, len), (0, 5));
8363 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
8364 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
8365 assert_eq!(
8366 p.lane(a)[0].start,
8367 0,
8368 "the untouched lane's clip did not move"
8369 );
8370 assert!(p.undo(), "one press undoes the whole close");
8371 assert_eq!(shape(&p), before, "back to exactly where it was");
8372 }
8373
8374 /// A clip carrying an explicit link id -- what a
8375 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
8376 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
8377 /// already builds inline.
8378 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
8379 Clip {
8380 fade_in: 0,
8381 fade_out: 0,
8382 transition_out: 0,
8383 visualizer: 0,
8384 viz_paint: 0,
8385 start,
8386 in_frame,
8387 out_frame,
8388 source: 0,
8389 link: Some(link),
8390 eq: None,
8391 color: None,
8392 transform: None,
8393 fit: FitPolicy::default(),
8394 speed: Speed::NORMAL,
8395 }
8396 }
8397
8398 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
8399 /// bordered by a linked take whose `A1` half is empty across the very
8400 /// same stretch widens the scope to both lanes, so the ripple carries the
8401 /// take rather than tearing it -- and one undo puts both halves back.
8402 #[test]
8403 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
8404 let sources = vec![Source::new(FILE, 0)];
8405 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8406 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8407 let mut p = Project::from_parts(
8408 sources,
8409 two(video, audio),
8410 Vec::new(),
8411 Vec::new(),
8412 Vec::new(),
8413 )
8414 .expect("valid parts");
8415 let before = shape(&p);
8416 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8417 assert_eq!(
8418 p.gap_at(Lane::A1, 3),
8419 Some((3, 2)),
8420 "the same stretch is empty on A1 too"
8421 );
8422
8423 let scope = p
8424 .gap_take_scope(Lane::V1, 3, 2)
8425 .expect("a matching gap on both halves widens the scope");
8426 assert_eq!(scope.len(), 2, "the take's other lane joins");
8427 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
8428
8429 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
8430 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
8431 assert_eq!(
8432 p.lane(Lane::A1)[1].start,
8433 3,
8434 "A1's far half rode along, in sync"
8435 );
8436 assert!(p.undo(), "one press undoes the whole close");
8437 assert_eq!(shape(&p), before, "back to exactly where it was");
8438 }
8439
8440 /// The real design question: a take whose gap is not the *same size* on
8441 /// both lanes cannot ripple by one number without pulling a lane's clip
8442 /// out from under the other's sync -- refused by name, with the frame
8443 /// naming which lane is out of step, rather than silently taking real
8444 /// media off the shorter side.
8445 #[test]
8446 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
8447 let sources = vec![Source::new(FILE, 0)];
8448 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8449 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
8450 // shorter than V1's [3,5) -- a legal offset-preserving group, and
8451 // still one take.
8452 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
8453 let p = Project::from_parts(
8454 sources,
8455 two(video, audio),
8456 Vec::new(),
8457 Vec::new(),
8458 Vec::new(),
8459 )
8460 .expect("valid parts");
8461 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8462 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
8463
8464 let err = p
8465 .gap_take_scope(Lane::V1, 3, 2)
8466 .expect_err("a mismatched gap cannot ripple by one number")
8467 .to_string();
8468 assert!(err.contains("A1"), "{err}");
8469 assert!(err.contains("out of sync"), "{err}");
8470 }
8471
8472 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
8473 /// there -- cannot close without cutting that audio out from under
8474 /// nothing asked to touch it: refused, not widened silently past.
8475 #[test]
8476 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
8477 let sources = vec![Source::new(FILE, 0)];
8478 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8479 // A1 plays through the whole span as one continuous clip, sharing
8480 // V1's first-half link: nothing empty at frame 3 there at all.
8481 let audio = vec![linked(0, 0, 9, 1)];
8482 let p = Project::from_parts(
8483 sources,
8484 two(video, audio),
8485 Vec::new(),
8486 Vec::new(),
8487 Vec::new(),
8488 )
8489 .expect("valid parts");
8490 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8491 assert_eq!(
8492 p.gap_at(Lane::A1, 3),
8493 None,
8494 "A1 plays through, no gap there"
8495 );
8496
8497 let err = p
8498 .gap_take_scope(Lane::V1, 3, 2)
8499 .expect_err("a solid partner cannot ripple with the gap")
8500 .to_string();
8501 assert!(err.contains("A1"), "{err}");
8502 assert!(err.contains("detach"), "{err}");
8503 }
8504
8505 /// The sweep is the single-gap close repeated on one lane, but measured once
8506 /// and applied from the right. The differing gap lengths here expose a
8507 /// front-to-back bug: the last clip would be cut against a stale frame after
8508 /// the first gap shifted it.
8509 #[test]
8510 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
8511 let mut p = Project::single(FILE, 1);
8512 let v = p.add_lane(LaneKind::Video);
8513 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
8514 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
8515 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
8516 let before = shape(&p);
8517
8518 assert_eq!(p.gap_count(v), 3);
8519 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
8520 assert_eq!(report.closed, 3);
8521 assert!(report.skipped.is_empty());
8522 assert_eq!(
8523 p.lane(v),
8524 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
8525 "all gaps closed without eating source frames"
8526 );
8527 assert!(p.undo(), "one undo for the whole sweep");
8528 assert_eq!(shape(&p), before);
8529 }
8530
8531 /// Empty, already-contiguous and tail-only lanes are not controls that do
8532 /// work. A single clip with a head gap does close, because there is a real
8533 /// placement to ripple back.
8534 #[test]
8535 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
8536 let mut p = Project::single(FILE, 9);
8537 let v = p.add_lane(LaneKind::Video);
8538 let history = p.history.len();
8539 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
8540 assert_eq!(
8541 report,
8542 GapSweep::default(),
8543 "an empty lane has no bounded gap"
8544 );
8545 assert_eq!(p.history.len(), history, "no undo step for a no-op");
8546
8547 let mut p = Project::single(FILE, 9);
8548 let v = p.add_lane(LaneKind::Video);
8549 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
8550 let before = shape(&p);
8551 let report = p
8552 .close_all_gaps_on_lane(v)
8553 .expect("single clip lane exists");
8554 assert_eq!(report.closed, 1, "the head gap closes");
8555 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8556 assert!(p.undo());
8557 assert_eq!(shape(&p), before);
8558
8559 let mut p = Project::single(FILE, 9);
8560 let history = p.history.len();
8561 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8562 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
8563 assert_eq!(p.history.len(), history);
8564
8565 let mut p = Project::single(FILE, 9);
8566 let v = p.add_lane(LaneKind::Video);
8567 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
8568 let history = p.history.len();
8569 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
8570 assert_eq!(
8571 report,
8572 GapSweep::default(),
8573 "the open-ended tail is not closed"
8574 );
8575 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8576 assert_eq!(p.history.len(), history);
8577 }
8578
8579 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
8580 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
8581 /// while V1's [6,9) has only [6,8) empty on A1.
8582 #[test]
8583 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
8584 let sources = vec![Source::new(FILE, 0)];
8585 let video = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(9, 9, 11, 0)];
8586 let audio = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(8, 8, 11, 0)];
8587 let mut p = Project::from_parts(
8588 sources,
8589 two(video, audio),
8590 Vec::new(),
8591 Vec::new(),
8592 Vec::new(),
8593 )
8594 .expect("valid parts");
8595 let before = shape(&p);
8596
8597 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8598 assert_eq!(report.closed, 1);
8599 assert_eq!(report.skipped.len(), 1);
8600 assert_eq!(report.skipped[0].start, 6);
8601 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
8602 assert!(
8603 report.skipped[0].reason.contains("out of sync"),
8604 "{report:?}"
8605 );
8606
8607 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
8608 assert_eq!(
8609 p.lane(Lane::A1)[1].start,
8610 2,
8611 "and its other half stayed in sync"
8612 );
8613 assert_eq!(
8614 p.lane(Lane::V1)[2].start,
8615 7,
8616 "the skipped later gap remains"
8617 );
8618 assert_eq!(
8619 p.lane(Lane::A1)[2].start,
8620 6,
8621 "A1's shorter gap remains shorter"
8622 );
8623 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
8624 assert!(p.undo(), "one undo restores every closed gap");
8625 assert_eq!(shape(&p), before);
8626 }
8627
8628 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
8629 /// their own caption storage: head gaps and gaps between cues count, an
8630 /// empty lane and the tail after the last cue do not.
8631 #[test]
8632 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
8633 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8634 let s = p.add_lane(LaneKind::Subtitle);
8635 assert_eq!(
8636 p.gap_at(s, 0),
8637 None,
8638 "an empty subtitle lane has nothing to close"
8639 );
8640
8641 p.place_sub(s, 5, caption(0, 3))
8642 .expect("single cue at [5,8)");
8643 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
8644 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
8645 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
8646 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
8647
8648 p.place_sub(s, 12, caption(0, 2))
8649 .expect("second cue at [12,14)");
8650 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
8651 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
8652 assert_eq!(
8653 p.gap_at(s, 14),
8654 None,
8655 "tail after the last cue is still open-ended"
8656 );
8657 }
8658
8659 /// Closing a caption gap ripples the subtitle lane only. It is not a media
8660 /// take close, so the video and audio lanes keep their frame positions.
8661 #[test]
8662 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
8663 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8664 let s = p.add_lane(LaneKind::Subtitle);
8665 p.place_sub(s, 5, caption(0, 3))
8666 .expect("single cue at [5,8)");
8667 let before_clips = shape(&p);
8668 let before_subs = p.sub_lane(s).to_vec();
8669
8670 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
8671 assert_eq!((start, len), (0, 5));
8672 p.cut_regions(&[(start, len)], &[s])
8673 .expect("caption lane gap closes");
8674
8675 assert_eq!(shape(&p), before_clips, "media lanes did not move");
8676 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
8677 assert!(p.undo(), "one undo restores the caption close");
8678 assert_eq!(shape(&p), before_clips);
8679 assert_eq!(p.sub_lane(s), before_subs);
8680 }
8681
8682 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
8683 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
8684 /// history entry for empty or already-contiguous lanes.
8685 #[test]
8686 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
8687 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8688 let s = p.add_lane(LaneKind::Subtitle);
8689 let history = p.history.len();
8690 let report = p
8691 .close_all_gaps_on_lane(s)
8692 .expect("empty subtitle lane exists");
8693 assert_eq!(
8694 report,
8695 GapSweep::default(),
8696 "empty subtitle lane has no bounded gap"
8697 );
8698 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
8699
8700 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
8701 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
8702 p.place_sub(s, 14, caption(0, 1))
8703 .expect("middle gap [9,14), tail after 15");
8704 let before = p.sub_lane(s).to_vec();
8705
8706 assert_eq!(p.gap_count(s), 3);
8707 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8708 assert_eq!(report.closed, 3);
8709 assert!(report.skipped.is_empty());
8710 assert_eq!(
8711 p.sub_lane(s),
8712 &[caption(0, 2), caption(2, 2), caption(4, 1)],
8713 "all bounded caption gaps closed without touching windows"
8714 );
8715 assert!(p.undo(), "one undo restores every caption gap");
8716 assert_eq!(p.sub_lane(s), before);
8717
8718 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8719 let s = p.add_lane(LaneKind::Subtitle);
8720 p.place_sub(s, 0, caption(0, 3))
8721 .expect("contiguous at the head");
8722 let history = p.history.len();
8723 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8724 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
8725 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
8726 assert_eq!(p.history.len(), history);
8727 }
8728
8729 #[test]
8730 fn ripple_delete_spans_partial_clips() {
8731 let mut p = three();
8732 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
8733 assert!(p.ripple_delete(2, 4));
8734 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
8735 assert_eq!(shape(&p)[1], shape(&p)[0]);
8736 assert_eq!(p.timeline_frames(), 5);
8737 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
8738 assert!(p.undo());
8739 assert_eq!(shape(&p), shape(&three()));
8740 // One that takes everything is a delete like any other: the timeline
8741 // empties, and the undo it cost brings it back whole.
8742 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
8743 assert_eq!(p.timeline_frames(), 0);
8744 assert!(
8745 !p.ripple_delete(0, 100),
8746 "and a delete with nothing left to take is not an undo step"
8747 );
8748 assert!(p.undo());
8749 assert_eq!(shape(&p), shape(&three()));
8750 }
8751
8752 #[test]
8753 fn undo_restores_exactly() {
8754 let mut p = three();
8755 let after_splits = shape(&p);
8756 assert!(p.delete(1));
8757 assert!(p.undo());
8758 assert_eq!(shape(&p), after_splits);
8759
8760 // walk all the way back through both splits, then run dry
8761 assert!(p.undo());
8762 assert_eq!(p.clips().len(), 2);
8763 assert!(p.undo());
8764 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8765 assert!(!p.undo(), "empty history");
8766 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8767 }
8768
8769 #[test]
8770 fn redo_restores_exactly() {
8771 let mut p = three();
8772 assert!(p.delete(1));
8773 let after_delete = p.parts();
8774 assert!(p.undo());
8775 assert!(p.redo());
8776 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
8777 assert!(!p.redo(), "empty redo stack");
8778 }
8779
8780 #[test]
8781 fn edit_after_undo_empties_redo() {
8782 let mut p = three();
8783 assert!(p.delete(1));
8784 assert!(p.undo());
8785 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
8786 assert!(p.split(1), "a fresh edit");
8787 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
8788 assert!(!p.redo(), "so redo has nothing left");
8789 }
8790
8791 #[test]
8792 fn redo_on_empty_stack_is_false() {
8793 let mut p = three();
8794 assert!(!p.redo(), "nothing has been undone yet");
8795 }
8796
8797 /// Past the cap the *oldest* step goes, so a long session undoes exactly
8798 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
8799 #[test]
8800 fn history_stops_at_the_cap() {
8801 let mut p = Project::single(FILE, 400);
8802 for frame in 1..=150 {
8803 assert!(p.split(frame), "split {frame} is an edit");
8804 }
8805 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
8806 for step in 0..HISTORY_CAP {
8807 assert!(p.undo(), "undo {step} is inside the cap");
8808 }
8809 assert!(!p.undo(), "and the 101st has nothing left to take");
8810 // 100 undos off 150 splits is the timeline after the 50th: the older
8811 // steps were dropped, not the newer ones.
8812 assert_eq!(p.clips().len(), 51);
8813 }
8814
8815 /// Undo/redo by hand across a split must never merge two takes into one
8816 /// group by reusing an id.
8817 #[test]
8818 fn group_ids_are_never_reused() {
8819 let mut p = Project::single(FILE, 9);
8820 assert!(p.split(3));
8821 let first = p.clips()[1].link;
8822 assert!(p.undo());
8823 assert!(p.split(5));
8824 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
8825 }
8826
8827 #[test]
8828 fn segments_from_reads_the_audio_lane() {
8829 let p = three();
8830 // mid-clip: partial first segment, whole clips after it
8831 assert_eq!(
8832 p.segments_from(4, FPS),
8833 vec![
8834 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8835 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8836 ]
8837 );
8838 // on a boundary: nothing partial
8839 assert_eq!(
8840 p.segments_from(3, FPS),
8841 vec![
8842 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
8843 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8844 ]
8845 );
8846 // from the top: one entry per clip
8847 assert_eq!(p.segments_from(0, FPS).len(), 3);
8848 // last clip only
8849 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
8850 // past the end / unusable fps
8851 assert!(p.segments_from(9, FPS).is_empty());
8852 assert!(p.segments_from(0, 0.0).is_empty());
8853 assert!(p.segments_from(0, f64::NAN).is_empty());
8854 }
8855
8856 #[test]
8857 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
8858 let mut p = three();
8859 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
8860 assert_eq!(
8861 p.segments_from(0, FPS),
8862 vec![
8863 (Some(0), 0.0, 3.0 / 30.0),
8864 (None, 0.0, 2.0 / 30.0),
8865 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8866 ]
8867 );
8868 // The list still covers exactly the timeline: that is what stops the
8869 // master clock stalling at the hole.
8870 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8871 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
8872 // Starting inside the gap trims the silence, not the clip after it.
8873 assert_eq!(
8874 p.segments_from(4, FPS),
8875 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
8876 );
8877 // ...and a lane that is nothing but gap is a run of silence.
8878 assert!(p.lift(Lane::A1, 0));
8879 assert!(p.lift(Lane::A1, 0));
8880 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
8881 }
8882
8883 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
8884 /// of source 0 then [0,4) of source 1.
8885 fn two_sources() -> Project {
8886 let mut p = three();
8887 let s = p.import(FILE2, 0);
8888 assert_eq!(s, 1);
8889 assert!(p.append_clip(s, 4));
8890 p
8891 }
8892
8893 #[test]
8894 fn import_dedups_and_appends() {
8895 let mut p = Project::single(FILE, 9);
8896 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
8897 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
8898 assert_eq!(p.import(FILE2, 0), 1);
8899 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
8900 // ...but the same file on another audio stream is another source: it is
8901 // what a clip names, and a clip plays exactly one stream.
8902 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
8903 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
8904 assert_eq!(p.sources()[2].audio_stream, 1);
8905 assert!(p.append_clip(2, 4), "a stream entry is placeable");
8906 assert!(p.undo());
8907 assert_eq!(p.sources().len(), 3);
8908 assert!(!p.append_clip(3, 5), "unknown source index");
8909 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
8910
8911 // Two spellings of one real file are one source: this is the case the
8912 // raw-path comparison above would get wrong.
8913 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
8914 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
8915 let mut p = Project::single(here, 9);
8916 assert_eq!(p.import(detour, 0), 0);
8917 assert_eq!(p.sources().len(), 1);
8918 }
8919
8920 #[test]
8921 fn append_clip_is_one_undo_step() {
8922 let mut p = two_sources();
8923 assert_eq!(p.timeline_frames(), 13);
8924 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
8925 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
8926 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
8927 assert!(p.undo());
8928 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
8929 assert_eq!(
8930 p.sources().len(),
8931 2,
8932 "the orphan source entry stays -- indexes are forever"
8933 );
8934 // ...and it is still usable, so a redo-by-hand costs no reimport.
8935 assert!(p.append_clip(1, 0));
8936 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
8937 }
8938
8939 #[test]
8940 fn edits_carry_the_source_along() {
8941 let mut p = two_sources();
8942 // A split inside the second source splits into two source-1 clips.
8943 assert!(p.split(11));
8944 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
8945 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
8946
8947 // A source-1 clip pasted into source-0 territory keeps its file, and so
8948 // does the source-0 half that got split off around it.
8949 let copied = p.clips()[4];
8950 assert!(p.paste(1, copied));
8951 assert_eq!(p.clips()[1].source, 1);
8952 assert_eq!(p.clips()[1].in_frame, 2);
8953 assert_eq!(p.clips()[2].source, 0);
8954 assert!(p.undo());
8955 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
8956 }
8957
8958 #[test]
8959 fn segments_from_names_the_source() {
8960 let p = two_sources();
8961 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
8962 assert_eq!(
8963 p.segments_from(4, FPS),
8964 vec![
8965 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8966 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8967 (Some(1), 0.0, 4.0 / 30.0),
8968 ]
8969 );
8970 // Mid-clip in source 1: only that source is left.
8971 assert_eq!(
8972 p.segments_from(10, FPS),
8973 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
8974 );
8975 assert!(p.segments_from(13, FPS).is_empty());
8976 // Segments still cover exactly the timeline across the join.
8977 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8978 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
8979 }
8980
8981 #[test]
8982 fn segments_follow_deletes_and_fps() {
8983 let mut p = three();
8984 assert!(p.delete(0));
8985 // source seconds, not timeline: deleting the head does not shift them
8986 let segs = p.segments_from(0, 25.0);
8987 assert_eq!(
8988 segs,
8989 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
8990 );
8991 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
8992 assert!(
8993 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
8994 "segments must cover exactly the timeline: {played}"
8995 );
8996 }
8997
8998 #[test]
8999 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
9000 // Import a second file, undo it: source 1 is now an orphan.
9001 let mut p = two_sources();
9002 assert!(p.undo());
9003 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9004 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
9005 assert!(eq.is_empty(), "and a project with no equalizer writes none");
9006 assert!(color.is_empty(), "nor a colour it never graded with");
9007 assert_eq!(
9008 lanes,
9009 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
9010 "the clips are untouched"
9011 );
9012
9013 // Three sources where only the middle one is orphaned: the survivors
9014 // renumber, and the clips follow.
9015 let mut p = Project::single(FILE, 9);
9016 assert_eq!(p.import(FILE2, 0), 1);
9017 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
9018 assert!(p.append_clip(2, 4));
9019 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9020 assert_eq!(
9021 sources,
9022 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
9023 );
9024 assert_eq!(
9025 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
9026 [0, 1]
9027 );
9028 // ...and what comes out is loadable, with the same timeline.
9029 let reloaded =
9030 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
9031 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
9032 assert_eq!(reloaded.sources().len(), 2);
9033 }
9034
9035 /// Taking a file out of the library: refused by name -- lanes and counts --
9036 /// while a clip still plays from it, and once nothing does, the entry goes
9037 /// and every clip that indexed past it is renumbered onto the short list.
9038 #[test]
9039 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
9040 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
9041 // plus a second stream of FILE as source 2 with a take of its own.
9042 let mut p = two_sources();
9043 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
9044 assert!(p.append_clip(2, 4));
9045
9046 let refusal = p
9047 .remove_source(1)
9048 .expect_err("a source with clips on it cannot go")
9049 .to_string();
9050 assert!(refusal.contains(FILE2), "names the file: {refusal}");
9051 assert!(
9052 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
9053 "names the lanes holding it: {refusal}"
9054 );
9055 assert!(refusal.contains("still plays"), "{refusal}");
9056 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
9057 assert_eq!(shape(&p)[0][3].source, 1);
9058
9059 // Delete FILE2's take -- the whole span, on every lane -- and the entry
9060 // is free to go. Source 2's clips become source 1's.
9061 assert!(p.delete_in(Lane::V1, 3));
9062 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
9063 p.remove_source(1).expect("nothing plays FILE2 any more");
9064 assert_eq!(
9065 p.sources(),
9066 [Source::new(FILE, 0), Source::new(FILE, 1)],
9067 "the middle entry is gone"
9068 );
9069 assert_eq!(
9070 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
9071 [0, 0, 0, 1],
9072 "the clips past it renumbered"
9073 );
9074 assert_eq!(
9075 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
9076 [0, 0, 0, 1],
9077 "on every lane"
9078 );
9079 // What is left is a project that still loads, which is the whole point
9080 // of renumbering rather than leaving a hole.
9081 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9082 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
9083 }
9084
9085 /// The two edges of a removal: it retires the undo stack (the corner-cut on
9086 /// [`Project::remove_source`]), and the last entry goes like any other
9087 /// once nothing plays it -- a project may name no file at all.
9088 #[test]
9089 fn remove_source_retires_undo_and_empties_the_library() {
9090 let mut p = two_sources();
9091 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
9092 assert!(!p.history.is_empty(), "there is something to undo");
9093 p.remove_source(1).expect("nothing plays FILE2");
9094 assert!(
9095 p.history.is_empty(),
9096 "a snapshot naming the removed source must not survive it"
9097 );
9098 assert!(!p.undo(), "and so there is nothing left to undo");
9099
9100 // The last file standing is held to the one rule every row is -- what
9101 // plays cannot go -- and to no other.
9102 assert_eq!(p.sources().len(), 1);
9103 let refusal = p
9104 .remove_source(0)
9105 .expect_err("its clips are still on the lanes")
9106 .to_string();
9107 assert!(refusal.contains("still plays"), "{refusal}");
9108 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
9109 while p.delete_in(Lane::V1, 0) {}
9110 p.remove_source(0)
9111 .expect("the last row goes like any other");
9112 assert!(
9113 p.sources().is_empty(),
9114 "a project may name no file at all: an empty library over an empty timeline"
9115 );
9116 assert_eq!(p.timeline_frames(), 0);
9117 assert!(
9118 p.remove_source(0).is_err(),
9119 "and an index that is not there is refused, not panicked on"
9120 );
9121 }
9122
9123 /// A clip's equalizer is the clip's: it survives every edit that copies a
9124 /// placement, and it comes back with an undo.
9125 #[test]
9126 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
9127 let mut p = three();
9128 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
9129 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
9130 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
9131 assert!(
9132 p.eq_of(Lane::V1, 0).is_none(),
9133 "one clip, not the lane above"
9134 );
9135
9136 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
9137 assert!(p.split(1));
9138 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
9139 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
9140 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
9141
9142 // A clipboard copy carries it -- onto another lane, at that.
9143 let copied = p.lane(Lane::A1)[1];
9144 assert!(p.place(Lane::V1, 20, copied));
9145 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
9146 assert!(p.undo());
9147 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
9148
9149 // ...and a change to one is one undo step, in both directions.
9150 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
9151 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
9152 assert!(p.undo());
9153 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
9154 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
9155 assert!(p.eq_of(Lane::A1, 0).is_none());
9156 assert!(p.undo());
9157 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
9158
9159 // Two refusals, neither of which costs an undo step.
9160 let mut nan = band_at(1);
9161 nan.bands[0].q = f32::INFINITY;
9162 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
9163 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
9164 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
9165 assert!(p.undo());
9166 assert_eq!(
9167 p.lane(Lane::A1).len(),
9168 3,
9169 "one step back is before the split"
9170 );
9171 assert!(p.undo());
9172 assert!(
9173 p.eq_of(Lane::A1, 0).is_none(),
9174 "and the next is before the setting: the refusals pushed none"
9175 );
9176 }
9177
9178 /// The table is append-only within a session, exactly as the sources are, so
9179 /// an undone setting is still in it -- and a save is where it goes.
9180 #[test]
9181 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
9182 let mut p = three();
9183 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
9184 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
9185 assert!(p.undo(), "back to the first setting");
9186 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
9187
9188 let (_, lanes, eq, _, _) = p.without_orphan_sources();
9189 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
9190 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
9191 assert_eq!(lanes[0].1[1].eq, None);
9192
9193 // One curve on three clips is one entry: settings that are equal share.
9194 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
9195 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
9196 let (_, lanes, eq, _, _) = p.without_orphan_sources();
9197 assert_eq!(eq.len(), 1, "equal settings share their entry");
9198 assert_eq!(lanes[1].1[2].eq, Some(0));
9199 reloads(&p, "an equalizer that outlived an undo");
9200 }
9201
9202 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
9203 /// grade is the clip's, through every edit that copies a placement.
9204 #[test]
9205 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
9206 let mut p = three();
9207 assert!(
9208 p.color_of(Lane::V1, 0).is_none(),
9209 "a fresh clip is ungraded"
9210 );
9211 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
9212 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9213 assert!(
9214 p.color_of(Lane::A1, 0).is_none(),
9215 "one clip, not the lane below"
9216 );
9217 assert!(
9218 p.eq_of(Lane::V1, 0).is_none(),
9219 "and a grade is not an equalizer"
9220 );
9221
9222 // Cutting a graded clip must not grade half of it: both halves inherit.
9223 assert!(p.split(1));
9224 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9225 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
9226 assert!(
9227 p.color_of(Lane::V1, 2).is_none(),
9228 "the clip after it is ungraded"
9229 );
9230
9231 // A clipboard copy carries it -- onto another lane, at that.
9232 let copied = p.lane(Lane::V1)[1];
9233 assert!(p.place(Lane::A1, 20, copied));
9234 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
9235 assert!(p.undo());
9236 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
9237
9238 // ...and a change to one is one undo step, in both directions.
9239 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
9240 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
9241 assert!(p.undo());
9242 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9243 assert!(
9244 p.set_color(Lane::V1, 0, None),
9245 "and taking it off is an edit"
9246 );
9247 assert!(p.color_of(Lane::V1, 0).is_none());
9248 assert!(p.undo());
9249 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9250
9251 // Two refusals, neither of which costs an undo step.
9252 let nan = ColorParams {
9253 contrast: f32::NAN,
9254 ..grade_at(1)
9255 };
9256 assert!(
9257 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
9258 "no clip there"
9259 );
9260 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
9261 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9262 assert!(p.undo());
9263 assert_eq!(
9264 p.lane(Lane::V1).len(),
9265 3,
9266 "one step back is before the split"
9267 );
9268 assert!(p.undo());
9269 assert!(
9270 p.color_of(Lane::V1, 0).is_none(),
9271 "and the next is before the grade: the refusals pushed none"
9272 );
9273 }
9274
9275 /// A slider drag is one gesture: the press snapshots, every sample after it
9276 /// only regrades, and the single undo lands on what the clip was *before*
9277 /// the hand touched it -- not one step back down the drag.
9278 #[test]
9279 fn a_whole_colour_drag_undoes_in_one_step() {
9280 let mut p = three();
9281 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
9282 for n in 2..=8 {
9283 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
9284 }
9285 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
9286 assert!(p.undo());
9287 assert!(
9288 p.color_of(Lane::V1, 0).is_none(),
9289 "one undo is the whole gesture, back to ungraded"
9290 );
9291
9292 // The live write refuses what the snapshotting one refuses, and a
9293 // refusal still costs no history either way.
9294 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
9295 assert!(!p.set_color_live(
9296 Lane::V1,
9297 0,
9298 Some(ColorParams {
9299 contrast: f32::NAN,
9300 ..grade_at(1)
9301 })
9302 ));
9303 assert!(p.undo());
9304 assert_eq!(
9305 p.lane(Lane::V1).len(),
9306 2,
9307 "the next step back is the split before the drag: no sample pushed one"
9308 );
9309 }
9310
9311 /// A drag across the colour wheel is one gesture -- the look's twin of
9312 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
9313 /// sample after it only repaints, and the single undo lands on the look
9314 /// the clip had *before* the hand touched it. The committing setter is
9315 /// still exactly one step, refusals included.
9316 #[test]
9317 fn a_whole_look_drag_undoes_in_one_step() {
9318 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
9319 let mut p = three();
9320 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
9321 for hue in 2..=8u8 {
9322 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
9323 }
9324 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
9325 assert!(p.undo());
9326 assert_eq!(
9327 p.lane(Lane::V1)[0].viz_paint,
9328 0,
9329 "one undo is the whole gesture, back to the default look"
9330 );
9331
9332 // The live write refuses an index that is not there -- and a refusal
9333 // costs no history -- while one committing write is one step back.
9334 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
9335 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
9336 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
9337 assert!(p.undo());
9338 assert_eq!(
9339 p.lane(Lane::V1)[0].viz_paint,
9340 0,
9341 "the committing setter is one undo step, no more"
9342 );
9343 }
9344
9345 /// The colour table is append-only within a session, exactly as the eq one
9346 /// is -- and a save is where an undone grade goes.
9347 #[test]
9348 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
9349 let mut p = three();
9350 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
9351 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
9352 assert!(p.undo(), "back to the first grade");
9353 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
9354
9355 let (_, lanes, _, color, _) = p.without_orphan_sources();
9356 assert_eq!(
9357 color,
9358 vec![grade_at(1)],
9359 "what nothing plays is not written"
9360 );
9361 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
9362 assert_eq!(lanes[0].1[1].color, None);
9363
9364 // One grade on three clips is one entry: settings that are equal share.
9365 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
9366 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
9367 let (_, lanes, _, color, _) = p.without_orphan_sources();
9368 assert_eq!(color.len(), 1, "equal grades share their entry");
9369 assert_eq!(lanes[1].1[2].color, Some(0));
9370 reloads(&p, "a colour that outlived an undo");
9371
9372 // An equalizer and a grade on one clip are two independent tables.
9373 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
9374 let (_, lanes, eq, color, _) = p.without_orphan_sources();
9375 assert_eq!((eq.len(), color.len()), (1, 1));
9376 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
9377 }
9378
9379 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
9380 /// placement is the clip's, through every edit that copies one.
9381 #[test]
9382 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
9383 let mut p = three();
9384 assert!(
9385 p.transform_of(Lane::V1, 0).is_none(),
9386 "a fresh clip is untransformed"
9387 );
9388 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9389 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9390 assert!(
9391 p.transform_of(Lane::A1, 0).is_none(),
9392 "one clip, not the lane below"
9393 );
9394 assert!(
9395 p.color_of(Lane::V1, 0).is_none(),
9396 "and a placement is not a grade"
9397 );
9398
9399 // Cutting a transformed clip must not transform half of it: both
9400 // halves inherit.
9401 assert!(p.split(1));
9402 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9403 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
9404 assert!(
9405 p.transform_of(Lane::V1, 2).is_none(),
9406 "the clip after it is untransformed"
9407 );
9408
9409 // A clipboard copy carries it -- onto another lane, at that.
9410 let copied = p.lane(Lane::V1)[1];
9411 assert!(p.place(Lane::A1, 20, copied));
9412 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
9413 assert!(p.undo());
9414 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
9415
9416 // ...and a change to one is one undo step, in both directions.
9417 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
9418 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
9419 assert!(p.undo());
9420 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9421 assert!(
9422 p.set_transform(Lane::V1, 0, None),
9423 "and taking it off is an edit"
9424 );
9425 assert!(p.transform_of(Lane::V1, 0).is_none());
9426 assert!(p.undo());
9427 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9428
9429 // Two refusals, neither of which costs an undo step.
9430 let nan = TransformParams {
9431 scale: f32::NAN,
9432 ..transform_at(1)
9433 };
9434 assert!(
9435 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
9436 "no clip there"
9437 );
9438 assert!(
9439 !p.set_transform(Lane::V1, 0, Some(nan)),
9440 "not a finite value"
9441 );
9442 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9443 assert!(p.undo());
9444 assert_eq!(
9445 p.lane(Lane::V1).len(),
9446 3,
9447 "one step back is before the split"
9448 );
9449 assert!(p.undo());
9450 assert!(
9451 p.transform_of(Lane::V1, 0).is_none(),
9452 "and the next is before the placement: the refusals pushed none"
9453 );
9454 }
9455
9456 /// The transform table is append-only within a session, exactly as the eq
9457 /// and colour ones are -- and a save is where an undone placement goes.
9458 #[test]
9459 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
9460 let mut p = three();
9461 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
9462 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9463 assert!(p.undo(), "back to the first placement");
9464 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
9465
9466 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9467 assert_eq!(
9468 transform,
9469 vec![transform_at(1)],
9470 "what nothing plays is not written"
9471 );
9472 assert_eq!(
9473 lanes[0].1[0].transform,
9474 Some(0),
9475 "and the survivor renumbers"
9476 );
9477 assert_eq!(lanes[0].1[1].transform, None);
9478
9479 // One placement on three clips is one entry: settings that are equal
9480 // share.
9481 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
9482 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
9483 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9484 assert_eq!(transform.len(), 1, "equal placements share their entry");
9485 assert_eq!(lanes[1].1[2].transform, Some(0));
9486 reloads(&p, "a transform that outlived an undo");
9487
9488 // A grade and a placement on one clip are two independent tables.
9489 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
9490 let (_, lanes, _, color, transform) = p.without_orphan_sources();
9491 assert_eq!((color.len(), transform.len()), (1, 1));
9492 assert_eq!(
9493 (lanes[0].1[0].color, lanes[0].1[0].transform),
9494 (Some(0), Some(0))
9495 );
9496 }
9497
9498 /// Not a claim about correctness but about cost: a clip is copied on every
9499 /// paste, every undo snapshot and every lane clone, so its size is worth
9500 /// knowing. The eq index fit the padding a `Copy` clip already had; the
9501 /// colour one did not, and the struct grew a word. The transform index is
9502 /// a third `Option<u16>`, and it fits the padding the fit policy and the
9503 /// transition byte already left behind, so the struct did not grow again.
9504 /// The packed visualizer look is a `u64` -- the strand colour has bytes
9505 /// above the clip's own four -- and nothing left in the struct is wide
9506 /// enough to hold it, so it grew a word again.
9507 #[test]
9508 fn a_clip_is_still_a_small_copy() {
9509 assert_eq!(
9510 std::mem::size_of::<Clip>(),
9511 64,
9512 "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index, 64 once the look was a u64"
9513 );
9514 }
9515
9516 #[test]
9517 fn from_parts_has_no_history_and_checks_the_invariants() {
9518 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
9519 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
9520 let mut p = Project::from_parts(
9521 sources.clone(),
9522 lanes.clone(),
9523 eq.clone(),
9524 color.clone(),
9525 Vec::new(),
9526 )
9527 .expect("valid parts");
9528 assert_eq!(p.clips(), three().clips());
9529 assert!(!p.undo(), "a loaded project has nothing to undo");
9530 assert!(p.split(4), "...and is editable from there");
9531 assert!(p.undo());
9532
9533 // A lane may be empty, and so may every lane -- an emptied timeline is a
9534 // project. No lane at all is not one: there would be nothing to place on.
9535 assert!(
9536 Project::from_parts(
9537 sources.clone(),
9538 two(video.clone(), Vec::new()),
9539 Vec::new(),
9540 Vec::new(),
9541 Vec::new(),
9542 )
9543 .is_ok()
9544 );
9545 assert!(
9546 Project::from_parts(
9547 sources.clone(),
9548 two(Vec::new(), Vec::new()),
9549 Vec::new(),
9550 Vec::new(),
9551 Vec::new(),
9552 )
9553 .is_ok()
9554 );
9555 assert!(
9556 Project::from_parts(
9557 sources.clone(),
9558 Vec::new(),
9559 Vec::new(),
9560 Vec::new(),
9561 Vec::new()
9562 )
9563 .is_err()
9564 );
9565 let bad: [Vec<Clip>; 5] = [
9566 vec![clip(0, 0, 3, 1)], // source that is not there
9567 vec![clip(0, 3, 3, 0)], // empty clip
9568 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
9569 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
9570 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
9571 ];
9572 for clips in bad {
9573 assert!(
9574 Project::from_parts(
9575 sources.clone(),
9576 two(clips.clone(), Vec::new()),
9577 Vec::new(),
9578 Vec::new(),
9579 Vec::new(),
9580 )
9581 .is_err(),
9582 "{clips:?}"
9583 );
9584 assert!(
9585 Project::from_parts(
9586 sources.clone(),
9587 two(video.clone(), clips.clone()),
9588 Vec::new(),
9589 Vec::new(),
9590 Vec::new(),
9591 )
9592 .is_err()
9593 );
9594 // ...and on a third lane, which is checked by the same walk.
9595 assert!(
9596 Project::from_parts(
9597 sources.clone(),
9598 vec![
9599 (LaneKind::Video, video.clone()),
9600 (LaneKind::Audio, audio.clone()),
9601 (LaneKind::Video, clips),
9602 ],
9603 Vec::new(),
9604 Vec::new(),
9605 Vec::new(),
9606 )
9607 .is_err()
9608 );
9609 }
9610 // An equalizer index no table entry answers, and a table entry the file
9611 // format could not have written, are refused at this door too.
9612 let eqd = |i: u16| {
9613 vec![Clip {
9614 fade_in: 0,
9615 fade_out: 0,
9616 transition_out: 0,
9617 visualizer: 0,
9618 viz_paint: 0,
9619 eq: Some(i),
9620 ..video[0]
9621 }]
9622 };
9623 assert!(
9624 Project::from_parts(
9625 sources.clone(),
9626 two(eqd(0), Vec::new()),
9627 Vec::new(),
9628 Vec::new(),
9629 Vec::new(),
9630 )
9631 .is_err()
9632 );
9633 let mut nan = band_at(1);
9634 nan.bands[0].freq_hz = f32::NAN;
9635 assert!(
9636 Project::from_parts(
9637 sources.clone(),
9638 two(eqd(0), Vec::new()),
9639 vec![nan],
9640 Vec::new(),
9641 Vec::new(),
9642 )
9643 .is_err()
9644 );
9645 let loaded = Project::from_parts(
9646 sources.clone(),
9647 two(eqd(0), Vec::new()),
9648 vec![band_at(1)],
9649 Vec::new(),
9650 Vec::new(),
9651 )
9652 .expect("an eq the table holds");
9653 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
9654
9655 // The same two refusals for a colour, at the same door.
9656 let graded = |i: u16| {
9657 vec![Clip {
9658 fade_in: 0,
9659 fade_out: 0,
9660 transition_out: 0,
9661 visualizer: 0,
9662 viz_paint: 0,
9663 color: Some(i),
9664 fit: FitPolicy::default(),
9665 speed: Speed::NORMAL,
9666 ..video[0]
9667 }]
9668 };
9669 assert!(
9670 Project::from_parts(
9671 sources.clone(),
9672 two(graded(0), Vec::new()),
9673 Vec::new(),
9674 Vec::new(),
9675 Vec::new(),
9676 )
9677 .is_err(),
9678 "a colour index no entry answers"
9679 );
9680 assert!(
9681 Project::from_parts(
9682 sources.clone(),
9683 two(graded(0), Vec::new()),
9684 Vec::new(),
9685 vec![ColorParams {
9686 tint: f32::NAN,
9687 ..grade_at(1)
9688 }],
9689 Vec::new(),
9690 )
9691 .is_err(),
9692 "a value the file format could not have written"
9693 );
9694 let loaded = Project::from_parts(
9695 sources.clone(),
9696 two(graded(0), Vec::new()),
9697 Vec::new(),
9698 vec![grade_at(1)],
9699 Vec::new(),
9700 )
9701 .expect("a colour the table holds");
9702 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
9703
9704 // Group ids survive a load, and the next split gets a fresh one.
9705 let mut p =
9706 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
9707 assert!(p.split(4));
9708 assert!(p.clips().iter().all(|c| c.link.is_some()));
9709 }
9710
9711 /// The grouping rules, at the untrusted door and after every edit that can
9712 /// touch a link. A link id is at most one placement per lane -- a clip or a
9713 /// caption, whichever carries it -- and no sequence of edits may produce
9714 /// otherwise, because what an edit produces is what a save writes and a load
9715 /// reads.
9716 ///
9717 /// Amended for the offset-preserving group: the members keep their own
9718 /// spans, so two placements of one id covering different frames is *legal*
9719 /// -- it is what a hand-built group is -- and the only refusal left is the
9720 /// doubled id inside one lane.
9721 #[test]
9722 fn a_link_id_is_never_two_clips_of_one_lane() {
9723 let sources = vec![Source::new(FILE, 0)];
9724 let linked = |start, in_frame, out_frame, link| Clip {
9725 fade_in: 0,
9726 fade_out: 0,
9727 transition_out: 0,
9728 visualizer: 0,
9729 viz_paint: 0,
9730 start,
9731 in_frame,
9732 out_frame,
9733 source: 0,
9734 link: Some(link),
9735 eq: None,
9736 color: None,
9737 transform: None,
9738 fit: FitPolicy::default(),
9739 speed: Speed::NORMAL,
9740 };
9741
9742 // The door: a doubled id inside one lane, refused by name.
9743 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
9744 Project::from_parts(
9745 sources.clone(),
9746 two(video, audio),
9747 Vec::new(),
9748 Vec::new(),
9749 Vec::new(),
9750 )
9751 .expect_err("refused")
9752 .to_string()
9753 };
9754 assert!(
9755 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
9756 .contains("link 7 names two clips in the V1 lane"),
9757 "a duplicate id inside one lane is refused by name"
9758 );
9759 // ...and the same doubling on a subtitle lane, in its own words: a
9760 // caption is the other placement an id may name.
9761 let caption = |start: u32, frames: u32, link| SubClip {
9762 start,
9763 frames,
9764 track: 0,
9765 in_us: 0,
9766 out_us: i64::from(frames) * 1_000_000,
9767 link: Some(link),
9768 };
9769 let subs = LaneData {
9770 clips: Vec::new(),
9771 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
9772 ..LaneData::new(LaneKind::Subtitle, Vec::new())
9773 };
9774 assert_eq!(
9775 links_are_consistent(&[subs]).unwrap_err().to_string(),
9776 "link 7 names two captions in the S1 lane"
9777 );
9778 // A pair covering *different* frames is legal now: the members of a
9779 // hand-built group keep their own spans, and what binds them is the id.
9780 let apart = Project::from_parts(
9781 sources.clone(),
9782 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
9783 Vec::new(),
9784 Vec::new(),
9785 Vec::new(),
9786 );
9787 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
9788 // A one-sided link is *not* an error: it is what a lift leaves behind.
9789 let mut p = Project::single(FILE, 9);
9790 assert!(p.lift(Lane::A1, 0));
9791 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
9792 assert!(
9793 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
9794 "a lifted lane's project has to load again"
9795 );
9796
9797 // The edits: nothing below may break either rule.
9798 let consistent = |p: &Project, what: &str| {
9799 assert!(
9800 links_are_consistent(&p.lanes).is_ok(),
9801 "{what}: {:?}",
9802 p.lanes
9803 );
9804 };
9805 let mut p = three();
9806 let copied = p.clips()[0];
9807 assert!(
9808 copied.link.is_some(),
9809 "the clipboard clip carries its group"
9810 );
9811 assert!(p.lift(Lane::V1, 0));
9812 assert!(p.place(Lane::V1, 0, copied));
9813 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
9814 assert_eq!(
9815 p.clips().iter().filter(|c| c.link == copied.link).count(),
9816 0,
9817 "a placement belongs to no group, so it cannot duplicate one"
9818 );
9819 consistent(&p, "lift + place twice");
9820 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
9821 consistent(&p, "place through a grouped clip");
9822 assert!(p.paste(6, copied), "a rippling paste through another");
9823 consistent(&p, "paste");
9824 assert!(p.split(2));
9825 consistent(&p, "split");
9826 assert!(p.ripple_delete(1, 3));
9827 consistent(&p, "ripple_delete");
9828 assert!(p.undo());
9829 consistent(&p, "undo");
9830 }
9831
9832 /// What an edit produces is what a save writes, so *every* state the public
9833 /// API can reach has to load again. The two the verifier panel found where
9834 /// it did not: a split and a regroup handed one group id to two clips that
9835 /// were not the same span, because the lanes had been edited apart.
9836 #[test]
9837 fn every_reachable_state_reloads() {
9838 let mut p = Project::single(FILE, 150);
9839 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
9840 assert!(p.split(10), "the lanes are cut apart at 10");
9841 reloads(&p, "place on one lane, then split");
9842
9843 let mut p = Project::single(FILE, 150);
9844 assert!(p.split(30));
9845 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
9846 assert!(p.regroup(30), "only the audio lane can rejoin");
9847 assert!(p.split(60));
9848 reloads(&p, "lift, regroup one lane, split");
9849
9850 // Two audio streams of one file, both placed: two source entries with
9851 // one path between them, which is the state a stream picked out of the
9852 // library reaches -- and the state a save has to write and read back.
9853 let mut p = Project::single(FILE, 150);
9854 let second = p.import(FILE, 1);
9855 assert_eq!(second, 1, "the same file on another stream is a new source");
9856 assert!(p.append_clip(second, 150));
9857 assert!(p.split(200));
9858 reloads(
9859 &p,
9860 "a second audio stream of the same file, placed and split",
9861 );
9862 let (sources, ..) = p.without_orphan_sources();
9863 assert_eq!(
9864 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
9865 [0, 1],
9866 "both entries survive the orphan prune: both are played"
9867 );
9868 }
9869
9870 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
9871 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
9872 /// is the stamp playback puts on a decoded source frame -- and the *last*
9873 /// source frame the pump is still holding at a timeline frame has to be
9874 /// exactly the one the export encoded there, at every rate. Anything else is
9875 /// A/V drift that grows with the clip, and no test of either side alone
9876 /// would see it.
9877 ///
9878 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
9879 /// is a better answer than the floor/floor this had: floor/floor put the
9880 /// preview a whole held frame off the export at slow rates.)
9881 #[test]
9882 fn speed_maps_both_ways() {
9883 for permille in (250..=4000).step_by(1) {
9884 let speed = Speed::from_permille(permille);
9885 assert_eq!(speed.permille(), permille, "no clamping in range");
9886 for d in 0..200u32 {
9887 let want = speed.source_at(d);
9888 // What the pump shows at `d` is the last frame whose stamp has
9889 // come due -- and it is `want`, the frame the export encodes
9890 // there. Slowed, that is the frame it is still holding; sped up,
9891 // it is the newest of the several that arrived.
9892 let held = (0..=want + 8)
9893 .filter(|&s| speed.timeline_at(s) <= d)
9894 .next_back();
9895 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
9896 }
9897 for n in 1..300u32 {
9898 // A footprint is never zero: a clip occupying no timeline frame
9899 // is a placement the lane invariants cannot hold.
9900 let frames = speed.frames(n);
9901 assert!(frames >= 1, "{speed} of {n} frames");
9902 // ...and its last timeline frame never reads past the clip.
9903 assert!(
9904 speed.source_at(frames - 1) < n,
9905 "{speed}: the last timeline frame of {n} reads past the clip"
9906 );
9907 // The trim inverse never overshoots the room it was given, and
9908 // answers for every room a footprint can be.
9909 let fit = speed.fit(frames).expect("a clip fits its own footprint");
9910 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
9911 // A room narrower than one source frame's own footprint holds
9912 // nothing, and says so rather than rounding something into it.
9913 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
9914 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
9915 }
9916 }
9917 // Real time is the identity map, byte for byte.
9918 for d in 0..1000 {
9919 assert_eq!(Speed::NORMAL.source_at(d), d);
9920 assert_eq!(Speed::NORMAL.timeline_at(d), d);
9921 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
9922 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
9923 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
9924 }
9925 // The one door: no zero, no reverse, nothing past the ends.
9926 assert_eq!(Speed::from_permille(0), Speed::MIN);
9927 assert_eq!(Speed::from_permille(249), Speed::MIN);
9928 assert_eq!(Speed::from_permille(4001), Speed::MAX);
9929 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
9930 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
9931 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
9932 }
9933
9934 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
9935 /// export encodes at a timeline frame is the one playback is holding there,
9936 /// a file is as long in timeline frames as the seconds it lasts, and the two
9937 /// compose so a speeded clip at another rate is exactly both.
9938 #[test]
9939 fn rate_composes_with_speed() {
9940 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
9941 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
9942 // the identity map or a single-rate project would move.
9943 for (source_fps, timeline_fps) in [
9944 (24000. / 1001., 30.),
9945 (30., 24000. / 1001.),
9946 (60., 30.),
9947 (25., 30.),
9948 (30., 30.),
9949 ] {
9950 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
9951 for n in 0..2000u32 {
9952 let source = rate.source_at(n);
9953 // The stamp is the *first* timeline-rate frame that shows it, so
9954 // the picture on screen at `n` is the picture encoded at `n`.
9955 let held = (0..=source + 4)
9956 .filter(|&s| rate.timeline_at(s) <= n)
9957 .next_back();
9958 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
9959 }
9960 // A file of `count` frames is `timeline_at(count)` frames long here,
9961 // and its last one still reads a frame the file has.
9962 for count in 1..500u32 {
9963 let frames = rate.timeline_at(count);
9964 assert!(frames >= 1, "a file is never zero frames long");
9965 assert!(
9966 rate.source_at(frames - 1) < count,
9967 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
9968 );
9969 }
9970 // No drift: the mapping is one exact division of the *rate itself*,
9971 // not an accumulation and not a rounded rate, so an hour in is as
9972 // true as the first second. (Held to the real ratio of the two rates
9973 // the caller asked for -- `as_f64` would be true of a wrong rate.)
9974 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
9975 let want = f64::from(n) * source_fps / timeline_fps;
9976 assert!(
9977 (f64::from(rate.source_at(n)) - want).abs() < 1.,
9978 "{source_fps} on {timeline_fps}: frame {n} drifted"
9979 );
9980 }
9981 }
9982 // The timeline's own rate is the identity, whichever way it is written.
9983 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
9984 assert!(
9985 Rate::from_fps(30.0004, 30.)
9986 .expect("30.0004 over 30")
9987 .is_real_time(),
9988 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
9989 );
9990 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
9991 // one thing `matches_timeline` refuses a file for now that the rate gate
9992 // is gone.
9993 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
9994 assert!(Rate::from_fps(30., f64::NAN).is_err());
9995 for n in 0..1000 {
9996 assert_eq!(Rate::REAL_TIME.source_at(n), n);
9997 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
9998 }
9999 // ...and the composition, in the order the decoder's door applies it:
10000 // the speed picks the clip's (timeline-rate) frame, the rate picks the
10001 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
10002 // timeline frames per frame shown, each of them exactly 800/1001 of a
10003 // file frame.
10004 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
10005 let speed = Speed::from_permille(2000);
10006 for d in 0..100u32 {
10007 assert_eq!(
10008 rate.source_at(speed.source_at(d)),
10009 (u64::from(d) * 2 * 800 / 1001) as u32,
10010 "2x of a 23.976 fps file at timeline frame {d}"
10011 );
10012 }
10013 }
10014
10015 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
10016 /// source frames per timeline frame and still starts at its own in-point,
10017 /// and a half-speed one shows every source frame twice.
10018 #[test]
10019 fn a_rate_maps_timeline_frames_onto_source_frames() {
10020 let mut p = Project::single(FILE, 40);
10021 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
10022 .expect("room enough");
10023 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
10024 assert_eq!(
10025 p.map(Lane::V1, 0),
10026 Some((0, 0)),
10027 "and it starts where it did"
10028 );
10029 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
10030 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
10031 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
10032 // The span a decoder is handed: as many source frames as it will read,
10033 // which is the last shown frame's own and not one more -- timeline frame
10034 // 19 shows source frame 38, so 39 frames are read and the 40th is a
10035 // picture nothing would display.
10036 let span = p.span_at(Lane::V1, 0).expect("a span");
10037 assert_eq!((span.len, span.source_len()), (20, 39));
10038 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
10039 // ...and the same clip the other way round.
10040 let mut p = Project::single(FILE, 40);
10041 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
10042 .expect("room enough");
10043 assert_eq!(p.timeline_frames(), 80);
10044 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
10045 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
10046 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
10047 assert_eq!(
10048 p.map(Lane::V1, 79),
10049 Some((0, 39)),
10050 "and the last timeline frame is still inside the source range"
10051 );
10052 }
10053
10054 /// A trim of a speeded clip is still a trim of its *source*, and the edge
10055 /// still stops at the wall: the room a rate leaves is measured in timeline
10056 /// frames and the range it commits in source ones.
10057 #[test]
10058 fn trimming_a_speeded_clip_stays_inside_its_room() {
10059 let mut p = Project::single(FILE, 40);
10060 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
10061 .expect("room enough");
10062 // A second clip butted against the first, so the wall is a real one.
10063 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
10064 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
10065 assert_eq!(room, (1, 20), "out to the neighbour and no further");
10066 assert!(
10067 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
10068 "clamped to the wall, which is where the edge already is"
10069 );
10070 let c = p.clips()[0];
10071 assert_eq!(c.end(), 20, "so nothing moved");
10072 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
10073 // ...and in: half the timeline frames is half the source range.
10074 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
10075 let c = p.clips()[0];
10076 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
10077 assert_eq!(c.end(), 10, "and ten timeline frames of them");
10078 assert!(sorted_disjoint(p.clips()));
10079 }
10080
10081 /// The frames a rate cannot address: at half speed each source frame is on
10082 /// screen twice, and the cut between the two showings is not a cut in the
10083 /// file. Refused, so the two halves always add up to the clip that was cut.
10084 #[test]
10085 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
10086 let mut p = Project::single(FILE, 10);
10087 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
10088 .expect("room enough");
10089 assert_eq!(p.timeline_frames(), 20);
10090 assert!(
10091 !p.split(3),
10092 "an odd frame is between two showings of one frame"
10093 );
10094 assert_eq!(p.clips().len(), 1, "and nothing was cut");
10095 assert!(p.split(4), "an even one is a frame boundary");
10096 let halves = p.clips().to_vec();
10097 assert_eq!(
10098 (halves[0].end(), halves[1].start, halves[1].end()),
10099 (4, 4, 20),
10100 "the halves meet, and still end where the clip did"
10101 );
10102 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
10103 assert!(p.regroup(4), "and the inverse puts it back");
10104 assert_eq!(p.clips().len(), 1);
10105 }
10106
10107 /// The same claim, swept: random op sequences off the public surface, the
10108 /// project reloaded after every one of them. A failure prints its seed, and
10109 /// the seed replays the whole sequence.
10110 #[test]
10111 fn random_edit_sequences_reload() {
10112 // Two thousand, not two hundred: the overlap a hole punched into a slow
10113 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
10114 // sequences, and a 200-seed sweep walked straight past it (it took a
10115 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
10116 // has no business being the narrow one.
10117 for seed in 0..2000u64 {
10118 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
10119 let mut next = move |n: u32| {
10120 // xorshift64*: no dependency, and the seed replays it exactly.
10121 rng ^= rng << 13;
10122 rng ^= rng >> 7;
10123 rng ^= rng << 17;
10124 (rng >> 33) as u32 % n
10125 };
10126 let mut p = Project::single(FILE, 40);
10127 for step in 0..24 {
10128 let frame = next(44);
10129 // A clipboard copy carries the group id of the take it came from
10130 // -- the input that made a placement duplicate an id -- and, one
10131 // time in three, a rate of its own: a *speeded clip placed over
10132 // a speeded clip* is the shape whose remainders have to be run
10133 // through `Speed::fit`, and it is not a shape the lanes hand out
10134 // on their own often enough to be sure of.
10135 let mut copied = *p
10136 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
10137 .get(next(4) as usize)
10138 .unwrap_or(&clip(0, 0, 5, 0));
10139 if next(3) == 0 {
10140 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
10141 }
10142 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
10143 let idx = next(4) as usize;
10144 let _ = match next(16) {
10145 // A clip dragged along its own lane to wherever the pointer
10146 // let it go: the op that moves a placement without changing
10147 // what it plays, so what it may not do is land on top of the
10148 // neighbour it was dragged at.
10149 15 => p.move_clip(lane, idx, lane, frame),
10150 // ...and a second `place`, so a punch lands inside a clip
10151 // far more often than one op in fourteen would put it there.
10152 14 => p.place(lane, frame, copied),
10153 0 => p.split(frame),
10154 1 => p.regroup(frame),
10155 2 => p.lift(lane, idx),
10156 3 => p.place(lane, frame, copied),
10157 4 => p.paste(frame, copied),
10158 5 => p.ripple_delete(frame, next(9)),
10159 6 => p.delete(idx),
10160 7 => p.undo(),
10161 // An equalizer put on and taken off in the mix: what a clip
10162 // carries has to reload with it, and the entries an undo
10163 // orphans must not come back out of the prune.
10164 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
10165 9 => p.set_eq(lane, idx, None),
10166 // ...and a colour grade in the same mix, for the same
10167 // reason: it rides on the clip and its orphans must go.
10168 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
10169 11 => p.set_color(lane, idx, None),
10170 // ...and a rate in with them, which is the one of the three
10171 // that moves *placements*: a clip that grew has to be
10172 // refused rather than overlap, and one that shrank leaves a
10173 // lane that still loads. Both are what `reloads` asks.
10174 12 => p
10175 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
10176 .is_ok(),
10177 _ => p.append_clip(0, 1 + next(9)),
10178 };
10179 reloads(&p, &format!("seed {seed}, step {step}"));
10180 }
10181 }
10182 }
10183
10184 /// The save/load round trip a project must survive: the parts a save writes,
10185 /// handed back to the constructor a load goes through -- every lane of them,
10186 /// and the reloaded timeline has to be the same lanes in the same order.
10187 fn reloads(p: &Project, what: &str) {
10188 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
10189 match Project::from_parts(sources, lanes, eq, color, transform) {
10190 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
10191 Ok(back) => {
10192 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
10193 // Placements, not whole clips: an orphan prune renumbers the
10194 // sources a clip names, which is the point of it.
10195 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
10196 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
10197 };
10198 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
10199 // The prune renumbers the eq table too, so what has to survive
10200 // is the settings themselves, clip by clip.
10201 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
10202 p.lanes()
10203 .into_iter()
10204 .map(|l| {
10205 (0..p.lane(l).len())
10206 .map(|i| p.eq_of(l, i).cloned())
10207 .collect()
10208 })
10209 .collect()
10210 };
10211 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
10212 // The colour table renumbers in the same prune, so the same
10213 // claim: the params a clip names, not the index it names them by.
10214 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
10215 p.lanes()
10216 .into_iter()
10217 .map(|l| {
10218 (0..p.lane(l).len())
10219 .map(|i| p.color_of(l, i).copied())
10220 .collect()
10221 })
10222 .collect()
10223 };
10224 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
10225 // ...and the transform table, by the same claim again.
10226 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
10227 p.lanes()
10228 .into_iter()
10229 .map(|l| {
10230 (0..p.lane(l).len())
10231 .map(|i| p.transform_of(l, i).copied())
10232 .collect()
10233 })
10234 .collect()
10235 };
10236 assert_eq!(
10237 transforms(&back),
10238 transforms(p),
10239 "{what}: the transforms changed"
10240 );
10241 }
10242 }
10243 }
10244
10245 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
10246 /// -- each one sorted and disjoint, and one span per group id -- asserted
10247 /// directly, where the point is the invariant rather than the round trip.
10248 fn invariants_hold(p: &Project, what: &str) {
10249 for lane in p.lanes() {
10250 assert!(
10251 sorted_disjoint(p.lane(lane)),
10252 "{what}: {} is out of order or overlaps itself: {:?}",
10253 lane.label(),
10254 p.lane(lane)
10255 );
10256 }
10257 if let Err(e) = links_are_consistent(&p.lanes) {
10258 panic!("{what}: {e}\n{:?}", p.lanes);
10259 }
10260 }
10261
10262 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
10263 /// edited without any other lane hearing about it. A handle naming a lane
10264 /// that is not there reads as empty and refuses to mutate.
10265 #[test]
10266 fn a_third_lane_is_a_peer() {
10267 let mut p = three();
10268 assert_eq!(p.lane_count(LaneKind::Video), 1);
10269 assert_eq!(p.lane_count(LaneKind::Audio), 1);
10270 let v2 = p.add_lane(LaneKind::Video);
10271 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
10272 assert_eq!(v2.label(), "V2");
10273 assert_eq!(p.lane_count(LaneKind::Video), 2);
10274 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
10275 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
10276
10277 // A handle for a lane that is not there: empty, and no mutation takes.
10278 let v3 = Lane::new(LaneKind::Video, 2);
10279 assert!(p.lane(v3).is_empty());
10280 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
10281 assert!(!p.lift(v3, 0));
10282 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
10283
10284 // Placing on V2 moves nothing else, and the lane can outrun the rest.
10285 let before = shape(&p);
10286 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10287 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
10288 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
10289 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
10290 assert_eq!(
10291 p.timeline_frames(),
10292 16,
10293 "the last lane to end sets the length"
10294 );
10295 assert_eq!(p.map(v2, 5), Some((0, 21)));
10296 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
10297 assert_eq!(
10298 p.span_at(v2, 0),
10299 Some(Span {
10300 start: 0,
10301 len: 4,
10302 from: None,
10303 speed: Speed::NORMAL
10304 })
10305 );
10306 // Every lane still covers the whole timeline, gaps included.
10307 for l in p.lanes() {
10308 let spans = p.spans_from(l, 0);
10309 assert_eq!(
10310 spans.iter().map(|s| s.len).sum::<u32>(),
10311 16,
10312 "{}",
10313 l.label()
10314 );
10315 }
10316 // ...and playback still reads V1 and A1, whatever else is there.
10317 assert_eq!(p.clips(), p.lane(Lane::V1));
10318 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
10319 let segments = p.segments_from(0, FPS);
10320 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
10321 assert_eq!(
10322 segments[3],
10323 (None, 0.0, 7.0 / FPS),
10324 "A1 keeps the clock counting over the picture V2 added"
10325 );
10326 invariants_hold(&p, "place on V2");
10327
10328 // A lift is that lane's business too, and the lane list undoes.
10329 assert!(p.lift(v2, 0));
10330 assert!(p.lane(v2).is_empty());
10331 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
10332 assert!(p.undo());
10333 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
10334 assert!(p.undo());
10335 assert!(p.lane(v2).is_empty(), "the placement came off V2");
10336 assert!(p.undo(), "and one more step takes the lane itself back");
10337 assert_eq!(p.lane_count(LaneKind::Video), 1);
10338 assert_eq!(shape(&p), shape(&three()));
10339 }
10340
10341 /// The add taken back: an empty lane comes off, a lane holding clips never
10342 /// does (and says which clips), the last lane of a kind never does, the
10343 /// lanes below the one that went move up an `ord`, and one undo puts it
10344 /// back where it stood.
10345 #[test]
10346 fn an_empty_lane_comes_off_again() {
10347 let mut p = three();
10348 let v2 = p.add_lane(LaneKind::Video);
10349 let v3 = p.add_lane(LaneKind::Video);
10350 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
10351 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
10352 let history = p.history.len();
10353
10354 // The last lane of its kind stays: `V1`/`A1` are where an import and a
10355 // paste land, and a project missing one would swallow half of a file
10356 // dropped on it.
10357 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
10358 assert_eq!(
10359 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
10360 "there is no V10 to remove"
10361 );
10362
10363 // A lane with clips on it refuses and names them: a track removal never
10364 // deletes a take.
10365 let refusal = why(p.remove_lane(v3));
10366 assert!(refusal.contains("V3 still holds"), "{refusal}");
10367 assert!(refusal.contains(FILE), "{refusal}");
10368 assert!(refusal.contains("at frame 0"), "{refusal}");
10369 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
10370 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
10371
10372 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
10373 // all.
10374 p.remove_lane(v2).expect("V2 is empty");
10375 assert_eq!(p.lane_count(LaneKind::Video), 2);
10376 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
10377 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
10378 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
10379 invariants_hold(&p, "remove V2");
10380
10381 // ...and one stroke puts the empty lane back above it.
10382 assert!(p.undo());
10383 assert_eq!(p.lane_count(LaneKind::Video), 3);
10384 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
10385 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
10386 }
10387
10388 /// A track dragged to another place in the stack: the whole lane travels --
10389 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
10390 /// a video one, a lane that crosses one of its own kind swaps names with it
10391 /// (and swaps the composite with it), one undo puts the order back, and a
10392 /// save carries it.
10393 #[test]
10394 fn a_track_is_dragged_to_another_place_in_the_stack() {
10395 let mut p = three();
10396 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
10397 let before = shape(&p);
10398 let history = p.history.len();
10399
10400 // A1 over V1: the screen is rearranged and nothing else is. Both keep
10401 // their names -- neither crossed a lane of its own kind -- so every
10402 // handle a front-end holds still names the track it named before.
10403 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
10404 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
10405 assert_eq!(
10406 shape(&p),
10407 vec![before[1].clone(), before[0].clone()],
10408 "each lane's clips travelled with it, and none was remapped"
10409 );
10410 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
10411 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
10412 invariants_hold(&p, "A1 over V1");
10413
10414 // Nothing moves for a lane that is not there, a slot that is not, or a
10415 // lane already standing in the one it was pointed at.
10416 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
10417 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
10418 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
10419 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
10420
10421 // ...and one stroke puts the order back.
10422 assert!(p.undo());
10423 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
10424 assert_eq!(shape(&p), before);
10425
10426 // A second video lane over the first: display order *is* the stack, so
10427 // the last video lane covering a frame is the picture that shows.
10428 let v2 = p.add_lane(LaneKind::Video);
10429 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
10430 let over = shape(&p)[2].clone();
10431 assert_eq!(
10432 p.composite_span_at(0).map(|s| s.len),
10433 Some(5),
10434 "V2's five frames are what frame 0 shows"
10435 );
10436
10437 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
10438 // a position among the lanes of its kind. The picture that wins changes
10439 // with it: the take that was covering is the covered one now.
10440 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
10441 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
10442 assert_eq!(
10443 shape(&p),
10444 vec![over.clone(), before[0].clone(), before[1].clone()],
10445 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
10446 );
10447 assert_eq!(
10448 p.composite_span_at(0).map(|s| s.len),
10449 Some(3),
10450 "the lower video lane wins, and it is the old V1 now"
10451 );
10452 invariants_hold(&p, "V2 over V1");
10453
10454 // A save writes that order and a load takes it back.
10455 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10456 assert_eq!(
10457 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10458 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
10459 );
10460 let back =
10461 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
10462 assert_eq!(back.lanes(), p.lanes());
10463 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
10464
10465 assert!(p.undo(), "and the stack goes back to how it stood");
10466 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
10467 }
10468
10469 /// The grouping rule across more than two lanes, under the offset model: a
10470 /// split *keeps* the group on the left halves and hands the right halves of
10471 /// that group one fresh id of their own -- a clip in no group comes out of
10472 /// the cut in none. So a take cut apart is two takes, one per side, and a
10473 /// lane that was never part of it stays out of both.
10474 #[test]
10475 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
10476 let mut p = Project::single(FILE, 9);
10477 let take = p.clips()[0].link.expect("a fresh project is one take");
10478 let v2 = p.add_lane(LaneKind::Video);
10479 assert!(
10480 p.place(v2, 0, clip(0, 0, 9, 0)),
10481 "a placement joins no group"
10482 );
10483 assert!(p.split(4));
10484 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
10485 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
10486 };
10487 let (left, right) = (side(&p, 0), side(&p, 1));
10488 // The lanes in order are V1, A1, V2: the take's two keep its id on the
10489 // left, and the placed clip never had one for the cut to keep.
10490 assert_eq!(
10491 left,
10492 vec![Some(take), Some(take), None],
10493 "the left halves keep the take"
10494 );
10495 // ...and the right halves of that take are one fresh group.
10496 assert_eq!(right[0], right[1]);
10497 assert_ne!(right[0], Some(take));
10498 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
10499 invariants_hold(&p, "split across three lanes");
10500
10501 // V2 ends early: the left halves still keep what each clip carried --
10502 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
10503 // shared by exactly the take's lanes.
10504 let mut p = Project::single(FILE, 9);
10505 let v2 = p.add_lane(LaneKind::Video);
10506 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
10507 assert!(p.split(3));
10508 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
10509 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
10510 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
10511 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
10512 invariants_hold(&p, "split where one lane ends early");
10513
10514 // The inverse rejoins each lane into the group its left half kept.
10515 assert!(p.regroup(3));
10516 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
10517 assert_eq!(
10518 p.lane(Lane::V1)[0].link,
10519 Some(take),
10520 "the take's id is back, not a fresh one"
10521 );
10522 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
10523 invariants_hold(&p, "regroup across three lanes");
10524 }
10525
10526 /// A group is one placement per lane, on however many lanes carry the id --
10527 /// not a video/audio pair and not a pairing by `ord` -- and the members may
10528 /// cover whatever frames they cover: the offset between them is what a
10529 /// hand-built group keeps. Lanes built by hand, because the rule is checked
10530 /// at the untrusted door and no edit can produce the one thing it refuses.
10531 #[test]
10532 fn a_group_may_span_any_lane() {
10533 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
10534 let one = |start: u32, end: u32, link| Clip {
10535 fade_in: 0,
10536 fade_out: 0,
10537 transition_out: 0,
10538 visualizer: 0,
10539 viz_paint: 0,
10540 start,
10541 in_frame: start,
10542 out_frame: end,
10543 source: 0,
10544 link: Some(link),
10545 eq: None,
10546 color: None,
10547 transform: None,
10548 fit: FitPolicy::default(),
10549 speed: Speed::NORMAL,
10550 };
10551 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
10552 let kinds = [
10553 LaneKind::Video,
10554 LaneKind::Audio,
10555 LaneKind::Video,
10556 LaneKind::Audio,
10557 ];
10558 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
10559 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
10560 };
10561 let take = || vec![one(0, 4, 7)];
10562 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
10563 // The same take on V1 + A2 only, the lanes between it empty: legal, the
10564 // way a lifted half is legal.
10565 let across = build([take(), Vec::new(), Vec::new(), take()]);
10566 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
10567 // ...and so is a group whose members disagree about their spans: the
10568 // offset between them is the hand's business, not the loader's.
10569 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
10570 assert!(
10571 links_are_consistent(&apart).is_ok(),
10572 "[0, 4) on V1 and [2, 6) on A2 are one group"
10573 );
10574 // One id twice in one lane is still that lane's error, by name.
10575 let twice = build([
10576 Vec::new(),
10577 Vec::new(),
10578 vec![one(0, 4, 7), one(4, 8, 7)],
10579 Vec::new(),
10580 ]);
10581 assert_eq!(
10582 links_are_consistent(&twice).unwrap_err().to_string(),
10583 "link 7 names two clips in the V2 lane"
10584 );
10585 }
10586
10587 /// Every lane a save writes comes out, in display order and with its kind --
10588 /// an empty one included, since it is state a front-end shows -- and a
10589 /// two-lane project still writes exactly the parts it always did.
10590 #[test]
10591 fn a_save_writes_every_lane_it_has() {
10592 let mut p = three();
10593 let before = p.without_orphan_sources();
10594 assert_eq!(before.1.len(), 2, "V1 and A1");
10595 let v2 = p.add_lane(LaneKind::Video);
10596 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10597 let a2 = p.add_lane(LaneKind::Audio);
10598 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10599 assert_eq!(
10600 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10601 [
10602 LaneKind::Video,
10603 LaneKind::Audio,
10604 LaneKind::Video,
10605 LaneKind::Audio
10606 ],
10607 "display order, not video-then-audio"
10608 );
10609 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
10610 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
10611 // ...and all four load again as the same four.
10612 let back =
10613 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
10614 assert_eq!(back.lanes(), p.lanes());
10615 assert_eq!(back.lane(a2), p.lane(a2));
10616
10617 // Taking the lanes back leaves exactly what a two-lane save wrote.
10618 for _ in 0..3 {
10619 assert!(p.undo());
10620 }
10621 assert_eq!(
10622 p.without_orphan_sources(),
10623 before,
10624 "byte for byte the same parts a two-lane save always wrote"
10625 );
10626 }
10627
10628 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
10629 /// three lanes and grows more: every lane's own order and the one
10630 /// span-per-id rule after every op, *and* the reload the v4 format restored
10631 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
10632 /// project of any number of lanes.
10633 #[test]
10634 fn random_edit_sequences_keep_many_lanes_consistent() {
10635 for seed in 0..2000u64 {
10636 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
10637 let mut next = move |n: u32| {
10638 rng ^= rng << 13;
10639 rng ^= rng >> 7;
10640 rng ^= rng << 17;
10641 (rng >> 33) as u32 % n
10642 };
10643 let mut p = Project::single(FILE, 40);
10644 let v2 = p.add_lane(LaneKind::Video);
10645 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
10646 let lanes = [Lane::V1, Lane::A1, v2];
10647 for step in 0..24 {
10648 let frame = next(44);
10649 let copied = *p
10650 .lane(lanes[next(3) as usize])
10651 .get(next(4) as usize)
10652 .unwrap_or(&clip(0, 0, 5, 0));
10653 let lane = lanes[next(3) as usize];
10654 let idx = next(4) as usize;
10655 let _ = match next(14) {
10656 // The drag, in the mix: a clip dragged along its own lane
10657 // and onto another one, at a frame the pointer picked --
10658 // which is where the group rule and the sorted+disjoint one
10659 // meet, since every half travels the same distance.
10660 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
10661 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
10662 11 => p.set_eq(lane, idx, None),
10663 // A rate, which on many lanes is the group rule as well:
10664 // every clip carrying the link moves together or none of
10665 // them does, and `invariants_hold` is what says so.
10666 12 => p
10667 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
10668 .is_ok(),
10669 0 => p.split(frame),
10670 1 => p.regroup(frame),
10671 2 => p.lift(lane, idx),
10672 3 => p.place(lane, frame, copied),
10673 4 => p.paste(frame, copied),
10674 5 => p.ripple_delete(frame, next(9)),
10675 6 => p.delete(idx),
10676 7 => p.undo(),
10677 8 => {
10678 p.add_lane(if next(2) == 0 {
10679 LaneKind::Video
10680 } else {
10681 LaneKind::Audio
10682 });
10683 true
10684 }
10685 _ => p.append_clip(0, 1 + next(9)),
10686 };
10687 invariants_hold(&p, &format!("seed {seed}, step {step}"));
10688 reloads(&p, &format!("seed {seed}, step {step}"));
10689 }
10690 }
10691 }
10692
10693 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
10694 /// there, `V1` shows again on either side of it, and a frame no video lane
10695 /// covers is a gap however many lanes there are.
10696 #[test]
10697 fn the_composite_is_the_topmost_lane_with_a_clip() {
10698 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10699 let lanes = vec![
10700 // V1: the whole 30 frames of source 0.
10701 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10702 // V2: source 1 over the middle third.
10703 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
10704 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10705 ];
10706 let p =
10707 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10708 assert_eq!(
10709 p.composite_spans_from(0),
10710 vec![
10711 Span {
10712 start: 0,
10713 len: 10,
10714 from: Some((0, 0)),
10715 speed: Speed::NORMAL
10716 },
10717 Span {
10718 start: 10,
10719 len: 10,
10720 from: Some((1, 5)),
10721 speed: Speed::NORMAL
10722 },
10723 Span {
10724 start: 20,
10725 len: 10,
10726 from: Some((0, 20)),
10727 speed: Speed::NORMAL
10728 },
10729 ],
10730 "V2 takes over for its own span and hands V1 back"
10731 );
10732 // A mid-span ask resolves the same way, which is what a seek does.
10733 assert_eq!(
10734 p.composite_span_at(15),
10735 Some(Span {
10736 start: 15,
10737 len: 5,
10738 from: Some((1, 10)),
10739 speed: Speed::NORMAL
10740 })
10741 );
10742 assert_eq!(p.composite_span_at(30), None, "past the end");
10743
10744 // A hole in V1 under V2's clip: black between the two, and black after
10745 // both run out (the audio lane is still holding the timeline open).
10746 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10747 let holed = vec![
10748 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
10749 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
10750 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10751 ];
10752 let p =
10753 Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
10754 assert_eq!(
10755 p.composite_spans_from(0),
10756 vec![
10757 Span {
10758 start: 0,
10759 len: 5,
10760 from: Some((0, 0)),
10761 speed: Speed::NORMAL
10762 },
10763 Span {
10764 start: 5,
10765 len: 5,
10766 from: None,
10767 speed: Speed::NORMAL
10768 },
10769 Span {
10770 start: 10,
10771 len: 10,
10772 from: Some((1, 0)),
10773 speed: Speed::NORMAL
10774 },
10775 Span {
10776 start: 20,
10777 len: 10,
10778 from: None,
10779 speed: Speed::NORMAL
10780 },
10781 ]
10782 );
10783
10784 // One video lane: the composite *is* that lane, span for span -- the
10785 // promise every existing two-lane project rests on.
10786 let p = Project::single(FILE, 30);
10787 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
10788 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
10789 }
10790
10791 /// Every audio lane holding something gets a play list, and only those.
10792 #[test]
10793 fn audio_segments_cover_every_lane_that_holds_something() {
10794 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10795 let lanes = vec![
10796 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10797 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10798 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
10799 (LaneKind::Audio, Vec::new()),
10800 ];
10801 let p =
10802 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10803 let lists = p.audio_segments_from(0, FPS);
10804 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
10805 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
10806 // A2 is a gap up to frame 15, then the whole of source 1.
10807 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
10808
10809 // No audio lane holds anything: one all-gap list, so such a timeline
10810 // still plays silence against a master clock.
10811 let p = Project::from_parts(
10812 vec![Source::new(FILE, 0)],
10813 vec![
10814 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10815 (LaneKind::Audio, Vec::new()),
10816 ],
10817 vec![],
10818 vec![],
10819 Vec::new(),
10820 )
10821 .expect("valid parts");
10822 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
10823 }
10824
10825 /// D4: removing a subtitle column used to clear the whole undo history,
10826 /// because a placement names its track by index into the palette and the
10827 /// reindex left every later entry naming the wrong one. The entry holds the
10828 /// palette beside the lanes now, so the reindex undoes with it.
10829 #[test]
10830 fn removing_a_subtitle_column_undoes_with_its_reindex() {
10831 let track = |label: &str| SubtitleTrack {
10832 path: FILE.into(),
10833 track: None,
10834 language: "eng".into(),
10835 name: String::new(),
10836 label: label.into(),
10837 cues: Vec::new(),
10838 bitmap: false,
10839 refused: None,
10840 };
10841 let mut p = Project::single(FILE, 300).with_subtitles(vec![
10842 track("one"),
10843 track("two"),
10844 track("three"),
10845 ]);
10846 assert_eq!(p.subtitles().len(), 3);
10847 let before = p.parts();
10848 let palette = p.subtitles().to_vec();
10849 // Column 0 goes, which renumbers the two behind it.
10850 p.remove_subtitles(0).expect("a column with nothing on it");
10851 assert_eq!(p.subtitles().len(), 2);
10852 assert_eq!(p.subtitles()[0].label, "two");
10853 assert!(p.undo(), "the removal is a step like any other cut");
10854 // The palette itself, and not only what `parts` happens to compare: this
10855 // is the assertion that cannot go vacuous if the restore below it ever
10856 // leaves a field of it behind.
10857 assert_eq!(
10858 p.subtitles(),
10859 palette.as_slice(),
10860 "the palette itself, back"
10861 );
10862 assert_eq!(p.parts(), before, "the palette and the lanes, both back");
10863 assert!(p.redo(), "and forward again");
10864 assert_eq!(p.subtitles().len(), 2, "the column goes again");
10865 assert_eq!(p.subtitles()[0].label, "two");
10866 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
10867 }
10868}