forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB33ee2baTahinli2 months ago960 commits

project.rs10594 lines, 462.3 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119 /// 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(format!("transform {bad} holds a value that is not a finite number").into());
1087 }
1088 if lanes.is_empty() {
1089 return Err("no lanes at all: that is not a project".into());
1090 }
1091 let lanes: Vec<LaneData> = lanes
1092 .into_iter()
1093 .map(|(kind, clips)| LaneData::new(kind, clips))
1094 .collect();
1095 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
1096 let name = lane.label();
1097 // A subtitle lane carries words and never a picture
1098 // ([`LaneKind::Subtitle`]); a file that puts one there names a
1099 // source on a lane that has nothing to play it with, and every
1100 // media path below would then read a clip off a lane it does not
1101 // know about.
1102 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
1103 return Err(format!(
1104 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
1105 data.clips.len()
1106 )
1107 .into());
1108 }
1109 for c in &data.clips {
1110 if c.out_frame <= c.in_frame {
1111 return Err(format!(
1112 "{name} clip at {} plays the empty range [{}, {})",
1113 c.start, c.in_frame, c.out_frame
1114 )
1115 .into());
1116 }
1117 if c.source >= sources.len() {
1118 return Err(format!(
1119 "{name} clip at {} names source {} of {}",
1120 c.start,
1121 c.source,
1122 sources.len()
1123 )
1124 .into());
1125 }
1126 if c.start.checked_add(c.frames()).is_none() {
1127 return Err(format!(
1128 "{name} clip at {} runs past the last frame there is",
1129 c.start
1130 )
1131 .into());
1132 }
1133 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1134 return Err(format!(
1135 "{name} clip at {} names eq {} of {}",
1136 c.start,
1137 c.eq.unwrap_or_default(),
1138 eq.len()
1139 )
1140 .into());
1141 }
1142 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1143 return Err(format!(
1144 "{name} clip at {} names color {} of {}",
1145 c.start,
1146 c.color.unwrap_or_default(),
1147 color.len()
1148 )
1149 .into());
1150 }
1151 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
1152 return Err(format!(
1153 "{name} clip at {} names transform {} of {}",
1154 c.start,
1155 c.transform.unwrap_or_default(),
1156 transform.len()
1157 )
1158 .into());
1159 }
1160 }
1161 if !sorted_disjoint(&data.clips) {
1162 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1163 }
1164 }
1165 links_are_consistent(&lanes)?;
1166 // The counter sits past every id the file names, on either of a lane's
1167 // lists: a v16 caption may carry the highest link there is, and a
1168 // re-issued id would silently group it with the next placement that
1169 // asks for one -- the loader refusing a save the editor just wrote.
1170 let next_link = lanes
1171 .iter()
1172 .flat_map(|l| {
1173 let clips = l.clips.iter().filter_map(|c| c.link);
1174 let subs = l.subs.iter().filter_map(|s| s.link);
1175 clips.chain(subs)
1176 })
1177 .max()
1178 // Saturating so a crafted file cannot make the counter wrap: at the
1179 // ceiling ids stop being fresh, which loses grouping, not memory.
1180 .map_or(0, |m| m.saturating_add(1));
1181 Ok(Self {
1182 sources: sources
1183 .iter()
1184 .map(|s| Source::new(&s.path, s.audio_stream))
1185 .collect(),
1186 lanes,
1187 eq,
1188 color,
1189 transform,
1190 history: Vec::new(),
1191 redo: Vec::new(),
1192 next_link,
1193 subtitles: Vec::new(),
1194 settings: ProjectSettings::placeholder(),
1195 })
1196 }
1197
1198 /// The first video lane -- what an export renders and what a single-lane
1199 /// caller still means by "the clips".
1200 pub fn clips(&self) -> &[Clip] {
1201 self.lane(Lane::V1)
1202 }
1203
1204 /// The clips of `lane`, or nothing at all for a lane that is not there.
1205 pub fn lane(&self, lane: Lane) -> &[Clip] {
1206 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1207 }
1208
1209 /// Every lane's handle, in display order -- what a walk over "all lanes"
1210 /// iterates, and what a front-end lays out top to bottom.
1211 pub fn lanes(&self) -> Vec<Lane> {
1212 handles(&self.lanes)
1213 }
1214
1215 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1216 /// for every `ord` below it, and none at or above it.
1217 pub fn lane_count(&self, kind: LaneKind) -> usize {
1218 self.lanes.iter().filter(|l| l.kind == kind).count()
1219 }
1220
1221 /// Appends an empty lane of `kind` and hands back its handle. One undo
1222 /// step, because the lane list is state a front-end shows: an added lane
1223 /// that could not be taken back would be the one edit with no way out.
1224 /// Nothing plays differently until something is placed on it.
1225 ///
1226 /// An empty lane is a lane like any other -- so is a whole project of them
1227 /// ([`Project::from_parts`]); nothing plays until something is placed.
1228 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1229 self.snapshot();
1230 self.lanes.push(LaneData::new(kind, Vec::new()));
1231 Lane::new(kind, self.lane_count(kind) - 1)
1232 }
1233
1234 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1235 /// one undo step like it, which restores the lane where it stood.
1236 ///
1237 /// Refused, changing nothing, while the lane holds anything: the refusal
1238 /// names the clips (file and first frame), because a track removal that
1239 /// deleted takes with it would be the one edit nobody sees coming. Refused
1240 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1241 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1242 /// kind and *skips* a kind that is not there), so a project without one
1243 /// would swallow half of every file dropped on it, silently.
1244 ///
1245 /// The lanes below it move up one `ord`, so a handle a caller was holding
1246 /// (a selection, an open card) names the lane after it from here on -- the
1247 /// one thing a front-end owes this call.
1248 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1249 let Some(i) = self.index(lane) else {
1250 return Err(format!("there is no {} to remove", lane.label()).into());
1251 };
1252 // A subtitle lane is not in that rule: nothing lands on one by itself
1253 // -- a project starts without any and one is added when a caption is --
1254 // so the last of them comes off like any other empty track.
1255 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1256 return Err(format!(
1257 "{} is the only {} track: every import lands on it",
1258 lane.label(),
1259 match lane.kind {
1260 LaneKind::Video => "video",
1261 LaneKind::Audio => "audio",
1262 // Unreachable while the guard above lets the last subtitle
1263 // lane go, and its own word here so the sentence stays true
1264 // if that rule is ever relaxed.
1265 LaneKind::Subtitle => "subtitle",
1266 }
1267 )
1268 .into());
1269 }
1270 if !self.lanes[i].subs.is_empty() {
1271 // Three names and a count, exactly as the clips below get: the way
1272 // out of the refusal is the drag, so the words say so.
1273 let named: Vec<String> = self.lanes[i]
1274 .subs
1275 .iter()
1276 .take(3)
1277 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1278 .collect();
1279 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1280 0 => String::new(),
1281 n => format!(" and {n} more"),
1282 };
1283 return Err(format!(
1284 "{} still holds {}{rest}: delete those captions (or drag them to \
1285 another track) first",
1286 lane.label(),
1287 named.join(", ")
1288 )
1289 .into());
1290 }
1291 let clips = &self.lanes[i].clips;
1292 if !clips.is_empty() {
1293 // Three names and a count: a lane can hold forty clips and a
1294 // refusal nobody reads to the end says nothing at all.
1295 let named: Vec<String> = clips
1296 .iter()
1297 .take(3)
1298 .map(|c| {
1299 let name = self.sources.get(c.source).map_or_else(
1300 || format!("source {}", c.source),
1301 |s| s.path.display().to_string(),
1302 );
1303 format!("{name} at frame {}", c.start)
1304 })
1305 .collect();
1306 let rest = match clips.len().saturating_sub(named.len()) {
1307 0 => String::new(),
1308 n => format!(" and {n} more"),
1309 };
1310 return Err(format!(
1311 "{} still holds {}{rest}: delete those clips (or drag them to \
1312 another track) first",
1313 lane.label(),
1314 named.join(", ")
1315 )
1316 .into());
1317 }
1318 self.snapshot();
1319 self.lanes.remove(i);
1320 Ok(())
1321 }
1322
1323 /// Moves `lane` to display position `to` -- an index into
1324 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1325 /// the handle it answers to from now on. `None`, changing nothing and
1326 /// snapshotting nothing, for a lane that is not there, a position that is
1327 /// not, and a lane already standing in it.
1328 ///
1329 /// The whole track travels: its clips, its gain, its kind. Nothing is
1330 /// remapped, so no take changes lane and no group is broken -- this is the
1331 /// *order* of the lanes and nothing else, which is why one call is one undo
1332 /// step like an add or a removal.
1333 ///
1334 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1335 /// last video lane covering a frame, so moving one video lane past another
1336 /// changes which picture wins, in the preview and in an export alike. The
1337 /// audio lanes are summed and their sum does not care about order, so an
1338 /// audio track moved among the video ones is a rearrangement of the screen
1339 /// alone.
1340 ///
1341 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1342 /// position among the lanes of that kind), so a lane that crosses one of
1343 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1344 /// `V1`, clips and all -- while one that crosses only lanes of the other
1345 /// kind keeps its name. That is the returned handle: unchanged means every
1346 /// handle a caller holds still names the track it named before.
1347 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1348 let i = self.index(lane)?;
1349 if to >= self.lanes.len() || to == i {
1350 return None;
1351 }
1352 self.snapshot();
1353 let data = self.lanes.remove(i);
1354 self.lanes.insert(to, data);
1355 Some(handles(&self.lanes)[to])
1356 }
1357
1358 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1359 /// not there. The one place a handle becomes a position.
1360 fn index(&self, lane: Lane) -> Option<usize> {
1361 self.lanes
1362 .iter()
1363 .enumerate()
1364 .filter(|(_, l)| l.kind == lane.kind)
1365 .map(|(i, _)| i)
1366 .nth(lane.ord)
1367 }
1368
1369 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1370 let i = self.index(lane)?;
1371 Some(&mut self.lanes[i].clips)
1372 }
1373
1374 /// The files the clips index into, in import order; index 0 is the file the
1375 /// project was opened with.
1376 pub fn sources(&self) -> &[Source] {
1377 &self.sources
1378 }
1379
1380 /// The same list in the `(path, stream)` shape the audio engine indexes
1381 /// into -- [`crate::AudioSession::open_multi_streams`] and
1382 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1383 /// was placed with is the stream that plays *and* the stream that exports.
1384 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1385 self.sources
1386 .iter()
1387 .map(|s| (s.path.clone(), s.audio_stream))
1388 .collect()
1389 }
1390
1391 /// Index for `path` played on `audio_stream`, appending it if it is new.
1392 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1393 /// by two paths imports once and two streams of one file are two sources.
1394 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1395 /// no history: a source entry alone changes nothing playable.
1396 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1397 let source = Source::new(path, audio_stream);
1398 match self.sources.iter().position(|s| *s == source) {
1399 Some(idx) => idx,
1400 None => {
1401 self.sources.push(source);
1402 self.sources.len() - 1
1403 }
1404 }
1405 }
1406
1407 /// Append a whole-file clip of `source` to the end of every *media* lane,
1408 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1409 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1410 /// come in through [`Project::add_subtitles`], which is the palette.
1411 ///
1412 /// One history snapshot, so an import is one undo step, and undoing it
1413 /// leaves the (harmless) source entry behind, because indexes are forever.
1414 /// Refused for an unknown source index.
1415 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1416 if source >= self.sources.len() {
1417 return false;
1418 }
1419 self.snapshot();
1420 let start = self.timeline_frames();
1421 let clip = Clip {
1422 fade_in: 0,
1423 fade_out: 0,
1424 transition_out: 0,
1425 visualizer: 0,
1426 viz_paint: 0,
1427 start,
1428 in_frame: 0,
1429 out_frame: frame_count.max(1),
1430 source,
1431 link: Some(self.new_link()),
1432 eq: None,
1433 color: None,
1434 transform: None,
1435 fit: FitPolicy::default(),
1436 speed: Speed::NORMAL,
1437 };
1438 for data in self
1439 .lanes
1440 .iter_mut()
1441 .filter(|l| l.kind != LaneKind::Subtitle)
1442 {
1443 data.clips.push(clip);
1444 }
1445 true
1446 }
1447
1448 /// Drops a source entry -- the file a library row *is* -- and renumbers
1449 /// every clip that indexed past it, which is why this is more than a
1450 /// `Vec::remove`.
1451 ///
1452 /// Refused, changing nothing, while any clip still plays from it: the
1453 /// refusal names the lanes and how many clips each holds, so a caller can
1454 /// say what has to be deleted first. The *last* entry goes like any other
1455 /// -- a project may name no file at all, which is an empty library over an
1456 /// empty timeline (nothing can play, since a clip would have refused the
1457 /// removal). What a front-end does with that is its own decision: `edith`'s
1458 /// window goes back to the empty state it launches in, and
1459 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1460 /// refuses to write a project that names nothing, because no such file
1461 /// could be opened again.
1462 ///
1463 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1464 /// source index of its own -- a clipboard, which is the one thing outside
1465 /// this type that does -- has to fix it up or drop it, or a paste plays a
1466 /// different file. [`PlaybackSession::remove_source`] hands back the index
1467 /// that went for exactly that.
1468 ///
1469 /// corner-cut: this retires the undo stack. `history` holds the lanes, the
1470 /// subtitle palette and the project's own settings -- no source list -- so a
1471 /// snapshot older than the removal can name the very source being removed
1472 /// (delete a file's clips, then remove the file) and restoring it would
1473 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1474 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1475 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1476 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1477 /// exists) currently rules out.
1478 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1479 let Some(source) = self.sources.get(idx) else {
1480 return Err(format!("there is no source {idx} to remove").into());
1481 };
1482 let name = source.path.display().to_string();
1483 let used: Vec<String> = handles(&self.lanes)
1484 .into_iter()
1485 .zip(&self.lanes)
1486 .filter_map(
1487 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1488 0 => None,
1489 1 => Some(format!("{} (1 clip)", lane.label())),
1490 n => Some(format!("{} ({n} clips)", lane.label())),
1491 },
1492 )
1493 .collect();
1494 if !used.is_empty() {
1495 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1496 }
1497 self.sources.remove(idx);
1498 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1499 if c.source > idx {
1500 c.source -= 1;
1501 }
1502 }
1503 self.history.clear();
1504 Ok(())
1505 }
1506
1507 /// The sources a clip actually names, with the clips reindexed onto them
1508 /// -- what a save writes. Indexes are forever *inside* a session (see
1509 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1510 /// entry behind; writing that orphan to a project file would let a file
1511 /// nothing plays refuse a future load. New indexes are assigned in order of
1512 /// first use -- lane by lane, in display order -- so the same project always
1513 /// emits the same bytes.
1514 ///
1515 /// Every lane comes out, in display order and with its kind: that is what a
1516 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1517 /// takes back.
1518 ///
1519 /// The equalizer and colour tables are pruned the same way and for the same
1520 /// reason: an undone [`set_eq`](Project::set_eq) or
1521 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1522 /// and this is the one moment they can go -- the indexes that survive it are
1523 /// only the ones a clip names.
1524 ///
1525 /// One exception, and it is the emptied timeline's: a project no clip plays
1526 /// from still keeps its first source, if it has one. A file is what a
1527 /// reopened project scaffolds itself from -- the frame rate is written
1528 /// nowhere else -- so a save that pruned the last of them would write a
1529 /// project that cannot be loaded back at all.
1530 ///
1531 /// What comes out is *not* ordered by anything a reader may assume: first
1532 /// use, lane by lane, means the entry at index 0 can be a still or a song
1533 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1534 /// picks its rate and its audio reference by what a source *is*, never by
1535 /// where it sits.
1536 pub fn without_orphan_sources(&self) -> Parts {
1537 let mut moved = vec![None; self.sources.len()];
1538 let mut sources = Vec::new();
1539 let mut moved_eq = vec![None; self.eq.len()];
1540 let mut eq = Vec::new();
1541 let mut moved_color = vec![None; self.color.len()];
1542 let mut color = Vec::new();
1543 let mut moved_transform = vec![None; self.transform.len()];
1544 let mut transform = Vec::new();
1545 let mut lanes = self.lanes.clone();
1546 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1547 let old = c.source;
1548 c.source = match moved[old] {
1549 Some(new) => new,
1550 None => {
1551 sources.push(self.sources[old].clone());
1552 moved[old] = Some(sources.len() - 1);
1553 sources.len() - 1
1554 }
1555 };
1556 if let Some(old) = c.eq.map(usize::from) {
1557 c.eq = Some(match moved_eq[old] {
1558 Some(new) => new,
1559 None => {
1560 eq.push(self.eq[old].clone());
1561 let new = (eq.len() - 1) as u16;
1562 moved_eq[old] = Some(new);
1563 new
1564 }
1565 });
1566 }
1567 if let Some(old) = c.color.map(usize::from) {
1568 c.color = Some(match moved_color[old] {
1569 Some(new) => new,
1570 None => {
1571 color.push(self.color[old]);
1572 let new = (color.len() - 1) as u16;
1573 moved_color[old] = Some(new);
1574 new
1575 }
1576 });
1577 }
1578 if let Some(old) = c.transform.map(usize::from) {
1579 c.transform = Some(match moved_transform[old] {
1580 Some(new) => new,
1581 None => {
1582 transform.push(self.transform[old]);
1583 let new = (transform.len() - 1) as u16;
1584 moved_transform[old] = Some(new);
1585 new
1586 }
1587 });
1588 }
1589 }
1590 if sources.is_empty() {
1591 sources.extend(self.sources.first().cloned());
1592 }
1593 (
1594 sources,
1595 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1596 // comes out for one is an empty list, and its *place* in the display
1597 // order is what a save writes it for. What is on it travels beside
1598 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1599 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1600 eq,
1601 color,
1602 transform,
1603 )
1604 }
1605
1606 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1607 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1608 /// track moves by it, which is what makes it a different control from a
1609 /// clip's equalizer (one frequency range of one take) and from the master
1610 /// volume (what this machine monitors at, which no file carries).
1611 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1612 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1613 }
1614
1615 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1616 /// One undo step like every other edit -- it is in the lane list, so an
1617 /// undo restores it with the rest. `false`, and no history, for a lane that
1618 /// is not there, for a value that is not finite, and for one already set.
1619 ///
1620 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1621 /// a value nobody reads: words have no loudness, so a slider that appeared
1622 /// to move one would be a control with no effect. (A video lane's gain is
1623 /// meaningless in the same way but is kept settable: it is the pair `A1`
1624 /// carries for a take, and mixing reads it off the audio lane alone.)
1625 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1626 let Some(i) = self.index(lane) else {
1627 return false;
1628 };
1629 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1630 return false;
1631 }
1632 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1633 if self.lanes[i].gain_db == db {
1634 return false;
1635 }
1636 self.snapshot();
1637 self.lanes[i].gain_db = db;
1638 true
1639 }
1640
1641 /// Every lane's volume in dB, in display order -- what a save writes,
1642 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1643 ///
1644 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1645 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1646 /// one): a save zips the two lists, so a lane that is in one and not the
1647 /// other would hand every track below it the volume of the track above.
1648 pub fn lane_gains(&self) -> Vec<f32> {
1649 self.lanes.iter().map(|l| l.gain_db).collect()
1650 }
1651
1652 /// What is placed on every lane, in display order and in step with
1653 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1654 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1655 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1656 ///
1657 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1658 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1659 /// clip's source there is no orphan to prune and no index to move.
1660 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1661 self.lanes.iter().map(|l| l.subs.clone()).collect()
1662 }
1663
1664 /// The placements a *load* puts back, one list per lane in display order --
1665 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1666 /// same reason. Called *after*
1667 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1668 /// names.
1669 ///
1670 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1671 /// like it, by name and in release, because it is the same untrusted file:
1672 /// a placement on a lane that is not a subtitle lane, an empty span or an
1673 /// empty window, a track the palette does not have, a span running past the
1674 /// last frame there is, and a lane that is out of order or overlaps itself
1675 /// ([`place_sub`] refuses every one of those on the live timeline).
1676 ///
1677 /// [`place_sub`]: Project::place_sub
1678 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1679 let names = handles(&self.lanes);
1680 let palette = self.subtitles.len();
1681 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1682 let name = lane.label();
1683 if list.is_empty() {
1684 continue;
1685 }
1686 if data.kind != LaneKind::Subtitle {
1687 return Err(format!(
1688 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1689 subtitle track",
1690 list.len()
1691 )
1692 .into());
1693 }
1694 for s in &list {
1695 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1696 return Err(format!(
1697 "{name} caption at {} is empty: {} frames of [{}, {})",
1698 s.start, s.frames, s.in_us, s.out_us
1699 )
1700 .into());
1701 }
1702 if s.track >= palette {
1703 return Err(format!(
1704 "{name} caption at {} names subtitle track {} of {palette}",
1705 s.start, s.track
1706 )
1707 .into());
1708 }
1709 if s.start.checked_add(s.frames).is_none() {
1710 return Err(format!(
1711 "{name} caption at {} runs past the last frame there is",
1712 s.start
1713 )
1714 .into());
1715 }
1716 }
1717 if !subs_sorted_disjoint(&list) {
1718 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1719 }
1720 data.subs = list;
1721 // The counter also has to clear the ids these captions carry: this
1722 // is the door a load's placements come through, *after*
1723 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1724 // a hand-grouped caption may carry the highest id in the file.
1725 self.next_link = self.next_link.max(
1726 data.subs
1727 .iter()
1728 .filter_map(|s| s.link)
1729 .max()
1730 .map_or(0, |m| m.saturating_add(1)),
1731 );
1732 }
1733 Ok(self)
1734 }
1735
1736 /// The mix settings a *load* puts back: lane volumes in display order (a
1737 /// short list leaves the rest at unity) and the master limiter, both
1738 /// clamped as their setters clamp them.
1739 ///
1740 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1741 /// setters push an undo step, and a project that arrives one undo away from
1742 /// a state it was never in is a project whose first ctrl+z is a surprise.
1743 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1744 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1745 if db.is_finite() {
1746 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1747 }
1748 }
1749 self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db);
1750 self
1751 }
1752
1753 /// The HDR rendition a *load* puts back -- the same door
1754 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1755 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1756 self.settings.tone = preset;
1757 self
1758 }
1759
1760 /// The canvas and rate a *load* or a fresh open names -- the project
1761 /// resolution and the rate every clip is counted in. The same door
1762 /// [`with_mix`](Project::with_mix) is, and no undo step for the same
1763 /// reason: a project that arrives one undo away from a state it was never
1764 /// in is a project whose first ctrl+z is a surprise.
1765 pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self {
1766 self.settings.resolution = (width, height);
1767 self.settings.frame_rate = frame_rate;
1768 self
1769 }
1770
1771 /// The saved switches a *load* puts back: whether the picture is cut on
1772 /// the stand-ins, whether new ones are made on arrival, which encoder an
1773 /// export opens, and the rate the mix was picked to run at. The load half
1774 /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo
1775 /// step for [`with_mix`](Project::with_mix)'s reason.
1776 pub fn with_switches(
1777 mut self,
1778 proxies: bool,
1779 auto_proxies: bool,
1780 encoder_seat: crate::export::EncoderSeat,
1781 sample_rate: Option<u32>,
1782 ) -> Self {
1783 self.settings.proxies = proxies;
1784 self.settings.auto_proxies = auto_proxies;
1785 self.settings.encoder_seat = encoder_seat;
1786 self.settings.sample_rate = sample_rate;
1787 self
1788 }
1789
1790 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1791 /// project setting, not a clip's: one picture, one look
1792 /// ([`crate::tonemap::Preset`]).
1793 pub fn tone(&self) -> crate::tonemap::Preset {
1794 self.settings.tone
1795 }
1796
1797 /// Sets it. `false` for the one already in force, which is what keeps a
1798 /// re-pick of the current rendition from costing a reseek. One undo step
1799 /// like every other project-setting pick.
1800 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1801 if self.settings.tone == preset {
1802 return false;
1803 }
1804 self.snapshot();
1805 self.settings.tone = preset;
1806 true
1807 }
1808
1809 /// The subtitle tracks a *load* puts back, in the order they were saved --
1810 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1811 /// the same reason.
1812 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1813 self.subtitles = tracks;
1814 self
1815 }
1816
1817 /// What this timeline shows over the picture, in the order they were added:
1818 /// what a front-end lists and what a save writes.
1819 pub fn subtitles(&self) -> &[SubtitleTrack] {
1820 &self.subtitles
1821 }
1822
1823 /// Adds a track, unless the very same one -- same file, same track number
1824 /// inside it -- is already on the list. `false` for that repeat: importing
1825 /// the same `.srt` twice is one subtitle track, not two identical ones.
1826 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1827 if self
1828 .subtitles
1829 .iter()
1830 .any(|t| t.path == track.path && t.track == track.track)
1831 {
1832 return false;
1833 }
1834 self.subtitles.push(track.clone());
1835 true
1836 }
1837
1838 /// Takes the track at `idx` off the list -- what a row's own remove goes
1839 /// through, so whatever an import added can be taken back out. Refused by
1840 /// name for a row this project does not have, rather than a silent no-op:
1841 /// a front-end holding a stale index has picked the wrong row and needs to
1842 /// hear it.
1843 ///
1844 /// Every index past `idx` moves down by one, as [`remove_source`](
1845 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1846 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1847 /// it, or it names a different track afterwards. The placements on the
1848 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1849 /// index into this very list, so every one past `idx` is walked down with
1850 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1851 /// for its clips, for its reason.
1852 ///
1853 /// Refused, changing nothing, while anything placed on a subtitle lane
1854 /// plays *this* row: the placement would have to be deleted or retargeted,
1855 /// and either one is an edit nobody asked for. The refusal names the lane
1856 /// and the frame it is at, up to three of them --
1857 /// [`remove_source`](Project::remove_source) refuses the same way for the
1858 /// same silent corruption.
1859 ///
1860 /// One undo step, and the reindex with it: every placement names a track
1861 /// by index into the palette ([`crate::subtitle`]), so a removal that
1862 /// renumbers them can only come back together with the palette it took
1863 /// the row from -- which is what the history entry holds, beside the
1864 /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that
1865 /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`]
1866 /// -- the panel's own door, which reads the subtitles of a file and
1867 /// nothing else.
1868 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1869 if idx >= self.subtitles.len() {
1870 return Err(format!("there is no subtitle track {idx} to remove").into());
1871 }
1872 let placed: Vec<String> = handles(&self.lanes)
1873 .into_iter()
1874 .zip(&self.lanes)
1875 .flat_map(|(lane, data)| {
1876 data.subs
1877 .iter()
1878 .filter(move |s| s.track == idx)
1879 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1880 })
1881 .take(3)
1882 .collect();
1883 if !placed.is_empty() {
1884 return Err(format!(
1885 "{} is on the timeline ({}): delete those clips first",
1886 self.track_name(idx),
1887 placed.join(", ")
1888 )
1889 .into());
1890 }
1891 self.snapshot();
1892 self.subtitles.remove(idx);
1893 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1894 if s.track > idx {
1895 s.track -= 1;
1896 }
1897 }
1898 Ok(())
1899 }
1900
1901 /// What a refusal calls a palette row: the name the panel shows, and the
1902 /// index alone for a row that is not there.
1903 fn track_name(&self, track: usize) -> String {
1904 self.subtitles
1905 .get(track)
1906 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1907 }
1908
1909 /// The subtitle lanes in display order -- what a front-end lays out and
1910 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1911 /// [`audio_lanes`](Project::audio_lanes).
1912 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1913 self.lanes()
1914 .into_iter()
1915 .filter(|l| l.kind == LaneKind::Subtitle)
1916 .collect()
1917 }
1918
1919 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1920 /// for a subtitle track, and empty for every other lane and for one that is
1921 /// not there.
1922 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1923 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1924 }
1925
1926 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1927 /// twin, with one deliberate difference: it **refuses** an overlap instead
1928 /// of overwriting what it lands on.
1929 ///
1930 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1931 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1932 /// carries is a *window of a track* and where the hand let go, and the
1933 /// second of those is the argument. So a caller builds the placement once
1934 /// (from the palette row it dragged) and drops it at as many frames as it
1935 /// likes without rewriting the field each time.
1936 ///
1937 /// A picture placed over a picture hides it and the hidden one is still
1938 /// there to drag back out; two captions in one frame are two lines nobody
1939 /// asked to stack, and the words that lost are gone from the screen with
1940 /// nothing to show for it. So the refusal names the placement in the way,
1941 /// and the caller picks another frame or another lane -- which is what a
1942 /// second subtitle lane is for.
1943 ///
1944 /// One undo step on success, and none on any refusal: an empty window or an
1945 /// empty span, a track the palette does not have
1946 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1947 /// subtitle lane, a span that would run past the last frame there is, and
1948 /// the overlap above.
1949 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1950 if lane.kind != LaneKind::Subtitle {
1951 return Err(format!(
1952 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1953 the others",
1954 lane.label()
1955 )
1956 .into());
1957 }
1958 let Some(i) = self.index(lane) else {
1959 return Err(format!("there is no {} to place on", lane.label()).into());
1960 };
1961 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1962 return Err(format!(
1963 "that placement is empty: {} frames of [{}, {})",
1964 sub.frames, sub.in_us, sub.out_us
1965 )
1966 .into());
1967 }
1968 if sub.track >= self.subtitles.len() {
1969 return Err(format!(
1970 "it names subtitle track {} of {}",
1971 sub.track,
1972 self.subtitles.len()
1973 )
1974 .into());
1975 }
1976 // The placement belongs to no group, for [`place`]'s reason: a caption
1977 // dragged out of the palette arrives alone, and grouping it with what
1978 // is under it is a hand's decision ([`Project::group_all`]).
1979 let sub = SubClip {
1980 start: at,
1981 link: None,
1982 ..sub
1983 };
1984 if at.checked_add(sub.frames).is_none() {
1985 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1986 }
1987 if let Some(other) = self.lanes[i]
1988 .subs
1989 .iter()
1990 .find(|o| o.end() > sub.start && o.start < sub.end())
1991 {
1992 return Err(format!(
1993 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1994 on another subtitle track",
1995 lane.label(),
1996 other.start,
1997 other.start,
1998 other.end()
1999 )
2000 .into());
2001 }
2002 self.snapshot();
2003 let subs = &mut self.lanes[i].subs;
2004 let idx = subs.partition_point(|o| o.start < sub.start);
2005 subs.insert(idx, sub);
2006 debug_assert!(subs_sorted_disjoint(subs));
2007 Ok(())
2008 }
2009
2010 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
2011 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
2012 /// refused an overlap where that one clamps to it, for
2013 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
2014 /// still and no picture under it that a landing would hide, so "as far as
2015 /// it goes" would silently be a frame nobody named.
2016 ///
2017 /// A caption *in* a group drags the group: one delta for every member --
2018 /// its clips and its other captions -- clamped to the room each of them
2019 /// has, exactly as a clip's drag always has. That is the point of putting
2020 /// a caption in a group: the words go where the picture goes.
2021 ///
2022 /// The window travels untouched: a caption dragged later says the same
2023 /// words later, exactly as a clip dragged later plays the same pictures
2024 /// later.
2025 ///
2026 /// One undo step on success; nothing changed and no step on a refusal --
2027 /// an index that is not there, a lane that is not a subtitle lane or is not
2028 /// there, and (for a caption in no group) an overlap. A drop that changes
2029 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
2030 /// up and put it back has done nothing wrong, and a front-end showing every
2031 /// `Err` would say so.
2032 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
2033 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
2034 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
2035 };
2036 if to.kind != LaneKind::Subtitle {
2037 return Err(format!(
2038 "{} is not a subtitle track: a caption cannot play on it",
2039 to.label()
2040 )
2041 .into());
2042 }
2043 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
2044 return Err(format!("there is no {} to move onto", to.label()).into());
2045 };
2046 if (here, start) == (dest, sub.start) {
2047 // A pick-up-put-back: the drag ended where it began, which is not a
2048 // mistake to name -- `Ok`, and no undo step, because nothing
2049 // changed. A refusal here would toast a hand that did nothing.
2050 return Ok(());
2051 }
2052 if start.checked_add(sub.frames).is_none() {
2053 return Err(
2054 format!("a placement at frame {start} runs past the last frame there is").into(),
2055 );
2056 }
2057 // A grouped caption carries its group, clamped to the room the whole
2058 // group has rather than refused ([`Project::move_room]) -- one drag, one
2059 // delta, one undo step.
2060 let members = self.group_of(from, idx).expect("the subtitle was found");
2061 if !members.alone() {
2062 if members
2063 .subs
2064 .iter()
2065 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
2066 {
2067 return Err(format!(
2068 "a group is one caption per track: {} already carries this group",
2069 to.label()
2070 )
2071 .into());
2072 }
2073 let want = i64::from(start) - i64::from(sub.start);
2074 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
2075 return Err(format!(
2076 "another placement already covers those frames on {}",
2077 to.label()
2078 )
2079 .into());
2080 };
2081 let delta = want.clamp(lo, hi);
2082 self.snapshot();
2083 for &(l, i) in &members.clips {
2084 let c = &mut self.lanes[l].clips[i];
2085 c.start = (i64::from(c.start) + delta) as u32;
2086 }
2087 for &(l, i) in &members.subs {
2088 let s = &mut self.lanes[l].subs[i];
2089 s.start = (i64::from(s.start) + delta) as u32;
2090 }
2091 let moved = self.lanes[here].subs.remove(idx);
2092 let subs = &mut self.lanes[dest].subs;
2093 let at = subs.partition_point(|o| o.start < moved.start);
2094 subs.insert(at, moved);
2095 debug_assert!(subs_sorted_disjoint(subs));
2096 debug_assert!(members
2097 .clips
2098 .iter()
2099 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
2100 return Ok(());
2101 }
2102 let moved = SubClip { start, ..sub };
2103 if let Some(other) = self.lanes[dest]
2104 .subs
2105 .iter()
2106 .enumerate()
2107 .find(|&(j, o)| {
2108 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
2109 })
2110 .map(|(_, o)| *o)
2111 {
2112 return Err(format!(
2113 "the {} subtitle at frame {} already covers [{}, {})",
2114 to.label(),
2115 other.start,
2116 other.start,
2117 other.end()
2118 )
2119 .into());
2120 }
2121 self.snapshot();
2122 self.lanes[here].subs.remove(idx);
2123 let subs = &mut self.lanes[dest].subs;
2124 let at = subs.partition_point(|o| o.start < moved.start);
2125 subs.insert(at, moved);
2126 debug_assert!(subs_sorted_disjoint(subs));
2127 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
2128 Ok(())
2129 }
2130
2131 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
2132 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
2133 /// pulling an edge past what is legal means "as far as it goes".
2134 ///
2135 /// The window follows the edge, in the seconds the frames are worth at
2136 /// `fps`: a head pulled in starts the caption later *in its track* (the
2137 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
2138 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
2139 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
2140 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
2141 /// needed here and nowhere else in this file, because a trim is the only
2142 /// edit that changes a *duration*.
2143 ///
2144 /// The walls: one frame always survives, an edge never crosses the
2145 /// neighbouring subtitle on its own lane, a head never walks back past the
2146 /// track's own start (`in_us` of 0), and a tail never runs past the last
2147 /// cue the track has -- which is the source length a media trim needs a
2148 /// caller's table for, and which this one can simply read.
2149 ///
2150 /// `Err`, with nothing changed and no undo step, for an index that is not
2151 /// there and an unusable `fps`. An edge that ends up where it already was
2152 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2153 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2154 /// reason: a drag that stops at a wall is not a mistake to report.
2155 pub fn trim_sub(
2156 &mut self,
2157 lane: Lane,
2158 idx: usize,
2159 edge: Edge,
2160 to: u32,
2161 fps: f64,
2162 ) -> crate::Result<()> {
2163 if !(fps.is_finite() && fps > 0.0) {
2164 return Err(format!("{fps} is not a frame rate to trim against").into());
2165 }
2166 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2167 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2168 };
2169 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2170 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2171 };
2172 let to = to.clamp(lo, hi);
2173 let at = match edge {
2174 Edge::Start => sub.start,
2175 Edge::End => sub.end(),
2176 };
2177 if to == at {
2178 // The edge is where it was asked to go -- either the hand did not
2179 // move it, or the clamp above stopped it at a wall it was already
2180 // standing against. Both are a drag that changed nothing: `Ok`, no
2181 // undo step, and no toast for a box that simply stopped moving.
2182 return Ok(());
2183 }
2184 self.snapshot();
2185 let members = self.group_of(lane, idx).expect("the subtitle was found");
2186 let i = self.index(lane).expect("the subtitle was found on it");
2187 let s = &mut self.lanes[i].subs[idx];
2188 match edge {
2189 // The words that stay are the words that were there, so the window
2190 // moves with the head -- a trim, not a slip.
2191 Edge::Start => {
2192 // Clamped to a window that is still a window: the walls above
2193 // are frames and the rounding between the two clocks is not
2194 // exact, and neither is a caller's hand-built placement.
2195 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2196 .clamp(0, s.out_us - 1);
2197 s.frames = s.end() - to;
2198 s.start = to;
2199 }
2200 Edge::End => {
2201 s.out_us =
2202 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2203 s.frames = to - s.start;
2204 }
2205 }
2206 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2207 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2208 // A caption in a group drags its group's edge with it, exactly as a
2209 // clip's trim does: one delta, each member clamped to its own room.
2210 // No source table to grow by, which only tightens how far a member may
2211 // follow -- never whether it may.
2212 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
2213 Ok(())
2214 }
2215
2216 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2217 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2218 /// drawing the box during a drag asks. `None` for an index that is not
2219 /// there.
2220 pub fn trim_sub_room(
2221 &self,
2222 lane: Lane,
2223 idx: usize,
2224 edge: Edge,
2225 fps: f64,
2226 ) -> Option<(u32, u32)> {
2227 let subs = self.sub_lane(lane);
2228 let s = *subs.get(idx)?;
2229 // How many timeline frames a stretch of the track is worth, which is
2230 // what turns its two walls -- its own start, and its last cue -- into
2231 // frames. A rate that is not a rate leaves the window where it is.
2232 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2233 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
2234 false => 0,
2235 };
2236 Some(match edge {
2237 Edge::Start => (
2238 s.start
2239 .saturating_sub(frames_of(s.in_us))
2240 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2241 s.end() - 1,
2242 ),
2243 Edge::End => {
2244 // Out to the end of the track it reads, and never over the
2245 // subtitle behind it. A track the palette no longer has (or one
2246 // with no cues at all) may not grow, exactly as a source with no
2247 // entry in a media trim's table may not.
2248 let track_end = self
2249 .subtitles
2250 .get(s.track)
2251 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2252 .unwrap_or(s.out_us);
2253 (
2254 s.start + 1,
2255 s.start
2256 .saturating_add(frames_of(track_end - s.in_us).max(1))
2257 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2258 )
2259 }
2260 })
2261 }
2262
2263 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2264 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2265 /// `false` for an index that is not there (which a lane that is not a
2266 /// subtitle lane always is).
2267 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2268 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2269 return false;
2270 };
2271 self.snapshot();
2272 self.lanes[i].subs.remove(idx);
2273 true
2274 }
2275
2276 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2277 /// window of its track, clipped to that window and shifted to where the
2278 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2279 /// carried through the picture's spans -- this is its twin for a track that
2280 /// is placed on a lane of its own, and it is what a preview draws and what
2281 /// an export of the lane would write.
2282 ///
2283 /// Cut, not stretched: a cue half inside the window keeps the half that is
2284 /// inside, and a cue wholly outside it is gone -- the same rule the media
2285 /// spans follow. `fps` is the timeline's rate, needed here because a
2286 /// placement's *position* is in frames while its words are in microseconds.
2287 ///
2288 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2289 /// of their cues, no file opened), which is how a front-end asks it.
2290 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2291 if !(fps.is_finite() && fps > 0.0) {
2292 return Vec::new();
2293 }
2294 let mut out = Vec::new();
2295 for s in self.sub_lane(lane) {
2296 let Some(track) = self.subtitles.get(s.track) else {
2297 // A placement whose track was taken off the palette
2298 // ([`Project::remove_subtitles`]) shows nothing rather than
2299 // showing another track's words.
2300 continue;
2301 };
2302 // Where the placement's own first microsecond lands on the
2303 // timeline, and how many microseconds of timeline one microsecond
2304 // of the window is worth: the placement's own proportion, which a
2305 // group's re-rate changes (the frames compress, the window does
2306 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2307 // every cue lands where it always did; at 2x the words cross the
2308 // screen in half the time, cue for cue.
2309 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2310 let onto = |t: i64| {
2311 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2312 };
2313 for cue in &track.cues {
2314 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2315 if b <= a {
2316 continue; // wholly outside the window this placement keeps
2317 }
2318 out.push(SubtitleCue {
2319 start_us: onto(a),
2320 end_us: onto(b),
2321 text: cue.text.clone(),
2322 image: cue.image.clone(),
2323 });
2324 }
2325 }
2326 // The placements come in timeline order, but two lanes' worth (or a
2327 // track whose cues a window reordered) do not.
2328 out.sort_by_key(|cue| cue.start_us);
2329 out
2330 }
2331
2332 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2333 /// lanes is multiplied by on its way into the mix: the same lanes in the
2334 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2335 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2336 /// the bit-exact path.
2337 pub fn audio_gains(&self) -> Vec<f32> {
2338 self.audio_lanes()
2339 .into_iter()
2340 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2341 .collect()
2342 }
2343
2344 /// The master limiter the mix is summed through. A project setting, not a
2345 /// clip's and not a lane's: there is one mix.
2346 pub fn limiter(&self) -> Limiter {
2347 self.settings.limiter
2348 }
2349
2350 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2351 /// for a setting already in force. One undo step like every other
2352 /// project-setting pick.
2353 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2354 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2355 if self.settings.limiter == limiter {
2356 return false;
2357 }
2358 self.snapshot();
2359 self.settings.limiter = limiter;
2360 true
2361 }
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2376 /// plays flat (and for an index that is not there) -- what a feeder and an
2377 /// export ask before they build an [`crate::eq::EqState`].
2378 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2379 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2380 }
2381
2382 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2383 /// take them off. One undo step, like every other edit. `false` -- and no
2384 /// history -- for an index that is not there and for params holding a value
2385 /// that is not finite, which is the one thing the file format could not
2386 /// write and read back.
2387 ///
2388 /// Settings equal to ones already in the table share their entry, so a
2389 /// project that puts the same curve on twenty clips writes it once.
2390 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2391 if idx >= self.lane(lane).len() {
2392 return false;
2393 }
2394 let slot = match params {
2395 None => None,
2396 Some(params) => {
2397 if !finite(&params) {
2398 return false;
2399 }
2400 Some(match self.eq.iter().position(|p| *p == params) {
2401 Some(at) => at as u16,
2402 // corner-cut: the table is append-only within a session (see
2403 // the module docs) and `Clip::eq` is a u16, so the 65535th
2404 // *distinct* setting of one session is refused rather than
2405 // silently aliased. Upgrade path if a UI ever drags a slider
2406 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2407 // snapshot the table into the history and compact it here.
2408 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2409 None => {
2410 self.eq.push(params);
2411 (self.eq.len() - 1) as u16
2412 }
2413 })
2414 }
2415 };
2416 self.snapshot();
2417 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2418 true
2419 }
2420
2421 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2422 /// ungraded (and for an index that is not there) -- what the renderer and
2423 /// the export ask before they call [`crate::color::apply_yuv`].
2424 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2425 self.color
2426 .get(usize::from(self.lane(lane).get(idx)?.color?))
2427 }
2428
2429 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2430 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2431 /// (and no history) for an index that is not there or a value that is not
2432 /// finite, and equal settings share a table entry.
2433 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2434 self.write_color(lane, idx, params, true)
2435 }
2436
2437 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2438 /// one pointer drag, whose first write (a plain `set_color`) already took the
2439 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2440 /// not one per pixel -- and undoing it lands where the hand picked it up.
2441 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2442 self.write_color(lane, idx, params, false)
2443 }
2444
2445 fn write_color(
2446 &mut self,
2447 lane: Lane,
2448 idx: usize,
2449 params: Option<ColorParams>,
2450 snapshot: bool,
2451 ) -> bool {
2452 if idx >= self.lane(lane).len() {
2453 return false;
2454 }
2455 let slot = match params {
2456 None => None,
2457 Some(params) => {
2458 if !color_finite(&params) {
2459 return false;
2460 }
2461 Some(match self.color.iter().position(|p| *p == params) {
2462 Some(at) => at as u16,
2463 // corner-cut: the 65535th *distinct* grade of one session is
2464 // refused rather than silently aliased, exactly as `set_eq`
2465 // refuses the 65535th curve; same upgrade path.
2466 None if self.color.len() >= usize::from(u16::MAX) => return false,
2467 None => {
2468 self.color.push(params);
2469 (self.color.len() - 1) as u16
2470 }
2471 })
2472 }
2473 };
2474 if snapshot {
2475 self.snapshot();
2476 }
2477 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2478 true
2479 }
2480
2481 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2482 /// policy's own placement (and for an index that is not there) -- what the
2483 /// renderer and the export ask before they place its picture.
2484 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2485 self.transform
2486 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2487 }
2488
2489 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2490 /// step, `false` (and no history) for an index that is not there or a
2491 /// value that is not finite, and equal settings share a table entry.
2492 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2493 self.write_transform(lane, idx, params, true)
2494 }
2495
2496 /// [`set_transform`](Self::set_transform) without the undo step, for
2497 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2498 /// one drag on a position/scale/rotate/crop control are one undo, not one
2499 /// per pixel.
2500 pub fn set_transform_live(
2501 &mut self,
2502 lane: Lane,
2503 idx: usize,
2504 params: Option<TransformParams>,
2505 ) -> bool {
2506 self.write_transform(lane, idx, params, false)
2507 }
2508
2509 fn write_transform(
2510 &mut self,
2511 lane: Lane,
2512 idx: usize,
2513 params: Option<TransformParams>,
2514 snapshot: bool,
2515 ) -> bool {
2516 if idx >= self.lane(lane).len() {
2517 return false;
2518 }
2519 let slot = match params {
2520 None => None,
2521 Some(params) => {
2522 if !transform_finite(&params) {
2523 return false;
2524 }
2525 Some(match self.transform.iter().position(|p| *p == params) {
2526 Some(at) => at as u16,
2527 // corner-cut: the 65535th *distinct* transform of one
2528 // session is refused rather than silently aliased,
2529 // exactly as `write_color` refuses the 65535th grade;
2530 // same upgrade path.
2531 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2532 None => {
2533 self.transform.push(params);
2534 (self.transform.len() - 1) as u16
2535 }
2536 })
2537 }
2538 };
2539 if snapshot {
2540 self.snapshot();
2541 }
2542 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2543 true
2544 }
2545
2546 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2547 /// index that is not there, which is what every clip starts at anyway.
2548 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2549 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2550 }
2551
2552 /// Sets it, for the clip **and its whole group**: a link is one span on
2553 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2554 /// from its sound would be a group no save could load. One snapshot, so the
2555 /// group's change is one [`Project::undo`].
2556 ///
2557 /// The source range is untouched -- a speed says how many timeline frames
2558 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2559 /// split still address the file afterwards.
2560 ///
2561 /// Refused, changing nothing and costing no undo step, when the clip would
2562 /// grow into the one after it on its own lane: slowing a clip down makes it
2563 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2564 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2565 /// something a user can go and fix. Also for an index that is not there.
2566 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2567 self.write_speed(lane, idx, speed, true)
2568 }
2569
2570 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2571 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2572 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2573 /// not one per rate it passed through -- exactly as
2574 /// [`set_color_live`](Self::set_color_live) is for a slider.
2575 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2576 self.write_speed(lane, idx, speed, false)
2577 }
2578
2579 fn write_speed(
2580 &mut self,
2581 lane: Lane,
2582 idx: usize,
2583 speed: Speed,
2584 snapshot: bool,
2585 ) -> crate::Result<()> {
2586 let Some(members) = self.group_of(lane, idx) else {
2587 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2588 };
2589 let labels = handles(&self.lanes);
2590 // The clip the hand is holding is the group's clock: everything else
2591 // in the group, caption members included, re-times by the ratio its new
2592 // rate gives its own frames. The clips take the rate itself; a caption
2593 // has none, so it takes the *ratio* -- its span on the timeline
2594 // compresses or stretches about the held clip's head, while the words
2595 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2596 // timeline moves, the track does not).
2597 let Some(held) = self.lane(lane).get(idx).copied() else {
2598 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2599 };
2600 // The same per-member piece `speeded_playhead` builds for this op,
2601 // asked here instead of read there -- a caption's length comes from
2602 // the map's own ends (`end - start`), never `round(len * ratio)`
2603 // separately, which is what let the two answers drift apart by a
2604 // frame.
2605 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2606 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2607 let retimed = |s: SubClip| {
2608 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2609 let start = map.apply(s.start);
2610 let end = map.apply(s.end()).max(start.saturating_add(1));
2611 SubClip { start, frames: end - start, ..s }
2612 };
2613 for &(l, i) in &members.clips {
2614 let clips = &self.lanes[l].clips;
2615 let mut moved = clips[i];
2616 moved.speed = speed;
2617 if let Some(next) = clips.get(i + 1)
2618 && moved.end() > next.start
2619 {
2620 let name = labels[l].label();
2621 return Err(format!(
2622 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2623 move it along, or trim this one first",
2624 moved.end(),
2625 next.start
2626 )
2627 .into());
2628 }
2629 }
2630 // ...and the captions, against their own lanes' captions: a stretch
2631 // that runs one into its neighbour is refused for the clip arm's
2632 // reason -- a lane may not overlap itself -- and by name like it.
2633 let subs: Vec<(usize, usize, SubClip)> = members
2634 .subs
2635 .iter()
2636 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2637 .collect();
2638 for &(l, i, moved) in &subs {
2639 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2640 if j != i && moved.start < other.end() && other.start < moved.end() {
2641 return Err(format!(
2642 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2643 starts at {}: move it along, or trim this one first",
2644 labels[l].label(),
2645 self.lanes[l].subs[i].start,
2646 moved.end(),
2647 other.start
2648 )
2649 .into());
2650 }
2651 }
2652 }
2653 if snapshot {
2654 self.snapshot();
2655 }
2656 for (l, i) in members.clips {
2657 self.lanes[l].clips[i].speed = speed;
2658 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2659 }
2660 for (l, i, moved) in subs {
2661 self.lanes[l].subs[i] = moved;
2662 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2663 }
2664 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2665 Ok(())
2666 }
2667
2668 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2669 /// playhead standing at `at` -- read off the geometry **before** the
2670 /// write, because the old ends are gone after it. The question a card
2671 /// asks as its bar moves: the picture under the cursor has to stay the
2672 /// picture under the cursor, or the scene changes with the rate.
2673 ///
2674 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2675 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2676 /// a clip member keeps its own start and re-fits its length at the new
2677 /// rate -- its **old** rate against the new one, which is what the bar's
2678 /// live samples ask about as much as a first press does; a caption
2679 /// member scales about the held clip's start by the held clip's own
2680 /// proportion; and a playhead outside every member's old extent stays
2681 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2682 /// (or the room a stretch takes) absorbs the difference, not the
2683 /// playhead. `None` for an index that is not there.
2684 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2685 let members = self.group_of(lane, idx)?;
2686 let held = self.lane(lane).get(idx).copied()?;
2687 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2688 for &(l, i) in members.clips.iter().chain(&members.subs) {
2689 let (span, map) = match self
2690 .lanes[l]
2691 .clips
2692 .get(i)
2693 .filter(|_| members.clips.contains(&(l, i)))
2694 {
2695 // The clip's own span, re-fitted at its own old rate: one
2696 // piece of the map, anchored where the clip itself is. The
2697 // new length is the same *source* frames at the new rate --
2698 // len divided by it, never multiplied.
2699 Some(c) => (
2700 (c.start, c.start + c.frames()),
2701 TimelineMap::piece(
2702 (c.start, c.start + c.frames()),
2703 (
2704 c.start,
2705 c.start + (c.len() as f64 / new).round() as u32,
2706 ),
2707 ),
2708 ),
2709 // The caption's span, scaled about the held clip's head by
2710 // the held clip's proportion -- the offset the group keeps.
2711 None => {
2712 let s = self.lanes[l].subs.get(i)?;
2713 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2714 (
2715 (s.start, s.end()),
2716 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2717 )
2718 }
2719 };
2720 // The piece owns only its own old span: outside it the playhead
2721 // is another member's question, or nobody's.
2722 if (span.0..span.1).contains(&at) {
2723 return Some(map.apply(at));
2724 }
2725 }
2726 Some(at)
2727 }
2728
2729 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2730 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2731 /// every clip starts at anyway.
2732 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2733 self.lane(lane)
2734 .get(idx)
2735 .map_or(FitPolicy::default(), |c| c.fit)
2736 }
2737
2738 /// Sets it. One undo step like every other edit, and `false` (with no
2739 /// history) for an index that is not there. Unlike an eq or a grade there is
2740 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2741 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2742 if idx >= self.lane(lane).len() {
2743 return false;
2744 }
2745 self.snapshot();
2746 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2747 true
2748 }
2749
2750 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
2751 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
2752 /// history) for an index that is not there.
2753 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
2754 if idx >= self.lane(lane).len() {
2755 return false;
2756 }
2757 self.snapshot();
2758 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
2759 true
2760 }
2761
2762 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
2763 /// `false` (with no history) for an index that is not there, the way every
2764 /// other setter refuses.
2765 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2766 self.write_viz_paint(lane, idx, paint, true)
2767 }
2768
2769 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
2770 /// samples *inside* one pointer drag across the colour wheel, whose first
2771 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
2772 /// rolls back to. One drag is one undo, not one per sample.
2773 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2774 self.write_viz_paint(lane, idx, paint, false)
2775 }
2776
2777 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
2778 if idx >= self.lane(lane).len() {
2779 return false;
2780 }
2781 if snapshot {
2782 self.snapshot();
2783 }
2784 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
2785 true
2786 }
2787
2788 /// Timeline frames of ramp-up from silence at the start of the clip at
2789 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2790 /// that has none.
2791 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2792 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2793 }
2794
2795 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2796 /// can shrink a clip's audible middle to nothing but never ask for more
2797 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2798 /// and `false` (no history) for an index that is not there.
2799 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2800 if idx >= self.lane(lane).len() {
2801 return false;
2802 }
2803 self.snapshot();
2804 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2805 clip.fade_in = frames.min(clip.frames());
2806 true
2807 }
2808
2809 /// Timeline frames of ramp-down to silence at the end of the clip at
2810 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2811 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2812 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2813 }
2814
2815 /// Sets it. Same promises as [`Project::set_fade_in`].
2816 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2817 if idx >= self.lane(lane).len() {
2818 return false;
2819 }
2820 self.snapshot();
2821 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2822 clip.fade_out = frames.min(clip.frames());
2823 true
2824 }
2825
2826 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2827 /// into its successor, at its own end. `0` for an index that is not
2828 /// there, same as a clip that has none.
2829 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2830 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2831 }
2832
2833 /// Sets it, clamped to the clip's own length and to how many frames its
2834 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2835 /// visible middle to nothing but never ask for more than the two clips
2836 /// between them have. `false` -- no history -- unless `lane` is video,
2837 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2838 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2839 /// them. One undo step like [`Project::set_fade_out`].
2840 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2841 if lane.kind != LaneKind::Video {
2842 return false;
2843 }
2844 let clips = self.lane(lane);
2845 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2846 return false;
2847 };
2848 if a.end() != b.start {
2849 return false;
2850 }
2851 let cap = a.frames().min(b.frames());
2852 self.snapshot();
2853 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2854 true
2855 }
2856
2857 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2858 /// after it, over `frames` timeline frames: sets `idx`'s
2859 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2860 /// each clamped to its own clip's length. `false` -- no history -- unless
2861 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2862 /// adjacent: the second's [`Clip::start`] is exactly the first's
2863 /// [`Clip::end`], no gap between them.
2864 ///
2865 /// This is the whole mechanism, not a stand-in for one: a *real*
2866 /// cross-fade -- both takes heard at once, blending -- is what two clips
2867 /// **overlapping** on separate lanes already get for free from the
2868 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2869 /// This call only shapes the edges of two clips already sitting
2870 /// end-to-end on *one* lane, so the join between them fades like one did.
2871 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2872 if lane.kind != LaneKind::Audio {
2873 return false;
2874 }
2875 let clips = self.lane(lane);
2876 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2877 return false;
2878 };
2879 if a.end() != b.start {
2880 return false;
2881 }
2882 self.snapshot();
2883 let clips = self.lane_mut(lane).expect("checked above");
2884 clips[idx].fade_out = frames.min(clips[idx].frames());
2885 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2886 true
2887 }
2888
2889 /// Every frame number on every lane rewritten onto a timeline counted at
2890 /// another rate: `k` is old timeline frames per new one, `counts` is how
2891 /// long each source is on the *new* timeline (indexed as
2892 /// [`Project::sources`] is), and the edit survives as the same seconds of
2893 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2894 /// the edit list, and the only thing that touches the frame numbers without
2895 /// being an edit anyone made.
2896 ///
2897 /// Every position -- a clip's start and its end alike -- goes through the
2898 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2899 /// stays a gap, and a take's picture and its sound land on the same frame on
2900 /// their two lanes: no lane can drift against another. A clip is then only
2901 /// ever made to *fit* the room its own start and end mapped to, never to
2902 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2903 /// below is the backstop for the one case that could: a slow clip so short
2904 /// that no source range fits its new room at all).
2905 ///
2906 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2907 /// onto the new grid, so a rate picked, unpicked and picked again is within
2908 /// a frame of where it started rather than back at it. Upgrade path is
2909 /// keeping the edit list at one reference rate and conforming on the way
2910 /// out, which every frame number in this module would then be measured in.
2911 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2912 for lane in &mut self.lanes {
2913 let mut cursor = 0;
2914 for clip in &mut lane.clips {
2915 let start = k.timeline_at(clip.start).max(cursor);
2916 // The room its own end mapped to -- never zero, since a clip is
2917 // never empty even on a grid too coarse to hold it.
2918 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2919 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2920 // Its footage, held inside the file's new length: a clip whose
2921 // out-point was the last frame of its source must not come out
2922 // of this naming a frame past the end -- that is a project that
2923 // would not open again ([`crate::PlaybackSession::open_project`]
2924 // refuses one by name).
2925 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2926 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2927 clip.start = start;
2928 clip.in_frame = in_frame;
2929 clip.out_frame = in_frame + len;
2930 cursor = clip.end();
2931 }
2932 // A subtitle's *window* is in microseconds and a rate change moves
2933 // no seconds, so only where it sits is remapped -- through the same
2934 // [`Rate::timeline_at`] every clip boundary goes through, so a
2935 // caption still starts on the frame its picture does.
2936 let mut cursor = 0;
2937 for sub in &mut lane.subs {
2938 let start = k.timeline_at(sub.start).max(cursor);
2939 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2940 sub.start = start;
2941 cursor = sub.end();
2942 }
2943 }
2944 }
2945
2946 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2947 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2948 ///
2949 /// A subtitle lane counts like any other: a caption placed past the last
2950 /// picture holds the timeline open under it, exactly as an `A2` running
2951 /// past `V1` does, rather than being silently clipped away by the length
2952 /// ([`crate::export::timeline_cues`] clips cues to this).
2953 pub fn timeline_frames(&self) -> u32 {
2954 self.lanes
2955 .iter()
2956 .filter_map(|l| match l.kind {
2957 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2958 _ => l.clips.last().map(Clip::end),
2959 })
2960 .max()
2961 .unwrap_or(0)
2962 }
2963
2964 /// The same, counting the *media* alone: where the last picture or sound
2965 /// runs out, with the captions over them ignored.
2966 ///
2967 /// What an export actually writes ends here -- the picture loop walks the
2968 /// composite spans and the file stops with them -- so this is the length a
2969 /// cue has to be inside of to be written at all (what
2970 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2971 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2972 /// thing is a picture or a sound, which is every timeline that has no
2973 /// caption hanging past the end of both.
2974 pub fn media_frames(&self) -> u32 {
2975 self.lanes
2976 .iter()
2977 .filter(|l| l.kind != LaneKind::Subtitle)
2978 .filter_map(|l| l.clips.last().map(Clip::end))
2979 .max()
2980 .unwrap_or(0)
2981 }
2982
2983 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2984 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2985 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2986 self.lane_spans(Lane::V1)
2987 }
2988
2989 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2990 // Timeline frames, not source ones: a box on a lane is as wide as the
2991 // clip is long *there*, which a speed halves or quadruples.
2992 self.lane(lane)
2993 .iter()
2994 .map(|c| (c.start, c.frames()))
2995 .collect()
2996 }
2997
2998 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2999 /// and past the end -- [`Project::span_at`] is the version that tells those
3000 /// two apart.
3001 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
3002 let clips = self.lane(lane);
3003 let idx = at(clips, timeline_frame)?;
3004 Some((idx, source_frame(&clips[idx], timeline_frame)))
3005 }
3006
3007 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
3008 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
3009 self.map(Lane::V1, timeline_frame)
3010 }
3011
3012 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
3013 /// it, or the gap running to the next clip (or to the end of the timeline,
3014 /// which is where a lane shorter than its neighbour keeps showing black).
3015 /// `None` at or past the end of the timeline, which is the only "nothing
3016 /// left" there is.
3017 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
3018 let total = self.timeline_frames();
3019 if timeline_frame >= total {
3020 return None;
3021 }
3022 let clips = self.lane(lane);
3023 Some(match at(clips, timeline_frame) {
3024 Some(idx) => Span {
3025 start: timeline_frame,
3026 len: clips[idx].end() - timeline_frame,
3027 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
3028 speed: clips[idx].speed,
3029 },
3030 None => Span {
3031 start: timeline_frame,
3032 speed: Speed::NORMAL,
3033 // The next placement, or the end of the timeline: a gap is
3034 // bounded by what comes after it, never by its own bookkeeping.
3035 len: clips
3036 .iter()
3037 .find(|c| c.start > timeline_frame)
3038 .map_or(total, |c| c.start)
3039 - timeline_frame,
3040 from: None,
3041 },
3042 })
3043 }
3044
3045 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
3046 /// gaps included -- the whole play list, which is what an export walks.
3047 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
3048 let mut out = Vec::new();
3049 let mut t = timeline_frame;
3050 while let Some(span) = self.span_at(lane, t) {
3051 t = span.end();
3052 out.push(span);
3053 }
3054 out
3055 }
3056
3057 /// What the *composite* shows from `timeline_frame` on -- the answer
3058 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
3059 /// video lane by one rule: **the topmost lane with a clip there wins**, and
3060 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
3061 /// (the usual overlay convention). A frame no video lane covers is a gap,
3062 /// which is black however many lanes are above or below it.
3063 ///
3064 /// No blending, so exactly one lane is visible at a time and the composite
3065 /// is itself a span list -- which is why one decoder plays it, the same one
3066 /// a single-lane timeline uses, rather than N running at once.
3067 ///
3068 /// The span is cut short wherever a *higher* lane's clip starts, because
3069 /// from that frame on a different lane wins; that is what makes walking
3070 /// [`composite_spans_from`](Project::composite_spans_from) correct.
3071 ///
3072 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
3073 /// lanes would then be visible in one frame and the caller needs a decoder
3074 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
3075 /// (this same walk, per lane) feeding N decoders.
3076 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
3077 let total = self.timeline_frames();
3078 if timeline_frame >= total {
3079 return None;
3080 }
3081 let video = self.video_lanes();
3082 // The last covering lane is the winner; only the lanes above it can
3083 // interrupt what it shows.
3084 let winner = video
3085 .iter()
3086 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
3087 let (from, speed, until) = match winner {
3088 Some(i) => {
3089 let clips = self.lane(video[i]);
3090 let idx = at(clips, timeline_frame).expect("just found above");
3091 (
3092 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
3093 clips[idx].speed,
3094 clips[idx].end(),
3095 )
3096 }
3097 // Nothing covers it: black until something above the floor starts.
3098 None => (None, Speed::NORMAL, total),
3099 };
3100 let takeover = video[winner.map_or(0, |i| i + 1)..]
3101 .iter()
3102 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
3103 .map(|c| c.start)
3104 .min();
3105 Some(Span {
3106 start: timeline_frame,
3107 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
3108 from,
3109 speed,
3110 })
3111 }
3112
3113 /// The video lanes in display order, topmost last -- the order the composite
3114 /// rule counts in.
3115 fn video_lanes(&self) -> Vec<Lane> {
3116 self.lanes()
3117 .into_iter()
3118 .filter(|l| l.kind == LaneKind::Video)
3119 .collect()
3120 }
3121
3122 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
3123 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
3124 /// index on that lane. `None` over a gap and past the end. What a front-end
3125 /// asks to act on "the clip on screen" without re-deriving the rule.
3126 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
3127 let video = self.video_lanes();
3128 let winner = video
3129 .iter()
3130 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
3131 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
3132 }
3133
3134 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
3135 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
3136 /// answers "the clip on screen"; this answers it per lane, which is what
3137 /// walking the lanes for something to select needs.
3138 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
3139 at(self.lane(lane), timeline_frame)
3140 }
3141
3142 /// How the composite is graded at `timeline_frame`, so the picture playback
3143 /// converts and the one an export encodes are graded from one answer.
3144 /// `None` over a gap (black is black) and for a clip nobody has graded,
3145 /// which is the byte-identical path everywhere.
3146 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
3147 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3148 self.color_of(lane, idx)
3149 }
3150
3151 /// [`composite_color_at`](Self::composite_color_at)'s twin for
3152 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
3153 /// policy's own placement.
3154 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
3155 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3156 self.transform_of(lane, idx)
3157 }
3158
3159 /// How the composite meets the project canvas at `timeline_frame`, so the
3160 /// picture playback composes and the one an export encodes are placed from
3161 /// one answer. `Fit` over a gap, where black is already the canvas.
3162 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
3163 self.composite_clip_at(timeline_frame)
3164 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
3165 }
3166
3167 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
3168 /// over a gap / a picture that is not a visualizer.
3169 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
3170 self.composite_clip_at(timeline_frame)
3171 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
3172 .unwrap_or(0)
3173 }
3174
3175 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
3176 /// `timeline_frame`, or zero over a gap / a picture that is not a
3177 /// visualizer.
3178 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
3179 self.composite_clip_at(timeline_frame)
3180 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
3181 .unwrap_or(0)
3182 }
3183
3184 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
3185 /// viewer sees from `timeline_frame` to the end, in order. What an export
3186 /// encodes and what playback walks at a clip boundary.
3187 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
3188 let mut out = Vec::new();
3189 let mut t = timeline_frame;
3190 while let Some(span) = self.composite_span_at(t) {
3191 t = span.end();
3192 out.push(span);
3193 }
3194 out
3195 }
3196
3197 /// Split every lane at `timeline_frame`, so that frame becomes the first
3198 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
3199 /// (`false`, no change) when no lane has a clip to split there -- at a
3200 /// placement's own start, in a gap, and past the end -- all of which would
3201 /// produce an empty clip or nothing at all.
3202 ///
3203 /// Lanes' halves share an id only where they are the *same* span: the lanes
3204 /// are edited apart, so the clip being cut here may start (or end)
3205 /// somewhere else on another lane, and a group id whose clips disagree
3206 /// about their span is not one take (see [`links_are_consistent`], which
3207 /// refuses to load one).
3208 ///
3209 /// Metadata only: no mapping changes, in any lane.
3210 pub fn split(&mut self, timeline_frame: u32) -> bool {
3211 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
3212 }
3213
3214 /// [`split`](Project::split), with the snapshot optional and the lanes
3215 /// named: a batch that has already taken a snapshot
3216 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3217 /// region and must still be one undo press, and a *scoped* batch must not
3218 /// cut a lane it was told to leave alone.
3219 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3220 let cut: Vec<Option<Clip>> = self
3221 .lanes
3222 .iter()
3223 .enumerate()
3224 .map(|(i, l)| {
3225 on.contains(&i)
3226 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3227 .flatten()
3228 })
3229 .collect();
3230 // The same question on the subtitle lanes, in their own arithmetic: a
3231 // razor cuts the captions with the picture, and a frame where only a
3232 // caption can be cut is still a cut.
3233 let cut_subs: Vec<bool> = self
3234 .lanes
3235 .iter()
3236 .enumerate()
3237 .map(|(i, l)| {
3238 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
3239 })
3240 .collect();
3241 // The links the captions carry, read before the room is opened below
3242 // -- `sub_open_room` takes the id off both halves, exactly as
3243 // `open_room` does for a clip, and the split hands the halves theirs
3244 // back afterwards.
3245 let sub_orig: Vec<Option<u32>> = self
3246 .lanes
3247 .iter()
3248 .zip(&cut_subs)
3249 .map(|(l, &cut)| {
3250 cut.then(|| {
3251 l.subs
3252 .iter()
3253 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3254 .and_then(|s| s.link)
3255 })
3256 .flatten()
3257 })
3258 .collect();
3259 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3260 return false;
3261 }
3262 if snapshot {
3263 self.snapshot();
3264 }
3265 for (data, _) in self
3266 .lanes
3267 .iter_mut()
3268 .zip(&cut_subs)
3269 .filter(|&(_, &cut)| cut)
3270 {
3271 // A split is room of no width: the halves keep their windows by
3272 // proportion and nothing moves.
3273 sub_open_room(&mut data.subs, timeline_frame, 0);
3274 debug_assert!(subs_sorted_disjoint(&data.subs));
3275 }
3276 // Each side is its own question, and the answer is the group the clip
3277 // already carried: the left half *keeps* its take's id -- the take the
3278 // frames before the cut still are -- and the right halves of one take
3279 // share one fresh id of their own, clips and captions alike. A lane
3280 // holding no group (a `place`ment, a caption nobody grouped) comes out
3281 // of the cut holding none, which is what it went in with. The captions'
3282 // own links were drawn above, before the room opened.
3283 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3284 let mut distinct: Vec<u32> = Vec::new();
3285 for id in orig.iter().chain(&sub_orig).flatten() {
3286 if !distinct.contains(id) {
3287 distinct.push(*id);
3288 }
3289 }
3290 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3291 let right_of =
3292 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
3293 for (l, data) in self.lanes.iter_mut().enumerate() {
3294 if !cut_subs[l] {
3295 continue;
3296 }
3297 // The pair the razor just made: they touch at the frame it cut.
3298 if let Some(idx) = data
3299 .subs
3300 .iter()
3301 .position(|s| s.end() == timeline_frame)
3302 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
3303 {
3304 data.subs[idx].link = sub_orig[l];
3305 data.subs[idx + 1].link = right_of(sub_orig[l]);
3306 }
3307 }
3308 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3309 // The lanes this call was not scoped to are not cut, whatever their
3310 // own clips would allow.
3311 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
3312 continue;
3313 };
3314 let mut tail = data.clips[idx];
3315 // Where the cut lands *in the file*, which is the clip's own rate
3316 // away from where it lands on the timeline. Both halves keep the
3317 // speed, and `splittable` has already refused any frame at which
3318 // the two would not add up to the one being cut.
3319 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3320 tail.start = timeline_frame;
3321 tail.link = right_of(orig[data_i]);
3322 // A split makes a new edge for each half, and a fade is a promise
3323 // about an edge: only the half that *kept* the original edge
3324 // keeps that fade, re-clamped to its own now-shorter length (a
3325 // cut inside the ramp shortens it, never leaves it pointing past
3326 // the clip it is on); the edge the cut itself made starts, or
3327 // ends, flat -- there was no silence there to ramp out of.
3328 tail.fade_in = 0;
3329 tail.fade_out = tail.fade_out.min(tail.frames());
3330 // A dissolve is a promise about the *end* edge, same as
3331 // `fade_out`: only the half that kept the clip's original end
3332 // (the tail) keeps it, re-clamped to its own now-shorter length;
3333 // the head's new end is the cut the razor just made, which starts
3334 // flat -- there was no successor to dissolve into there.
3335 tail.transition_out = tail.transition_out.min(tail.frames());
3336 data.clips[idx].out_frame = tail.in_frame;
3337 data.clips[idx].link = orig[data_i];
3338 data.clips[idx].fade_out = 0;
3339 data.clips[idx].transition_out = 0;
3340 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3341 data.clips.insert(idx + 1, tail);
3342 }
3343 true
3344 }
3345
3346 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3347 /// at `timeline_frame` in every lane and put the result back in one group.
3348 /// Only what a split could have produced is rejoined -- the two sides must
3349 /// touch on the timeline *and* be consecutive frames of the same source --
3350 /// so the clip list comes back exactly as it was and traversal with it.
3351 /// `false` when no lane has such a pair. The rejoined placement keeps the
3352 /// **left** half's id, which is the take the split left on it: rejoining a
3353 /// cut take puts the take back, id and all.
3354 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3355 // What each lane would end up covering, if it joins here at all.
3356 let joined: Vec<Option<(u32, u32)>> = self
3357 .lanes
3358 .iter()
3359 .map(|l| {
3360 joinable(&l.clips, timeline_frame)
3361 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3362 })
3363 .collect();
3364 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3365 let join_subs: Vec<Option<usize>> = self
3366 .lanes
3367 .iter()
3368 .map(|l| sub_joinable(&l.subs, timeline_frame))
3369 .collect();
3370 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3371 return false;
3372 }
3373 self.snapshot();
3374 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3375 if let Some(idx) = sub {
3376 data.subs[idx].frames += data.subs[idx + 1].frames;
3377 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3378 data.subs.remove(idx + 1);
3379 debug_assert!(subs_sorted_disjoint(&data.subs));
3380 }
3381 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3382 continue;
3383 };
3384 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3385 data.clips.remove(idx + 1);
3386 }
3387 true
3388 }
3389
3390 /// Take the placement at `idx` of `lane` out of its group: every clip and
3391 /// every caption carrying its id -- on however many lanes -- is handed an
3392 /// id of its own, so from here on each half moves, trims and is deleted
3393 /// alone. The music video whose sound is to be cut against its picture
3394 /// starts here, and so does the caption that has to come off the picture it
3395 /// was pinned to.
3396 ///
3397 /// An id of its own rather than none at all: a half no other lane is grouped
3398 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3399 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3400 /// as detached. `None` would instead say "was never part of a take", which
3401 /// is what a one-lane [`place`](Project::place) means.
3402 ///
3403 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3404 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3405 /// the group back. Refused (`false`, nothing changed) for an index that is
3406 /// not there, a placement in no group at all, and one whose group has no
3407 /// other half -- that one is already detached, and a refusal must not cost
3408 /// an undo step.
3409 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3410 let Some(members) = self.group_of(lane, idx) else {
3411 return false;
3412 };
3413 if members.alone() {
3414 return false;
3415 }
3416 let Some(id) = self
3417 .lane(lane)
3418 .get(idx)
3419 .and_then(|c| c.link)
3420 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3421 else {
3422 return false;
3423 };
3424 self.snapshot();
3425 // Drawn before the walk: `new_link` takes the whole project, and the
3426 // walk holds the lanes.
3427 let count = members.clips.len() + members.subs.len();
3428 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3429 for data in &mut self.lanes {
3430 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3431 c.link = fresh.pop();
3432 }
3433 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3434 s.link = fresh.pop();
3435 }
3436 }
3437 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3438 true
3439 }
3440
3441 /// Put two clips on two lanes into one group, so what moves one moves the
3442 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3443 /// how a picture is regrouped with sound it was never opened with. Whatever
3444 /// either of them was grouped with comes along: those clips cover this same
3445 /// span already, so the result is one group and not two overlapping ones.
3446 ///
3447 /// Same frames or nothing: a group id names **one span** on however many
3448 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3449 /// clips that do not cover the same frames cannot be one take, and the
3450 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3451 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3452 /// mean, not the rule.
3453 ///
3454 /// Metadata only, one snapshot. The error says what is wrong, because
3455 /// `false` would not: a bad index, one lane twice (a group is at most one
3456 /// clip per lane), spans that disagree, and a pair that is already one take
3457 /// -- nothing changes, and none of them costs an undo step.
3458 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3459 if a == b {
3460 return Err(format!(
3461 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3462 a.label()
3463 )
3464 .into());
3465 }
3466 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3467 p.lane(lane)
3468 .get(idx)
3469 .copied()
3470 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3471 };
3472 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3473 if (x.start, x.end()) != (y.start, y.end()) {
3474 return Err(format!(
3475 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3476 a.label(),
3477 x.start,
3478 x.end(),
3479 b.label(),
3480 y.start,
3481 y.end()
3482 )
3483 .into());
3484 }
3485 if x.link.is_some() && x.link == y.link {
3486 return Err("those two are one take already".into());
3487 }
3488 self.snapshot();
3489 let id = self.new_link();
3490 // Every clip either of them was grouped with, by the same rule: all of
3491 // them cover this span, so one id over the lot stays consistent.
3492 let old = [x.link, y.link];
3493 for data in &mut self.lanes {
3494 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3495 if old.contains(&c.link) {
3496 c.link = Some(id);
3497 }
3498 }
3499 }
3500 // And the two themselves, which a `place` may have left in no group.
3501 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3502 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3503 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3504 Ok(())
3505 }
3506
3507 /// Put every placement the picks name into one group -- the group a hand
3508 /// builds with ctrl-click and a menu: the picture, its sound and the
3509 /// caption over it, on as many lanes as the picks name. What any of them
3510 /// was already grouped with rides along (one group, not two sharing a
3511 /// member), and the members keep their own spans: a group is one id over
3512 /// one placement per lane, and the offsets between them are what the group
3513 /// preserves -- a drag, a trim and a delete all move the members *by the
3514 /// same distance*, not to the same frames.
3515 ///
3516 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3517 /// and the refusal says which lane -- and a pick that names nothing is
3518 /// refused with its own words. At least two picks, or there is nothing to
3519 /// group.
3520 ///
3521 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3522 /// apart again. None of the refusals changes anything or costs an undo
3523 /// step.
3524 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3525 if picks.len() < 2 {
3526 return Err("a group is two placements or more: pick another one first".into());
3527 }
3528 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3529 for &(lane, idx) in picks {
3530 if seen.contains(&lane) {
3531 return Err(format!(
3532 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3533 track",
3534 lane.label()
3535 )
3536 .into());
3537 }
3538 seen.push(lane);
3539 let there = if lane.kind == LaneKind::Subtitle {
3540 idx < self.sub_lane(lane).len()
3541 } else {
3542 idx < self.lane(lane).len()
3543 };
3544 if !there {
3545 let what = if lane.kind == LaneKind::Subtitle {
3546 "subtitle"
3547 } else {
3548 "clip"
3549 };
3550 return Err(
3551 format!("there is no {what} {idx} on {}", lane.label()).into()
3552 );
3553 }
3554 }
3555 let links: Vec<Option<u32>> = picks
3556 .iter()
3557 .map(|&(lane, idx)| {
3558 if lane.kind == LaneKind::Subtitle {
3559 self.sub_lane(lane)[idx].link
3560 } else {
3561 self.lane(lane)[idx].link
3562 }
3563 })
3564 .collect();
3565 // The picks are already one per lane (`seen`, above), but a pick's
3566 // *existing* group can carry a second member onto a lane another
3567 // pick (or another existing group in the merge) already occupies --
3568 // two captions on one sub lane, say, each grouped with a different
3569 // clip before this call. Merging both in would leave that lane with
3570 // two members of one id, which `links_are_consistent` may never see:
3571 // refused by name, before anything moves, rather than a group closed
3572 // broken.
3573 let labels = handles(&self.lanes);
3574 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3575 for (li, data) in self.lanes.iter().enumerate() {
3576 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3577 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3578 if n > 0 {
3579 per_lane.insert(li, n as u32);
3580 }
3581 }
3582 // A pick that carries no link of its own is invisible to the scan
3583 // above (there is no `Some` to match): it still claims its lane.
3584 for &(lane, _) in picks {
3585 let li = self.index(lane).expect("checked above");
3586 per_lane.entry(li).or_insert(0);
3587 if !self.lanes[li]
3588 .clips
3589 .iter()
3590 .any(|c| c.link.is_some() && links.contains(&c.link))
3591 && !self.lanes[li]
3592 .subs
3593 .iter()
3594 .any(|s| s.link.is_some() && links.contains(&s.link))
3595 {
3596 *per_lane.get_mut(&li).expect("just inserted") += 1;
3597 }
3598 }
3599 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3600 return Err(format!(
3601 "a group is one placement per lane: merging these groups would put two on {}",
3602 labels[li].label()
3603 )
3604 .into());
3605 }
3606 self.snapshot();
3607 let id = self.new_link();
3608 // Whatever any pick was grouped with comes along, for [`group`]'s
3609 // reason -- one id over the lot, not two groups sharing a member.
3610 for data in &mut self.lanes {
3611 for c in data.clips.iter_mut() {
3612 if c.link.is_some() && links.contains(&c.link) {
3613 c.link = Some(id);
3614 }
3615 }
3616 for s in data.subs.iter_mut() {
3617 if s.link.is_some() && links.contains(&s.link) {
3618 s.link = Some(id);
3619 }
3620 }
3621 }
3622 // And the picks themselves, which a `place` may have left in no group.
3623 // The lane seats are read before the walk, which holds the lanes.
3624 let seats: Vec<(usize, bool)> = picks
3625 .iter()
3626 .map(|&(lane, _)| {
3627 (
3628 self.index(lane).expect("checked above"),
3629 lane.kind == LaneKind::Subtitle,
3630 )
3631 })
3632 .collect();
3633 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3634 let _ = lane;
3635 if sub {
3636 self.lanes[at].subs[idx].link = Some(id);
3637 } else {
3638 self.lanes[at].clips[idx].link = Some(id);
3639 }
3640 }
3641 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3642 Ok(())
3643 }
3644
3645 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3646 /// lands on and leaving every other clip exactly where it is -- the
3647 /// per-lane paste. Anything already there is trimmed away (and split in two
3648 /// if `clip` lands inside it), which is what keeps the lane sorted and
3649 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3650 /// gap. Refused only for an empty `clip`.
3651 ///
3652 /// The placement belongs to no group: a clipboard clip carries the link id
3653 /// of the take it was copied from, and placing it twice -- or placing a copy
3654 /// back over the clip it came from -- would put that id on two clips of one
3655 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3656 /// `None` rather than a fresh id because a one-lane placement has nothing on
3657 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3658 /// become a group again.
3659 ///
3660 /// Refused for an empty `clip`, for a lane that is not there, and for a
3661 /// subtitle lane, which carries no picture and no sound
3662 /// ([`Project::place_sub`] is its door).
3663 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3664 if clip.out_frame <= clip.in_frame
3665 || lane.kind == LaneKind::Subtitle
3666 || self.index(lane).is_none()
3667 {
3668 return false;
3669 }
3670 self.snapshot();
3671 let clip = Clip {
3672 fade_in: 0,
3673 fade_out: 0,
3674 transition_out: 0,
3675 start: timeline_frame,
3676 link: None,
3677 ..clip
3678 };
3679 self.insert_over(lane, clip);
3680 true
3681 }
3682
3683 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3684 /// one grouped take -- what a picture let go over a further video track
3685 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3686 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3687 /// this half a file with sound landed on a layer silent, and the only way to
3688 /// hear it was to drop it a second time on an audio lane.
3689 ///
3690 /// Both halves overwrite what they land on and neither ripples, exactly as
3691 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3692 /// nothing under it moves. One history snapshot for the pair, the added lane
3693 /// included, so one [`Project::undo`] takes the whole placement back. The two
3694 /// carry one link, which is what makes them one take to a drag, a trim and a
3695 /// save.
3696 ///
3697 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3698 /// there or is not a video lane: sound placed alone is
3699 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3700 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3701 if clip.out_frame <= clip.in_frame
3702 || lane.kind != LaneKind::Video
3703 || self.index(lane).is_none()
3704 {
3705 return false;
3706 }
3707 self.snapshot();
3708 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3709 // an ord names a lane only while every ord below it does.
3710 while self.lane_count(LaneKind::Audio) <= lane.ord {
3711 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3712 }
3713 let clip = Clip {
3714 fade_in: 0,
3715 fade_out: 0,
3716 transition_out: 0,
3717 start: timeline_frame,
3718 link: Some(self.new_link()),
3719 ..clip
3720 };
3721 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3722 self.insert_over(half, clip);
3723 }
3724 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3725 true
3726 }
3727
3728 /// `clip` into `lane` at its own start, over whatever it lands on: the
3729 /// insert both placement doors make, which is what keeps a lane sorted and
3730 /// disjoint. The caller has checked that the lane is there.
3731 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3732 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3733 clear(clips, clip.start, clip.end());
3734 let idx = clips.partition_point(|c| c.start < clip.start);
3735 clips.insert(idx, clip);
3736 debug_assert!(sorted_disjoint(clips));
3737 }
3738
3739 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3740 /// frame `start`: the drag that rearranges takes, along a track and across
3741 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3742 /// was. `start` at the clip's own is the pure lane change.
3743 ///
3744 /// The whole group travels the same distance, each half on the lane it
3745 /// already sits on -- a link means "these cover one span on however many
3746 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3747 /// sound would be a group no save could load. Only the dragged half changes
3748 /// lane, and that is not a desync: a link names no lane at all.
3749 ///
3750 /// `start` is **clamped**, never refused, to the room the group has: no
3751 /// member crosses a neighbour on the lane it lands on, exactly as
3752 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3753 /// dragging past a neighbour means "as far as it goes", and butting up
3754 /// against the take next door is how clips are laid end to end. The
3755 /// tightest member's wall wins, so a sound half boxed in between two others
3756 /// holds its picture still.
3757 ///
3758 /// Refused, changing nothing and costing no undo step, for a lane that is
3759 /// not there, an index that is not there, a move across *kinds* (a picture
3760 /// cannot play on an audio lane, and the save it wrote would not open
3761 /// again), a head let go *inside* another clip or into a gap too narrow to
3762 /// hold this one -- a move that overwrote what it landed on would destroy a
3763 /// take the pointer never named, which is what [`place`](Project::place)
3764 /// may do and a drag may not -- a half let go onto the lane its own partner
3765 /// is on, and a drop that changes neither lane nor frame, which is a clip
3766 /// picked up and put back down, i.e. a click.
3767 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3768 self.move_selection(&[(from, idx)], from, idx, to, start)
3769 }
3770
3771 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
3772 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
3773 /// reads it) travels the same distance as the clip at `idx` of `from`,
3774 /// which alone changes lane, onto `to`. One clamp across the whole set
3775 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
3776 /// neighbour that boxes in *any* member narrows the delta every member
3777 /// moves by, and a member with no room at all (`lo > hi`) refuses the
3778 /// whole set rather than moving the rest and leaving that one behind.
3779 /// `move_clip` is this with a selection of one -- the dragged clip's own
3780 /// group and nothing else -- so a drag on a clip outside the selection is
3781 /// byte-identical to before this existed.
3782 pub fn move_selection(
3783 &mut self,
3784 picks: &[(Lane, usize)],
3785 from: Lane,
3786 idx: usize,
3787 to: Lane,
3788 start: u32,
3789 ) -> bool {
3790 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3791 return false;
3792 };
3793 if from.kind != to.kind {
3794 return false;
3795 }
3796 let held = self.index(from).expect("the clip was found on it");
3797 // Every pick's own group, unioned: the whole selection moves as one,
3798 // and a pick's link partners (not themselves picked) come along with
3799 // it exactly as a lone drag's do.
3800 let mut members = Members::default();
3801 for &(lane, i) in picks {
3802 let Some(group) = self.group_of(lane, i) else {
3803 continue;
3804 };
3805 for m in group.clips {
3806 if !members.clips.contains(&m) {
3807 members.clips.push(m);
3808 }
3809 }
3810 for m in group.subs {
3811 if !members.subs.contains(&m) {
3812 members.subs.push(m);
3813 }
3814 }
3815 }
3816 if !members.clips.contains(&(held, idx)) {
3817 members.clips.push((held, idx));
3818 }
3819 // The two halves of *the dragged clip's own* group would land on one
3820 // span of one lane, which is the one thing a link may never mean --
3821 // checked against that group alone, not the whole moving set: an
3822 // unlinked fellow pick already sitting on `dest` is no conflict at
3823 // all, since it travels by the same delta and `move_room` below
3824 // leaves it the room to. Refused rather than clamped: the partner
3825 // moves the same distance, so there is no room for it anywhere on
3826 // that lane.
3827 let own_group = self.group_of(from, idx).expect("the clip was found");
3828 if dest != held
3829 && own_group
3830 .clips
3831 .iter()
3832 .chain(&own_group.subs)
3833 .any(|&(l, _)| l == dest)
3834 {
3835 return false;
3836 }
3837 let want = i64::from(start) - i64::from(clip.start);
3838 // How far the group may travel, in timeline frames and signed: every
3839 // member -- the clips and any caption grouped with them -- narrows it
3840 // to the gap it is landing in, and what is left is what the pointer is
3841 // clamped to.
3842 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3843 return false;
3844 };
3845 if lo > hi {
3846 return false;
3847 }
3848 let delta = want.clamp(lo, hi);
3849 if delta == 0 && dest == held {
3850 return false;
3851 }
3852 self.snapshot();
3853 for &(l, i) in &members.clips {
3854 let c = &mut self.lanes[l].clips[i];
3855 // In range by the walls above, which are `u32` frames throughout.
3856 c.start = (i64::from(c.start) + delta) as u32;
3857 }
3858 for &(l, i) in &members.subs {
3859 let s = &mut self.lanes[l].subs[i];
3860 s.start = (i64::from(s.start) + delta) as u32;
3861 }
3862 if dest != held {
3863 let clip = self.lanes[held].clips.remove(idx);
3864 let clips = &mut self.lanes[dest].clips;
3865 let at = clips.partition_point(|c| c.start < clip.start);
3866 clips.insert(at, clip);
3867 }
3868 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3869 debug_assert!(members
3870 .clips
3871 .iter()
3872 .chain(&members.subs)
3873 .all(|&(l, _)| {
3874 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3875 }));
3876 true
3877 }
3878
3879 /// How far a group drag may travel, `(least, most)` in timeline frames and
3880 /// signed: every member narrows the range to the gap it is landing in --
3881 /// the clips against their lanes' clips and the captions against their
3882 /// lanes' captions -- and what is left is what the pointer is clamped to.
3883 /// `travelling` names the one member that changes lane, if any: the clip a
3884 /// hand is carrying onto another track, whose walls are read on the lane it
3885 /// is let go over at the frame the pointer named. `None` when a member has
3886 /// no gap to land in at all.
3887 fn move_room(
3888 &self,
3889 members: &Members,
3890 travelling: Option<(usize, usize, usize, u32)>,
3891 ) -> Option<(i64, i64)> {
3892 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3893 for &(l, i) in members.clips.iter().chain(&members.subs) {
3894 let sub = members.subs.contains(&(l, i));
3895 let (start, frames) = match self.lanes[l]
3896 .clips
3897 .get(i)
3898 .filter(|_| !sub)
3899 .map(|c| (c.start, c.frames()))
3900 {
3901 Some(pair) => pair,
3902 None => {
3903 let s = self.lanes[l].subs.get(i)?;
3904 (s.start, s.frames)
3905 }
3906 };
3907 let land = travelling
3908 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3909 .map_or(l, |(_, _, dest, _)| dest);
3910 // Which gap this member's walls are read off: its own place on the
3911 // lane it stays on, and the frame the pointer named on the lane it
3912 // is let go over. A clip's neighbours are the clips of the lane it
3913 // lands on and a caption's are its captions -- the two lists of one
3914 // lane never meet.
3915 let at = match travelling {
3916 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3917 _ => start,
3918 };
3919 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3920 let neighbours: Vec<(u32, u32)> = if sub {
3921 self.lanes[land]
3922 .subs
3923 .iter()
3924 .map(|s| (s.start, s.end()))
3925 .collect()
3926 } else {
3927 self.lanes[land]
3928 .clips
3929 .iter()
3930 .map(|c| (c.start, c.end()))
3931 .collect()
3932 };
3933 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3934 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3935 continue;
3936 }
3937 if *other_start <= at && at < *other_end {
3938 // A head let go inside another placement, which a clamp
3939 // has no answer for: the drop is refused.
3940 return None;
3941 }
3942 match other_end <= &at {
3943 true => wall_lo = wall_lo.max(*other_end),
3944 false => wall_hi = wall_hi.min(*other_start),
3945 }
3946 }
3947 if wall_hi - wall_lo < frames {
3948 return None;
3949 }
3950 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3951 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3952 }
3953 Some((lo, hi))
3954 }
3955
3956 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3957 /// the drag on a clip's end that makes it play more or less of its source.
3958 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3959 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3960 /// is room that was already empty. One snapshot, so a whole drag is one
3961 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3962 /// sample. Changes the timeline->source mapping: the caller must reseek.
3963 ///
3964 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3965 /// exactly what they played before, which is what makes this a trim and not
3966 /// a slip.
3967 ///
3968 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3969 /// legal means "as far as it goes", and stopping the box there is the
3970 /// affordance. The walls are: one frame of clip always survives, an edge
3971 /// never crosses the neighbouring clip on its own lane, an in-point never
3972 /// walks back past the source's first frame, and an out-point never runs
3973 /// past `source_frames[clip.source]` -- the caller's table of how long each
3974 /// source actually is ([`Project`] does not know, and a clip ending past its
3975 /// file's last frame is a save that will not open again; see
3976 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3977 /// there may not grow at all.
3978 ///
3979 /// Linked placements trim *together*, by one delta: every member's same
3980 /// edge moves the distance the dragged one did, clamped to the room its
3981 /// own walls leave -- offsets between the members of a hand-built group
3982 /// survive the trim, exactly as they survive a drag.
3983 ///
3984 /// `false`, changing nothing and costing no undo step, for an index that is
3985 /// not there and for an edge that is already where it was asked to go.
3986 pub fn trim(
3987 &mut self,
3988 lane: Lane,
3989 idx: usize,
3990 edge: Edge,
3991 to: u32,
3992 source_frames: &[u32],
3993 ) -> bool {
3994 let (Some((lo, hi)), Some(clip)) = (
3995 self.trim_room(lane, idx, edge, source_frames),
3996 self.lane(lane).get(idx).copied(),
3997 ) else {
3998 return false;
3999 };
4000 let to = to.clamp(lo, hi);
4001 let at = match edge {
4002 Edge::Start => clip.start,
4003 Edge::End => clip.end(),
4004 };
4005 if to == at {
4006 return false;
4007 }
4008 // Worked out before anything moves: at a slow rate a room can be too
4009 // narrow to hold even one source frame ([`Speed::fit`]), and the
4010 // dragged clip refusing to fit must refuse the whole gesture rather
4011 // than be given a range wider than its room -- which is the overlap
4012 // the lane invariant exists to forbid. The walls below leave that room,
4013 // so this is the backstop for a project that came in through another
4014 // door.
4015 let room = match edge {
4016 // The frames that stay play what they played, so what survives is
4017 // measured from the *end*.
4018 Edge::Start => clip.end() - to,
4019 Edge::End => to - clip.start,
4020 };
4021 let Some(keep) = clip.speed.fit(room) else {
4022 return false;
4023 };
4024 let members = self.group_of(lane, idx).expect("checked above");
4025 self.snapshot();
4026 let still = self.is_still(&clip);
4027 let held = self.index(lane).expect("checked above");
4028 let c = &mut self.lanes[held].clips[idx];
4029 match edge {
4030 // A still has no earlier frame to walk an in-point back to --
4031 // every frame of it is the same picture -- so its head grows
4032 // *forward*: the range it plays is however long the new room is,
4033 // anchored at the source's frame 0. Bounded by `lo`, which is where
4034 // the cap in `source_frames` is applied.
4035 Edge::Start if still => {
4036 c.in_frame = 0;
4037 c.out_frame = keep;
4038 c.start = to;
4039 }
4040 Edge::Start => {
4041 // Non-negative by `lo`, which is what keeps the in-point on the
4042 // source.
4043 c.in_frame = c.out_frame - keep.min(c.out_frame);
4044 c.start = to;
4045 }
4046 // Never wider than the room the edge was clamped to: see
4047 // [`Speed::fit`].
4048 Edge::End => c.out_frame = c.in_frame + keep,
4049 }
4050 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
4051 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
4052 true
4053 }
4054
4055 /// The rest of a group after one member's `edge` has moved by `delta`:
4056 /// every other member's same edge moves the same distance, clamped to the
4057 /// room its own walls leave -- a clip's against its lane and its source,
4058 /// a caption's against its own lane, its window following by the
4059 /// placement's own proportion. The undo step is the caller's: this is the
4060 // second half of one edit, not an edit of its own.
4061 fn follow_group(
4062 &mut self,
4063 members: &Members,
4064 dragged: &(usize, usize),
4065 edge: Edge,
4066 delta: i64,
4067 source_frames: &[u32],
4068 ) {
4069 for &(l, i) in &members.clips {
4070 if (l, i) == *dragged {
4071 continue;
4072 }
4073 let c = self.lanes[l].clips[i];
4074 let at = match edge {
4075 Edge::Start => c.start,
4076 Edge::End => c.end(),
4077 };
4078 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
4079 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
4080 if to == at {
4081 continue;
4082 }
4083 let room = match edge {
4084 Edge::Start => c.end() - to,
4085 Edge::End => to - c.start,
4086 };
4087 let Some(keep) = c.speed.fit(room) else {
4088 continue;
4089 };
4090 let still = self.is_still(&self.lanes[l].clips[i]);
4091 let c = &mut self.lanes[l].clips[i];
4092 match edge {
4093 Edge::Start if still => {
4094 c.in_frame = 0;
4095 c.out_frame = keep;
4096 c.start = to;
4097 }
4098 Edge::Start => {
4099 c.in_frame = c.out_frame - keep.min(c.out_frame);
4100 c.start = to;
4101 }
4102 Edge::End => c.out_frame = c.in_frame + keep,
4103 }
4104 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4105 }
4106 for &(l, i) in &members.subs {
4107 if (l, i) == *dragged {
4108 continue;
4109 }
4110 let s = self.lanes[l].subs[i];
4111 let at = match edge {
4112 Edge::Start => s.start,
4113 Edge::End => s.end(),
4114 };
4115 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
4116 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
4117 if to == at {
4118 continue;
4119 }
4120 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
4121 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4122 }
4123 }
4124
4125 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
4126 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
4127 /// What a front-end drawing the box *during* a drag asks, so the live width
4128 /// is the width the release will commit and an edge stops under the pointer
4129 /// rather than snapping back. The **clip's own** walls: the rest of its
4130 /// group follows by the same delta within their own ([`follow_group`]), so
4131 /// what is drawn for the dragged edge is what its own clip will commit.
4132 /// `None` for an index that is not there.
4133 pub fn trim_room(
4134 &self,
4135 lane: Lane,
4136 idx: usize,
4137 edge: Edge,
4138 source_frames: &[u32],
4139 ) -> Option<(u32, u32)> {
4140 let l = self.index(lane)?;
4141 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
4142 }
4143
4144 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
4145 /// its lane's storage index: the one wall computation, asked for the clip
4146 /// itself and for each member a group trim carries.
4147 fn clip_room(
4148 &self,
4149 l: usize,
4150 i: usize,
4151 edge: Edge,
4152 source_frames: &[u32],
4153 ) -> (u32, u32) {
4154 let clips = &self.lanes[l].clips;
4155 let c = clips[i];
4156 let (lo, hi) = match edge {
4157 Edge::Start => (
4158 // Back to the source's own first frame -- as many *timeline*
4159 // frames as that head is worth at the clip's rate, which at
4160 // real time is the head itself -- and never over the clip in
4161 // front of it. Saturating because a clip may hold *more*
4162 // head than the timeline has room for -- a ripple delete
4163 // slides a clip back to frame 0 with its in-point wherever
4164 // the cut left it -- and frame 0 is the other wall.
4165 //
4166 // A still is measured from its *tail* instead: it has no
4167 // in-point worth the name (every frame the same picture), so
4168 // its head reaches exactly as far as its tail does -- out to
4169 // the length the caller's table gives it, whole. Measured
4170 // from the in-point it would have no head room at all, which
4171 // is a placed picture whose left edge cannot be dragged out.
4172 // No entry in the table means no growth, as it does at the
4173 // other end.
4174 if self.is_still(&c) {
4175 c.end().saturating_sub(
4176 c.speed
4177 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
4178 )
4179 } else {
4180 c.start.saturating_sub(c.speed.room(c.in_frame))
4181 }
4182 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
4183 // One *frame of clip* always survives, and at a rate below
4184 // real time one frame of clip is several frames of timeline
4185 // ([`Speed::room`]): an edge dragged closer than that would
4186 // ask for a range no source frame fits in. At real time this
4187 // is `end - 1`, unchanged.
4188 c.end() - c.speed.room(1),
4189 ),
4190 Edge::End => (
4191 // ...and the same wall from the other end: the shortest this
4192 // clip can be is the room one source frame of it takes.
4193 c.start + c.speed.room(1),
4194 // Out to whatever is left of the source -- again in timeline
4195 // frames, at this clip's rate -- and never over the clip
4196 // behind it.
4197 c.start
4198 .saturating_add(
4199 c.speed.room(
4200 source_frames
4201 .get(c.source)
4202 .copied()
4203 .unwrap_or(c.out_frame)
4204 .saturating_sub(c.in_frame),
4205 ),
4206 )
4207 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
4208 ),
4209 };
4210 // `hi.max(lo)`: for a clip the invariants hold for, the range always
4211 // contains the edge's own place, and a caller's wrong `source_frames`
4212 // must not become an empty range (or a panicking `clamp`) here.
4213 (lo, hi.max(lo))
4214 }
4215
4216 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
4217 /// every frame is the same picture, so which frame of it a clip's in-point
4218 /// names is not a question -- what [`Project::trim`] lets grow at either
4219 /// end. `false` for a source that is not there.
4220 fn is_still(&self, clip: &Clip) -> bool {
4221 self.sources
4222 .get(clip.source)
4223 .is_some_and(|s| crate::is_image(&s.path))
4224 }
4225
4226 /// The placements that move as one with the one at `idx` of `lane` --
4227 /// itself and whatever carries its link, on the media lanes and the
4228 /// subtitle ones alike. `None` for an index that is not there.
4229 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
4230 let sub = lane.kind == LaneKind::Subtitle;
4231 let link = if sub {
4232 self.sub_lane(lane).get(idx)?.link
4233 } else {
4234 self.lane(lane).get(idx)?.link
4235 };
4236 let mut members = Members::default();
4237 match link {
4238 Some(link) => {
4239 for (l, data) in self.lanes.iter().enumerate() {
4240 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
4241 members.clips.push((l, i));
4242 }
4243 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
4244 members.subs.push((l, i));
4245 }
4246 }
4247 }
4248 None => {
4249 let l = self.index(lane).expect("the placement was found on it");
4250 if sub {
4251 members.subs.push((l, idx));
4252 } else {
4253 members.clips.push((l, idx));
4254 }
4255 }
4256 }
4257 Some(members)
4258 }
4259
4260 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4261 /// new group, pushing everything from there on later by its length in
4262 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4263 /// the clip it lands in is split around it; past the end of the timeline it
4264 /// goes down where it was asked for, with black in front of it -- which is
4265 /// what a library row let go on the open bed means, and what the ghost under
4266 /// the pointer promised. A clipboard means "put it here", not "here and
4267 /// black in front", and clamps to the end at its own door
4268 /// ([`crate::PlaybackSession::paste_at`]).
4269 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4270 ///
4271 /// `V1` and `A1` and no other lane, because a take is one picture and one
4272 /// sound: copying it onto every lane there is would play the same audio
4273 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4274 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4275 /// video lane it is a clip that decodes to nothing, and a save carrying one
4276 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4277 /// `V1` only, for the mirror of that reason. The room is still opened on
4278 /// every media lane, or the lanes it was not inserted into would slide out
4279 /// of step with the ones it was -- and the subtitle lanes are left alone:
4280 /// the words keep their own clock, and a caption that should travel with a
4281 /// clip is what a group is for.
4282 ///
4283 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4284 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4285 /// an empty `clip` and for one naming a source that is not there (both of
4286 /// which the public fields let a caller build), and for a paste whose ripple
4287 /// would push a clip past the last frame there is -- nothing is changed by
4288 /// any of them.
4289 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4290 let Some(source) = self.sources.get(clip.source) else {
4291 return false;
4292 };
4293 if clip.out_frame <= clip.in_frame {
4294 return false;
4295 }
4296 let audio_only = crate::is_audio(&source.path);
4297 // ...and its mirror: a still is a picture and no sound, so a copy of one
4298 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4299 // worker tries to demux -- which silences the *whole session*, not just
4300 // that clip -- and a save the engine's own `open_project` then refuses.
4301 let picture_only = crate::is_image(&source.path);
4302 // The frame it was asked for and no other: a row let go on the empty
4303 // bed past the last clip lands *there*, under the ghost that promised
4304 // it, with black in front. Clamping to the end here made every drop on
4305 // open bed an append -- the clipboard's rule, applied to a hand that
4306 // had named a place.
4307 let at = timeline_frame;
4308 // The room it takes on the timeline, which its speed decides -- not the
4309 // source range it reads.
4310 let len = clip.frames();
4311 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4312 // hand-written file may hold a clip that ends at the very last frame
4313 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4314 // rather than wrapped there -- a wrapped start lands *behind* the clip
4315 // it belongs after, which is an overlap no save will read back.
4316 if at.checked_add(len).is_none()
4317 || self
4318 .lanes
4319 .iter()
4320 .flat_map(|l| &l.clips)
4321 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4322 {
4323 return false;
4324 }
4325 // ...and room *to open*: the paste splits whatever it lands inside of,
4326 // and a speeded clip can only be cut where its own rate has a source
4327 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4328 // of one, which is the overlap a lane may never hold. At real time every
4329 // frame answers, so this cannot refuse an unspeeded paste.
4330 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4331 if self
4332 .lanes
4333 .iter()
4334 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4335 {
4336 return false;
4337 }
4338 self.snapshot();
4339 let clip = Clip {
4340 fade_in: 0,
4341 fade_out: 0,
4342 transition_out: 0,
4343 start: at,
4344 link: Some(self.new_link()),
4345 ..clip
4346 };
4347 // Only lanes that can play the source: a file with no picture belongs on
4348 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4349 // it for an import. On a video lane it would decode to nothing, and the
4350 // save it wrote would not open again.
4351 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4352 (true, _) => &[LaneKind::Audio],
4353 (_, true) => &[LaneKind::Video],
4354 _ => &[LaneKind::Video, LaneKind::Audio],
4355 };
4356 let takes: Vec<usize> = kinds
4357 .iter()
4358 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4359 .collect();
4360 for (i, data) in self.lanes.iter_mut().enumerate() {
4361 open_room(&mut data.clips, at, len);
4362 // The subtitle lanes are NOT touched: a paste inserts media, and
4363 // the words keep their own clock. Opening room here used to split
4364 // a caption the paste landed inside and slide the rest behind it
4365 // -- "a caption that stayed put while the picture moved on no
4366 // longer says the same thing" -- but a caption pinned to nothing
4367 // (and a video arriving on a timeline of words alone) has no
4368 // picture to follow, and the split did to the words what no hand
4369 // asked for. A caption that should travel with a clip is what a
4370 // group is for, and a group moves as one.
4371 if takes.contains(&i) {
4372 let idx = data.clips.partition_point(|c| c.start < at);
4373 data.clips.insert(idx, clip);
4374 }
4375 debug_assert!(sorted_disjoint(&data.clips));
4376 debug_assert!(subs_sorted_disjoint(&data.subs));
4377 }
4378 true
4379 }
4380
4381 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
4382 /// `items` lands on the lane it names, its head moved by the offset every
4383 /// other item moves by too -- `at` less the earliest `start` among them,
4384 /// so the set's own gaps and lane assignment survive the trip from
4385 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
4386 /// way a lone clip's copy does.
4387 ///
4388 /// All-or-nothing, and **refused** rather than opening room or splitting
4389 /// a neighbour the way [`paste`](Project::paste) does for one clip:
4390 /// a set-paste never ripples the bed, so a landing that overlaps so much
4391 /// as one existing clip on its own lane refuses the whole set, changing
4392 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
4393 /// clamps instead of refusing, but a paste has no drag to clamp against,
4394 /// and a landing moved off the frame asked for is not what a paste means.
4395 /// `items` empty, naming a lane or a source that is not there, or a clip
4396 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
4397 ///
4398 /// Exactly one history snapshot for the whole set, so one
4399 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
4400 /// on every lane an item lands on: the caller must reseek.
4401 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
4402 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
4403 return false;
4404 };
4405 // Resolved once, up front, off the lanes as they stand now: a lane or
4406 // source that is not there, or a landing that would overlap a
4407 // neighbour, refuses the whole set before any of it is written.
4408 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
4409 for &(lane, clip) in items {
4410 let Some(li) = self.index(lane) else {
4411 return false;
4412 };
4413 if self.sources.get(clip.source).is_none() || clip.out_frame <= clip.in_frame {
4414 return false;
4415 }
4416 let delta = i64::from(clip.start) - i64::from(anchor);
4417 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
4418 return false;
4419 };
4420 let Some(end) = start.checked_add(clip.frames()) else {
4421 return false;
4422 };
4423 if self.lanes[li]
4424 .clips
4425 .iter()
4426 .any(|c| c.start < end && start < c.end())
4427 {
4428 return false;
4429 }
4430 landings.push((li, Clip { start, ..clip }));
4431 }
4432 self.snapshot();
4433 for (li, mut clip) in landings {
4434 clip.link = Some(self.new_link());
4435 clip.fade_in = 0;
4436 clip.fade_out = 0;
4437 clip.transition_out = 0;
4438 let clips = &mut self.lanes[li].clips;
4439 let idx = clips.partition_point(|c| c.start < clip.start);
4440 clips.insert(idx, clip);
4441 }
4442 true
4443 }
4444
4445 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4446 /// silence, and nothing else moves. Refused only for an out-of-range index
4447 /// (which a lane that is not there always is) -- lifting the last placement
4448 /// there is leaves an *empty* timeline, which is a state the project holds
4449 /// like any other and an undo brings back.
4450 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4451 if idx >= self.lane(lane).len() {
4452 return false;
4453 }
4454 self.snapshot();
4455 self.lane_mut(lane).expect("checked above").remove(idx);
4456 true
4457 }
4458
4459 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4460 /// the hole: everything after slides back by `len`. The rippling delete --
4461 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4462 /// empty range; a delete that leaves nothing behind empties the timeline,
4463 /// which is a state like any other and one undo away.
4464 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4465 if len == 0 {
4466 return false;
4467 }
4468 // Nothing reaches past `at`: there is nothing to cut and nothing to
4469 // slide back, and a delete that changes nothing must not cost an undo
4470 // step (see [`snapshot`](Project::snapshot)).
4471 if !self
4472 .lanes
4473 .iter()
4474 .flat_map(|l| &l.clips)
4475 .any(|c| c.end() > at)
4476 {
4477 return false;
4478 }
4479 self.snapshot();
4480 let on = all_lanes(&self.lanes);
4481 ripple(&mut self.lanes, &on, at, len);
4482 true
4483 }
4484
4485 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
4486 /// a right-click on empty bench space names before offering to close it.
4487 /// `None` when `frame` sits inside a placement, or past the last one: the
4488 /// open end of a lane is not a gap, since there is nothing after it to slide
4489 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
4490 /// the media [`Clip`] list they deliberately never hold.
4491 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
4492 let data = self.index(lane).map(|i| &self.lanes[i])?;
4493 match data.kind {
4494 LaneKind::Subtitle => gap(&data.subs, frame),
4495 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
4496 }
4497 }
4498
4499 /// How many bounded holes `lane` holds. The open end after the last
4500 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
4501 /// it would move nothing.
4502 pub fn gap_count(&self, lane: Lane) -> usize {
4503 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
4504 return 0;
4505 };
4506 match data.kind {
4507 LaneKind::Subtitle => gaps(&data.subs).len(),
4508 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
4509 }
4510 }
4511
4512 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4513 /// together to keep sync -- what a right-click on empty bench space asks
4514 /// before the menu offers to close it, and what widens
4515 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
4516 /// named to the whole take the gap might be half of.
4517 ///
4518 /// A clip bordering the gap on `lane` -- the one ending where it starts,
4519 /// the one starting where it ends -- carries a link when it is one take
4520 /// with a clip on another lane. That lane joins the scope only when the
4521 /// *exact same* stretch is empty there too (same start, same length): the
4522 /// ripple then removes nothing but silence, on every lane it touches, and
4523 /// both halves stay the length they always were. A link whose partner
4524 /// lane is not empty there -- a gap of a different length, or none at all
4525 /// -- is named back to the caller rather than silently widened past
4526 /// (which would cut real media out of a lane nothing asked to touch) or
4527 /// silently left out (which is the defect this closes: a per-lane ripple
4528 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
4529 /// to refuse it after the fact, on the very half this could have carried
4530 /// along).
4531 ///
4532 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
4533 /// partner clip sits on another lane -- the unlinked case, untouched.
4534 ///
4535 /// Subtitle lanes have no media take halves to inspect. A caption can be
4536 /// hand-grouped with clips, but it is not the imported A/V take this method
4537 /// widens for, so a subtitle gap stays scoped to its own lane; the later
4538 /// scoped cut still refuses an explicit group split.
4539 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4540 let Some(li) = self.index(lane) else {
4541 return Err("no track to work on".into());
4542 };
4543 let labels = handles(&self.lanes);
4544 let end = start + frames;
4545 let mut scope = vec![lane];
4546 for c in self.lanes[li]
4547 .clips
4548 .iter()
4549 .filter(|c| c.end() == start || c.start == end)
4550 {
4551 let Some(id) = c.link else { continue };
4552 for (j, data) in self.lanes.iter().enumerate() {
4553 if j == li {
4554 continue;
4555 }
4556 let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else {
4557 continue;
4558 };
4559 match gap(&data.clips, start) {
4560 Some((s, f)) if s == start && f == frames => {
4561 let other = labels[j];
4562 if !scope.contains(&other) {
4563 scope.push(other);
4564 }
4565 }
4566 _ => {
4567 return Err(format!(
4568 "the {} clip at frame {} is one take with the {} clip at frame {}: \
4569 closing this gap alone would pull the take out of sync -- close {}'s \
4570 gap there too, or detach them first",
4571 labels[li].label(),
4572 c.start,
4573 labels[j].label(),
4574 half.start,
4575 labels[j].label()
4576 )
4577 .into());
4578 }
4579 }
4580 }
4581 }
4582 Ok(scope)
4583 }
4584
4585 /// Close every bounded gap on `lane`, as one undo step, without making the
4586 /// lane's scope global. Media lanes use the same take-safety widening
4587 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
4588 /// halves ride along only when their matching lane is empty over that exact
4589 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
4590 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
4591 /// halves of an imported A/V take, so the media take-widening rule has
4592 /// nothing to add there.
4593 ///
4594 /// The walk is back-to-front. Closing a gap shifts everything after it, so
4595 /// later holes must be consumed while their measured starts are still true;
4596 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
4597 /// only before the first successful close, so an all-skipped sweep is not an
4598 /// undo step.
4599 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4600 let Some(i) = self.index(lane) else {
4601 return Err("no track to work on".into());
4602 };
4603 if self.lanes[i].kind == LaneKind::Subtitle {
4604 return Ok(self.close_all_subtitle_gaps_on_lane(i));
4605 }
4606 let mut report = GapSweep::default();
4607 let mut snapshot = false;
4608 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
4609 match self
4610 .gap_take_scope(lane, start, frames)
4611 .and_then(|scope| {
4612 let on = self.scoped(&scope)?;
4613 self.scope_holds_takes_whole(&on, start)?;
4614 Ok(on)
4615 }) {
4616 Ok(on) => {
4617 if !snapshot {
4618 self.snapshot();
4619 snapshot = true;
4620 }
4621 ripple(&mut self.lanes, &on, start, frames);
4622 report.closed += 1;
4623 }
4624 Err(e) => report.skipped.push(GapSkip {
4625 start,
4626 reason: e.to_string(),
4627 }),
4628 }
4629 }
4630 report.skipped.reverse();
4631 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4632 Ok(report)
4633 }
4634
4635 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
4636 /// take-scope widening: a caption is not one half of an A/V take. Explicit
4637 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
4638 /// so a grouped caption is refused rather than pulled away from its group.
4639 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
4640 let mut report = GapSweep::default();
4641 let mut snapshot = false;
4642 let on = [i];
4643 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
4644 match self.scope_holds_takes_whole(&on, start) {
4645 Ok(()) => {
4646 if !snapshot {
4647 self.snapshot();
4648 snapshot = true;
4649 }
4650 ripple(&mut self.lanes, &on, start, frames);
4651 report.closed += 1;
4652 }
4653 Err(e) => report.skipped.push(GapSkip {
4654 start,
4655 reason: e.to_string(),
4656 }),
4657 }
4658 }
4659 report.skipped.reverse();
4660 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4661 report
4662 }
4663
4664 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4665 /// out of the lanes in `scope` and close each hole, as one edit: the
4666 /// jumpcut a silence scan asks for ([`crate::silence`]).
4667 ///
4668 /// A lane that is not in `scope` **does not move**, which is the whole
4669 /// point of the parameter: the silences of a podcast track come out
4670 /// without the music track under it sliding. `scope` is an arbitrary set of
4671 /// lanes and not a kind or a range, so a caller with its own idea of what
4672 /// is selected (a take, a track, everything) says it in lanes and nothing
4673 /// here has to learn about selection.
4674 ///
4675 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4676 /// reason this exists rather than a caller's loop over
4677 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4678 /// undo press, not forty. Cut back to front, so a region's frames still
4679 /// mean what the caller measured while the ones before it are cut.
4680 ///
4681 /// The list is sorted and overlapping entries are merged before anything is
4682 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4683 /// other's frames. Refused, with no undo step, for an empty list, for a
4684 /// scope naming no lane that is there, and -- by name -- when the scope
4685 /// would take one half of a take with it
4686 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4687 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4688 let regions = tidy(regions);
4689 let on = self.scoped(scope)?;
4690 let Some(&(first, _)) = regions.first() else {
4691 return Err("nothing to cut".into());
4692 };
4693 self.scope_holds_takes_whole(&on, first)?;
4694 self.snapshot();
4695 for &(at, len) in regions.iter().rev() {
4696 ripple(&mut self.lanes, &on, at, len);
4697 }
4698 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4699 Ok(())
4700 }
4701
4702 /// The storage indices of `scope`, which is what every batch below walks.
4703 /// `Err` for a scope that names nothing there rather than a silent no-op:
4704 /// an edit asked for on a lane that is not there did not happen, and the
4705 /// caller has to hear so.
4706 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4707 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4708 match on.is_empty() {
4709 true => Err("no track to work on".into()),
4710 false => Ok(on),
4711 }
4712 }
4713
4714 /// The law a scoped ripple lives under: **a group travels as one**, so a
4715 /// batch that moves one half of a take and not the other would leave the
4716 /// halves disagreeing about where they stand -- an offset no hand asked
4717 /// for, and the reason the take's lanes have to be scoped together.
4718 ///
4719 /// Refused by name rather than widened silently. Widening would edit a
4720 /// track the user did not scope, which is exactly the surprise scoping
4721 /// exists to end; a front-end that wants the take is free to *say* the
4722 /// take's lanes, and to name them in what it tells the user afterwards.
4723 ///
4724 /// Only from `from` on: a take sitting entirely before the first cut does
4725 /// not move, so it is not this rule's business.
4726 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4727 let labels = handles(&self.lanes);
4728 // The halves of a group are on either of a lane's lists, and the
4729 // refusal names whichever sits outside the scope -- a clip like it
4730 // always has, and a caption now that a group may hold one.
4731 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4732 let Some(id) = link else {
4733 return Ok(());
4734 };
4735 for (j, data) in self.lanes.iter().enumerate() {
4736 if on.contains(&j) {
4737 continue;
4738 }
4739 let clip = data.clips.iter().find(|o| o.link == Some(id));
4740 let sub = data.subs.iter().find(|s| s.link == Some(id));
4741 if let Some(half) = clip {
4742 return Err(format!(
4743 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4744 moving one track of a take would pull it apart -- take the whole take, \
4745 or detach them first",
4746 labels[j].label(),
4747 half.start
4748 )
4749 .into());
4750 }
4751 if let Some(half) = sub {
4752 return Err(format!(
4753 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4754 moving one track of a take would pull it apart -- take the whole take, \
4755 or detach them first",
4756 labels[j].label(),
4757 half.start
4758 )
4759 .into());
4760 }
4761 }
4762 Ok(())
4763 };
4764 for &i in on {
4765 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4766 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4767 }
4768 // A caption before the first cut does not move, so it is not this
4769 // rule's business -- exactly the clip test's own line.
4770 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4771 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4772 }
4773 }
4774 Ok(())
4775 }
4776
4777 /// Play every one of `regions` at `speed` instead of cutting it: each is
4778 /// split out of whatever covers it, re-rated, and the room it no longer
4779 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4780 /// does not ripple, and a hole where a silence shrank is the one thing this
4781 /// must not leave. One snapshot for the lot, like
4782 /// [`cut_regions`](Project::cut_regions).
4783 ///
4784 /// The rate is **absolute**, not a multiplier on what is there: running it
4785 /// twice over the same stretch leaves it at `speed`, not at `speed`
4786 /// squared, so a second pass over an already-cut timeline changes nothing.
4787 ///
4788 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4789 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4790 ///
4791 /// Refused by name, with nothing changed and no undo step, when:
4792 ///
4793 /// * the scope would take one half of a take with it
4794 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4795 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4796 /// shrink by different amounts and the ripple would pull them apart,
4797 /// which is what cutting does not suffer and why delete mode has no such
4798 /// refusal;
4799 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4800 /// piece could not be split out exactly;
4801 /// * two lanes' pieces would end up different lengths, which is a group
4802 /// whose halves disagree about their span (the refusal
4803 /// [`write_speed`](Project::write_speed) already makes, in its words);
4804 /// * the region would grow rather than shrink, i.e. it already plays faster
4805 /// than `speed`.
4806 pub fn speed_regions(
4807 &mut self,
4808 regions: &[(u32, u32)],
4809 speed: Speed,
4810 scope: &[Lane],
4811 ) -> crate::Result<()> {
4812 let regions = tidy(regions);
4813 let on = self.scoped(scope)?;
4814 let Some(&(first, _)) = regions.first() else {
4815 return Err("nothing to speed up".into());
4816 };
4817 self.scope_holds_takes_whole(&on, first)?;
4818 let labels = handles(&self.lanes);
4819 // Before anything is touched, because this is the refusal a person can
4820 // act on: a clip that laps over the edge of a silence has to be trimmed
4821 // (or the silences cut instead), and saying so after a rollback would
4822 // be saying it about a timeline that already looks different.
4823 for &(at, len) in &regions {
4824 for &l in &on {
4825 for c in &self.lanes[l].clips {
4826 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4827 {
4828 return Err(format!(
4829 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4830 speeding it up would pull the lanes apart -- trim it first, or cut the \
4831 silences out instead",
4832 labels[l].label(),
4833 c.start,
4834 at + len
4835 )
4836 .into());
4837 }
4838 }
4839 }
4840 }
4841 // The rest is checked as it is built: a split's own arithmetic is what
4842 // says whether a rate can address an edge. So the snapshot is taken
4843 // first and *rolled back* on a refusal -- one undo either way, and a
4844 // refusal still costs no step (`undo` pops the one just pushed).
4845 self.snapshot();
4846 for &(at, len) in regions.iter().rev() {
4847 self.write_split(at, false, &on);
4848 self.write_split(at + len, false, &on);
4849 let mut room: Option<(Lane, u32)> = None;
4850 let mut refused = None;
4851 for &l in &on {
4852 let clips = &self.lanes[l].clips;
4853 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4854 if (c.start, c.end()) != (at, at + len) {
4855 // *Which* edge did not come off: a rate that cannot
4856 // address the end of the silence is not a rate that
4857 // cannot address its start, and naming the wrong frame
4858 // sends the user looking in the wrong place.
4859 let edge = match c.start == at {
4860 true => at + len,
4861 false => at,
4862 };
4863 refused = Some(format!(
4864 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4865 detach it, or put it back to 1.00x first",
4866 labels[l].label(),
4867 c.start,
4868 c.speed
4869 ));
4870 continue;
4871 }
4872 let after = speed.frames(c.len());
4873 match room {
4874 None => room = Some((labels[l], after)),
4875 Some((first, n)) if n != after => {
4876 refused = Some(format!(
4877 "at {speed} the {} half of the silence at frame {at} would cover \
4878 {after} frames and the {} half {n}: they are one take and a take \
4879 is one span -- detach them first",
4880 labels[l].label(),
4881 first.label()
4882 ));
4883 }
4884 Some(_) => {}
4885 }
4886 }
4887 }
4888 let shrunk = match (refused, room) {
4889 (Some(e), _) => {
4890 self.undo();
4891 return Err(e.into());
4892 }
4893 // A gap on every lane: nothing to re-rate, and nothing to close.
4894 (None, None) => continue,
4895 (None, Some((_, after))) => after,
4896 };
4897 // The region's new length, on every scoped lane alike.
4898 let after = shrunk;
4899 let Some(delta) = len.checked_sub(shrunk) else {
4900 self.undo();
4901 return Err(format!(
4902 "the silence at frame {at} already plays faster than {speed}: \
4903 at that rate it would be {shrunk} frames instead of {len}"
4904 )
4905 .into());
4906 };
4907 for &l in &on {
4908 for c in &mut self.lanes[l].clips {
4909 if c.start == at && c.end() == at + len {
4910 c.speed = speed;
4911 } else if c.start >= at + len {
4912 c.start -= delta;
4913 }
4914 }
4915 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4916 // The captions on a scoped lane travel with the region's time:
4917 // a piece inside it plays in `after` frames instead of `len`
4918 // -- same words on less timeline, its window untouched, for
4919 // [`write_speed`]'s reason -- and everything behind the region
4920 // slides up by what the region gave back.
4921 //
4922 // The pieces inside re-time by their *boundaries*, not each
4923 // on its own: rounding one piece's start and its neighbour's
4924 // start apart can land both on the same frame (two one-frame
4925 // cues of a thirty-frame region at 2x both want frame 15), so
4926 // the mapped boundaries are walked in order and forced apart
4927 // -- each piece at least one frame, none past the region's own
4928 // new end, where the first follower lands exactly. A rounding
4929 // artifact is clamped, not refused: nothing about the words
4930 // asked for an overlap.
4931 let share = f64::from(after) / f64::from(len).max(1.);
4932 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4933 let mut prev = at;
4934 let subs = &mut self.lanes[l].subs;
4935 for i in 0..subs.len() {
4936 let s = subs[i];
4937 if s.start >= at + len {
4938 subs[i].start = s.start - delta;
4939 } else if s.start >= at && s.end() <= at + len {
4940 let mut start = map(s.start).max(prev);
4941 let end = map(s.end()).max(start + 1).min(at + after);
4942 start = start.min(end - 1);
4943 subs[i].start = start;
4944 subs[i].frames = end - start;
4945 prev = end;
4946 }
4947 }
4948 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4949 }
4950 }
4951 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4952 Ok(())
4953 }
4954
4955 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4956 /// -- the whole-group delete a single-lane front-end means. `false` for a
4957 /// bad index. Changes the mapping: the caller must reseek.
4958 pub fn delete(&mut self, idx: usize) -> bool {
4959 self.delete_in(Lane::V1, idx)
4960 }
4961
4962 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4963 /// in no group (or a group of one, which is the same thing to a delete) is
4964 /// what it always was: its own span cut out of *every* lane, so the
4965 /// timeline closes up under it. A clip in a group takes the group with it,
4966 /// each member by its **own** span and on its **own** lane -- the members
4967 /// keep their offsets, so their spans may disagree, and the lanes may end
4968 /// up out of step with each other, which is inherent to a hand-built group
4969 /// and one undo away. Every member -- clips and captions alike -- goes by
4970 /// the same law: its own span out of its own lane, hole closed; a caption
4971 /// in no group keeps the lift that leaves a gap, which is its own door's
4972 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4973 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4974 /// index, and for a lane that is not there. Changes the mapping: the
4975 /// caller must reseek.
4976 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4977 let Some(members) = self.group_of(lane, idx) else {
4978 return false;
4979 };
4980 if !members.alone() {
4981 return self.delete_members(&members);
4982 }
4983 let Some(clip) = self.lane(lane).get(idx).copied() else {
4984 return false;
4985 };
4986 self.ripple_delete(clip.start, clip.frames())
4987 }
4988
4989 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4990 /// caption in no group lifts, exactly as its own key always made it
4991 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4992 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4993 /// span out of its own lane, hole closed, captions and clips alike.
4994 /// `false` for a bad index.
4995 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4996 let Some(members) = self.group_of(lane, idx) else {
4997 return false;
4998 };
4999 if !members.alone() {
5000 return self.delete_members(&members);
5001 }
5002 self.lift_sub(lane, idx)
5003 }
5004
5005 /// The one whole-group delete both doors land in: every member's own span
5006 /// cut out of its own lane and the hole closed there -- clips and
5007 /// captions by the same law -- and nothing else on another lane moves,
5008 /// which is what keeps one member's ripple from dragging another
5009 /// member's lane out from under it. One snapshot, one undo step.
5010 fn delete_members(&mut self, members: &Members) -> bool {
5011 self.snapshot();
5012 for &(l, i) in &members.clips {
5013 let c = self.lanes[l].clips[i];
5014 ripple(&mut self.lanes, &[l], c.start, c.frames());
5015 }
5016 // The captions go by the same law their clip siblings do -- the span
5017 // out of its own lane, the hole closed -- and not by the lift a
5018 // *lone* caption's delete is: deleted with its group, the words after
5019 // it slide up with everything else, or the lane the group emptied is
5020 // the one lane the delete left a hole in. `ripple` is the one
5021 // mechanism (it clears the span and shifts the rest, clips and
5022 // captions alike); a sub lane holds no clips, so its other list is
5023 // untouched.
5024 for &(l, i) in &members.subs {
5025 let s = self.lanes[l].subs[i];
5026 ripple(&mut self.lanes, &[l], s.start, s.frames);
5027 }
5028 debug_assert!(links_are_consistent(&self.lanes).is_ok());
5029 true
5030 }
5031
5032 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
5033 #[cfg(test)]
5034 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
5035 self.lane(lane)
5036 }
5037
5038 /// How many undo steps are stacked: what the sweep asks so "one op, one
5039 /// snapshot" is a count and not a guess.
5040 #[cfg(test)]
5041 pub(crate) fn history_len(&self) -> usize {
5042 self.history.len()
5043 }
5044
5045 /// How many redo steps are stacked: what the sweep asks to check `undo`
5046 /// left a branch behind, and that a fresh edit clears it.
5047 #[cfg(test)]
5048 pub(crate) fn redo_len(&self) -> usize {
5049 self.redo.len()
5050 }
5051
5052 /// The project's own settings as they stand ([`ProjectSettings`]) -- what an
5053 /// undo entry holds beside the lanes, and what the session reads back after
5054 /// one is restored ([`crate::PlaybackSession::undo`]).
5055 pub(crate) fn settings_now(&self) -> ProjectSettings {
5056 self.settings.clone()
5057 }
5058
5059 /// One undo step for a change to the project's own settings: `from` is the
5060 /// state the change is from and `now` the one it leaves behind. The entry
5061 /// pushed holds `from`, while the copy kept here is `now` -- so the next
5062 /// lane edit's own entry carries the canvas and the rate really in force
5063 /// rather than the ones before the pick. The lanes the entry holds are the
5064 /// ones in place at the call: a settings door leaves them alone and may
5065 /// take this step after its change, and one that moves them
5066 /// ([`Project::retime`] on a rate change) takes it before, with `now` equal
5067 /// to `from`, mirroring the new state afterwards
5068 /// ([`Project::mirror_settings`]).
5069 pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) {
5070 self.settings = from;
5071 self.snapshot();
5072 self.settings = now;
5073 }
5074
5075 /// Keeps `now` as this project's copy of its own settings, without a step:
5076 /// the second half of a settings door that had to take its step before the
5077 /// change.
5078 pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) {
5079 self.settings = now;
5080 }
5081
5082 /// Every part of the project that an edit can change, as comparable
5083 /// values: what the sweep's undo round-trip asks "byte identical?" of.
5084 #[cfg(test)]
5085 pub(crate) fn parts(&self) -> SweepParts {
5086 SweepParts(
5087 self.sources.len(),
5088 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
5089 self.lanes.iter().map(|l| l.subs.clone()).collect(),
5090 self.subtitles.clone(),
5091 self.settings.clone(),
5092 )
5093 }
5094
5095 /// Restore everything from before the last successful edit -- the lanes,
5096 /// the subtitle palette and the project's own settings. `false` when there
5097 /// is nothing left to undo. Pushes what was just left onto the redo stack,
5098 /// so [`Project::redo`] can walk forward again.
5099 pub fn undo(&mut self) -> bool {
5100 match self.history.pop() {
5101 Some(prev) => {
5102 self.redo.push(Snapshot {
5103 lanes: std::mem::replace(&mut self.lanes, prev.lanes),
5104 subtitles: self.subtitles.clone(),
5105 settings: self.settings.clone(),
5106 });
5107 self.subtitles = prev.subtitles;
5108 self.settings = prev.settings;
5109 true
5110 }
5111 None => false,
5112 }
5113 }
5114
5115 /// Restore everything from before the last [`Project::undo`] -- the
5116 /// mirror of `undo`, walking the redo stack it fills. `false` when there
5117 /// is nothing left to redo, which is also true after any fresh edit: a
5118 /// new [`Project::snapshot`] clears the branch `undo` left behind.
5119 pub fn redo(&mut self) -> bool {
5120 match self.redo.pop() {
5121 Some(next) => {
5122 self.history.push(Snapshot {
5123 lanes: std::mem::replace(&mut self.lanes, next.lanes),
5124 subtitles: self.subtitles.clone(),
5125 settings: self.settings.clone(),
5126 });
5127 self.subtitles = next.subtitles;
5128 self.settings = next.settings;
5129 true
5130 }
5131 None => false,
5132 }
5133 }
5134
5135 /// The project an export renders from: everything a render reads, with the
5136 /// undo history left behind. An export never walks the history back, and
5137 /// cloning it costs a copy of every lane list in the session -- this is
5138 /// taken on the UI thread, so it clones the lanes and the sources alone.
5139 pub fn export_snapshot(&self) -> Self {
5140 Self {
5141 sources: self.sources.clone(),
5142 lanes: self.lanes.clone(),
5143 eq: self.eq.clone(),
5144 color: self.color.clone(),
5145 transform: self.transform.clone(),
5146 history: Vec::new(),
5147 redo: Vec::new(),
5148 next_link: self.next_link,
5149 subtitles: self.subtitles.clone(),
5150 settings: self.settings.clone(),
5151 }
5152 }
5153
5154 /// Half-open `(source, start, end)` segments in *source* seconds, from
5155 /// `timeline_frame` to the end of the timeline -- the play list for the
5156 /// audio worker, read off **`A1`**. A `None` source is a gap: the
5157 /// worker synthesises that many seconds of silence, which is what keeps the
5158 /// audio master clock counting across a hole instead of stalling on it.
5159 /// The first entry is partial when the position is mid-clip. Empty when the
5160 /// position is past the end or `fps` is not usable.
5161 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
5162 self.lane_segments_from(Lane::A1, timeline_frame, fps)
5163 }
5164
5165 /// [`segments_from`](Project::segments_from) for a named lane.
5166 pub fn lane_segments_from(
5167 &self,
5168 lane: Lane,
5169 timeline_frame: u32,
5170 fps: f64,
5171 ) -> Vec<(Option<usize>, f64, f64)> {
5172 if !(fps.is_finite() && fps > 0.0) {
5173 return Vec::new();
5174 }
5175 self.spans_from(lane, timeline_frame)
5176 .iter()
5177 .map(|span| match span.from {
5178 // A clip's window is in *source* seconds: where in the file it
5179 // reads from, which a delete before it never shifts. How many
5180 // source frames that is, is the span's own arithmetic -- at a
5181 // speed it is not the timeline length ([`Span::source_len`]).
5182 Some((source, in_frame)) => (
5183 Some(source),
5184 f64::from(in_frame) / fps,
5185 f64::from(in_frame + span.source_len()) / fps,
5186 ),
5187 // A gap has no file, so all it can say is how long it is.
5188 None => (None, 0.0, f64::from(span.len) / fps),
5189 })
5190 .collect()
5191 }
5192
5193 /// One play list per audio lane that *holds* something, in display order --
5194 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
5195 /// what an export asks how many lanes it would have to mix.
5196 ///
5197 /// Never empty: a timeline whose audio lanes are all empty (or which has no
5198 /// audio lane at all) still yields one all-gap list, so it plays silence
5199 /// against a master clock exactly as it did before there were lanes to
5200 /// count. Lanes with nothing on them are left out rather than mixed in as
5201 /// silence: they would cost a decode thread each and add zero.
5202 pub fn audio_segments_from(
5203 &self,
5204 timeline_frame: u32,
5205 fps: f64,
5206 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
5207 self.audio_lanes()
5208 .into_iter()
5209 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
5210 .collect()
5211 }
5212
5213 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
5214 /// builds a play list for, in the same order. Public because everything
5215 /// asked per audio lane -- which clip a segment's equalizer belongs to,
5216 /// which lane an mp4 export would copy -- has to read the very list the
5217 /// sound comes off, or the two answers drift apart (which is exactly how an
5218 /// `A2`-only project once exported silently, ledger).
5219 pub fn audio_lanes(&self) -> Vec<Lane> {
5220 let lanes: Vec<Lane> = self
5221 .lanes()
5222 .into_iter()
5223 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
5224 .collect();
5225 match lanes.is_empty() {
5226 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
5227 // no sound still plays silence against the master clock.
5228 true => vec![Lane::A1],
5229 false => lanes,
5230 }
5231 }
5232
5233 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
5234 /// segments plays at, and how long the timeline gives it: the same lanes in
5235 /// the same order, one entry per segment, `None` for a segment at real time
5236 /// -- which is every segment of a project nobody has speeded, and the path
5237 /// the audio worker leaves bit-identical.
5238 ///
5239 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
5240 /// the segment tuple is what every opener and a dozen tests speak, and a
5241 /// rate is not part of *which samples* a segment names.
5242 ///
5243 /// The seconds are what makes a resample exact: a segment's own window
5244 /// resolves to whole source frames, and dividing that by the rate would
5245 /// leave each clip a fraction of a frame short or long -- a drift that grows
5246 /// clip by clip. Told how much timeline it owes, the worker pads or trims
5247 /// the last few samples of each segment instead, so the sound stays locked
5248 /// to the picture however many speeded cuts it walks through.
5249 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
5250 self.audio_lanes()
5251 .into_iter()
5252 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
5253 .collect()
5254 }
5255
5256 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
5257 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5258 /// same walk, same `fps` refusal.
5259 pub fn lane_speeds_from(
5260 &self,
5261 lane: Lane,
5262 timeline_frame: u32,
5263 fps: f64,
5264 ) -> Vec<Option<Stretch>> {
5265 if !(fps.is_finite() && fps > 0.0) {
5266 return Vec::new();
5267 }
5268 self.spans_from(lane, timeline_frame)
5269 .iter()
5270 .map(|span| {
5271 (!span.speed.is_normal()).then(|| Stretch {
5272 step: span.speed.as_f64(),
5273 timeline_secs: f64::from(span.len) / fps,
5274 })
5275 })
5276 .collect()
5277 }
5278
5279 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
5280 /// segments plays through: the same lanes in the same order, one entry per
5281 /// segment, `None` where the segment is a gap or its clip plays flat.
5282 ///
5283 /// A parallel list rather than a fourth element of the segment tuple: that
5284 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
5285 /// and an effect is not part of *which samples* a segment names. A short
5286 /// list therefore means "flat from here on" rather than a length mismatch --
5287 /// see [`crate::AudioSession::open_mixed_streams_eq`].
5288 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
5289 self.audio_lanes()
5290 .into_iter()
5291 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
5292 .collect()
5293 }
5294
5295 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
5296 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5297 /// same walk, same `fps` refusal, so the two lists cannot come out different
5298 /// lengths.
5299 pub fn lane_eqs_from(
5300 &self,
5301 lane: Lane,
5302 timeline_frame: u32,
5303 fps: f64,
5304 ) -> Vec<Option<EqParams>> {
5305 if !(fps.is_finite() && fps > 0.0) {
5306 return Vec::new();
5307 }
5308 self.spans_from(lane, timeline_frame)
5309 .iter()
5310 // A span off a clip covers that clip's frames and no others, so its
5311 // own start names the clip -- the index a [`Span`] does not carry.
5312 .map(|span| {
5313 self.map(lane, span.start)
5314 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
5315 })
5316 .collect()
5317 }
5318
5319 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
5320 /// segments plays through: the same lanes in the same order, one entry per
5321 /// segment, `None` where the segment is a gap or its clip has neither a
5322 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
5323 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
5324 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
5325 self.audio_lanes()
5326 .into_iter()
5327 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
5328 .collect()
5329 }
5330
5331 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
5332 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
5333 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
5334 if !(fps.is_finite() && fps > 0.0) {
5335 return Vec::new();
5336 }
5337 self.spans_from(lane, timeline_frame)
5338 .iter()
5339 .map(|span| {
5340 let (idx, _) = self.map(lane, span.start)?;
5341 let clip = self.lane(lane).get(idx)?;
5342 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
5343 // `span.len` is the clip's own remaining frames from
5344 // `span.start` on -- shorter than `clip.frames()` only
5345 // when this is the first span of a seek mid-clip.
5346 elapsed: clip.frames().saturating_sub(span.len),
5347 fade_in: clip.fade_in,
5348 fade_out: clip.fade_out,
5349 total: clip.frames(),
5350 })
5351 })
5352 .collect()
5353 }
5354
5355 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
5356 /// it has decided it will succeed -- a refusal must not cost an undo step.
5357 /// Clears the redo stack: a fresh edit branches off from here, so whatever
5358 /// `undo` had left to redo is no longer where this edit leads back to.
5359 fn snapshot(&mut self) {
5360 if self.history.len() == HISTORY_CAP {
5361 self.history.remove(0);
5362 }
5363 self.history.push(Snapshot {
5364 lanes: self.lanes.clone(),
5365 subtitles: self.subtitles.clone(),
5366 settings: self.settings.clone(),
5367 });
5368 self.redo.clear();
5369 }
5370
5371 fn new_link(&mut self) -> u32 {
5372 let id = self.next_link;
5373 self.next_link = self.next_link.saturating_add(1);
5374 id
5375 }
5376
5377}
5378
5379/// The handle of every lane, in storage order -- the one definition of what
5380/// [`Lane::ord`] counts.
5381fn handles(lanes: &[LaneData]) -> Vec<Lane> {
5382 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
5383 lanes
5384 .iter()
5385 .map(|l| match l.kind {
5386 LaneKind::Video => {
5387 video += 1;
5388 Lane::new(LaneKind::Video, video - 1)
5389 }
5390 LaneKind::Audio => {
5391 audio += 1;
5392 Lane::new(LaneKind::Audio, audio - 1)
5393 }
5394 LaneKind::Subtitle => {
5395 subtitle += 1;
5396 Lane::new(LaneKind::Subtitle, subtitle - 1)
5397 }
5398 })
5399 .collect()
5400}
5401
5402/// The one law a caption re-time scales by: frame `f` moves about the held
5403/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
5404/// commits it, [`Project::speeded_playhead`] previews it -- both build their
5405/// [`TimelineMap`] piece from this single answer so the two cannot drift
5406/// apart by a frame the way they once did.
5407fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
5408 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
5409 .round()
5410 .clamp(0., f64::from(u32::MAX)) as u32
5411}
5412
5413/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
5414/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
5415/// a speed cannot be applied twice or forgotten in one of them.
5416fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
5417 // Clamped inside the clip's own range: rounding at a slow rate can put the
5418 // last timeline frame of a clip a frame past its out-point, and a source
5419 // frame outside the range is one the next clip owns.
5420 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
5421}
5422
5423/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
5424/// finder generic makes the subtitle path use the same bounded-hole rules as
5425/// media lanes without teaching the media-specific take logic about captions.
5426trait GapPlacement {
5427 fn start_frame(&self) -> u32;
5428 fn end_frame(&self) -> u32;
5429}
5430
5431impl GapPlacement for Clip {
5432 fn start_frame(&self) -> u32 {
5433 self.start
5434 }
5435
5436 fn end_frame(&self) -> u32 {
5437 self.end()
5438 }
5439}
5440
5441impl GapPlacement for SubClip {
5442 fn start_frame(&self) -> u32 {
5443 self.start
5444 }
5445
5446 fn end_frame(&self) -> u32 {
5447 self.end()
5448 }
5449}
5450
5451/// Index of the placement covering `frame`, or `None` for a gap or past the
5452/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
5453fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
5454 let idx = items.partition_point(|item| item.start_frame() <= frame).checked_sub(1)?;
5455 (frame < items[idx].end_frame()).then_some(idx)
5456}
5457
5458/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
5459/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
5460/// invariant like [`at`]: the first placement whose start is past `frame` is
5461/// the far wall, and the last one that ends at or before `frame` (or the
5462/// timeline's own head, `0`, when there is none) is the near one.
5463fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
5464 if at(items, frame).is_some() {
5465 return None;
5466 }
5467 let idx = items.partition_point(|item| item.start_frame() <= frame);
5468 let next = items.get(idx)?;
5469 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
5470 Some((start, next.start_frame() - start))
5471}
5472
5473/// Every bounded hole in `items`, left to right. The tail after the last
5474/// placement is deliberately absent: there is no later placement for a ripple
5475/// to bring back.
5476fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
5477 let mut out = Vec::new();
5478 let mut next = 0;
5479 for item in items {
5480 if item.start_frame() > next {
5481 out.push((next, item.start_frame() - next));
5482 }
5483 next = item.end_frame();
5484 }
5485 out
5486}
5487
5488/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
5489/// there would cut in two. A placement's own first frame is not inside it.
5490fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
5491 let idx = at(clips, frame)?;
5492 // ...and, on a speeded clip, one its rate can actually address
5493 // ([`Speed::split_at`]): a cut between two showings of one source frame
5494 // would leave halves that no longer add up to the clip that was cut.
5495 (frame > clips[idx].start)
5496 .then_some(idx)
5497 .filter(|&idx| split_source(&clips[idx], frame).is_some())
5498}
5499
5500/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
5501/// rate cannot address that frame.
5502fn split_source(c: &Clip, frame: u32) -> Option<u32> {
5503 c.speed
5504 .split_at(c.len(), frame - c.start)
5505 .map(|src| c.in_frame + src)
5506}
5507
5508/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
5509/// rejoin: they must touch there, and be consecutive frames of one source.
5510fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
5511 let idx = clips.iter().position(|c| c.end() == frame)?;
5512 let next = clips.get(idx + 1)?;
5513 let joined = clips[idx].len() + next.len();
5514 (next.start == frame
5515 && next.source == clips[idx].source
5516 && next.in_frame == clips[idx].out_frame
5517 // ...at one rate, and one that puts the rejoined clip back in exactly
5518 // the room the two took up: what a split could have produced, which is
5519 // all this undoes.
5520 && next.speed == clips[idx].speed
5521 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
5522 .then_some(idx)
5523}
5524
5525/// The lane invariant: sorted by `start`, no two placements overlapping, no
5526/// empty placement. Checked at every constructor and asserted after every
5527/// mutation -- the offset model is only tractable while it holds.
5528/// The one thing an equalizer setting may not be: a value the text format
5529/// cannot write and read back as itself. Checked wherever params come in, so
5530/// what an edit produces is always what a save writes and a load reads.
5531fn finite(params: &EqParams) -> bool {
5532 params
5533 .bands
5534 .iter()
5535 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
5536}
5537
5538/// The same for a colour grade: [`crate::color`] itself falls back to identity
5539/// on a non-finite value, but a value that cannot be written and read back as
5540/// itself has no business reaching the model.
5541fn color_finite(p: &ColorParams) -> bool {
5542 p.brightness.is_finite()
5543 && p.contrast.is_finite()
5544 && p.saturation.is_finite()
5545 && p.tint.is_finite()
5546}
5547
5548/// The same for a transform: [`crate::scale`] clamps a non-finite value to
5549/// identity at read time, but a value that cannot round-trip has no business
5550/// reaching the model.
5551fn transform_finite(p: &TransformParams) -> bool {
5552 p.pos_x.is_finite()
5553 && p.pos_y.is_finite()
5554 && p.scale.is_finite()
5555 && p.rotate.is_finite()
5556 && p.crop_l.is_finite()
5557 && p.crop_r.is_finite()
5558 && p.crop_t.is_finite()
5559 && p.crop_b.is_finite()
5560}
5561
5562fn sorted_disjoint(clips: &[Clip]) -> bool {
5563 clips.iter().all(|c| c.out_frame > c.in_frame)
5564 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
5565}
5566
5567/// The very same invariant on a subtitle lane, in that lane's own two units:
5568/// sorted by `start`, no two placements overlapping, no empty placement at
5569/// either end. Asserted after every mutation, exactly as its twin is.
5570fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
5571 subs.iter()
5572 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
5573 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
5574}
5575
5576/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
5577/// the one conversion between a lane's clock and a cue's, and `0` for a rate
5578/// that is not one (every caller of this has already refused such a rate).
5579fn us_of(frames: i64, fps: f64) -> i64 {
5580 match fps.is_finite() && fps > 0.0 {
5581 true => ((frames as f64) / fps * 1e6).round() as i64,
5582 false => 0,
5583 }
5584}
5585
5586/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5587/// dropping what is inside the hole, splitting what straddles it and trimming
5588/// what overlaps an edge. The windows follow the cut by proportion
5589/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5590fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5591 let mut out = Vec::with_capacity(subs.len() + 1);
5592 for s in subs.drain(..) {
5593 if s.end() <= start || s.start >= end {
5594 out.push(s);
5595 continue;
5596 }
5597 if s.start < start {
5598 out.push(SubClip {
5599 frames: start - s.start,
5600 out_us: s.window_at(start),
5601 // Both pieces lose the group id, for [`clear`]'s reason: one
5602 // id on two boxes of one lane is the one thing it may never
5603 // mean.
5604 link: None,
5605 ..s
5606 });
5607 }
5608 if s.end() > end {
5609 out.push(SubClip {
5610 start: end,
5611 frames: s.end() - end,
5612 in_us: s.window_at(end),
5613 link: None,
5614 ..s
5615 });
5616 }
5617 }
5618 *subs = out;
5619}
5620
5621/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5622/// `len`, splitting a placement that straddles `at` so the two halves end up on
5623/// either side of the hole. A `len` of 0 is that split alone, which is what a
5624/// [`Project::split`] over a subtitle lane is.
5625fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5626 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5627 let s = subs[idx];
5628 let cut = s.window_at(at);
5629 subs[idx] = SubClip {
5630 frames: at - s.start,
5631 out_us: cut,
5632 link: None,
5633 ..s
5634 };
5635 subs.insert(
5636 idx + 1,
5637 SubClip {
5638 start: at,
5639 frames: s.end() - at,
5640 in_us: cut,
5641 link: None,
5642 ..s
5643 },
5644 );
5645 }
5646 for s in subs.iter_mut().filter(|s| s.start >= at) {
5647 s.start += len;
5648 }
5649}
5650
5651/// [`joinable`] for a subtitle lane: the first of the two placements a
5652/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5653/// produced and nothing else -- they touch on the timeline, they read the same
5654/// track, and the second one's window carries on where the first's stopped.
5655fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5656 let idx = subs.iter().position(|s| s.end() == frame)?;
5657 let next = subs.get(idx + 1)?;
5658 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5659 .then_some(idx)
5660}
5661
5662/// How far one `edge` of the caption at `idx` may travel against its own lane's
5663/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5664/// rate, which a caption *following* a group's trim does not have to be exact
5665/// about -- its own walls, its own one surviving frame, and nothing that needs
5666/// a clock.
5667fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5668 let s = &subs[idx];
5669 match edge {
5670 Edge::Start => (
5671 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5672 s.end() - 1,
5673 ),
5674 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5675 }
5676}
5677
5678/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5679/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5680/// forwards and backwards. The caption a group's trim is carrying has no rate
5681/// of its own and needs none: what one frame of it is worth in microseconds is
5682/// the window it already shows over the frames it already takes.
5683fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5684 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5685 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5686 match edge {
5687 Edge::Start => {
5688 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5689 s.frames = s.end() - to;
5690 s.start = to;
5691 }
5692 Edge::End => {
5693 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5694 s.frames = to - s.start;
5695 }
5696 }
5697 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5698}
5699
5700/// The grouping invariant, checked in release at [`Project::from_parts`] and
5701/// asserted by the tests after every edit: a link id names **at most one**
5702/// placement per lane -- a clip on a media lane or a caption on a subtitle
5703/// one, whichever carries it. That is all "these move together" can mean now
5704/// that a group is assembled by hand: the members keep their own spans and
5705/// their own offsets, and what binds them is the id alone.
5706///
5707/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5708/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5709/// placements of one group may cover different frames -- the offset-preserving
5710/// group a hand builds with [`Project::group_all`], which a drag moves by one
5711/// delta rather than by one span.
5712///
5713/// A link no other lane carries is legal and is not an error: lifting one half
5714/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5715/// timeline has to load again.
5716/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5717/// asked by the sweep suite's universal law.
5718#[cfg(test)]
5719pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5720 links_are_consistent(&p.lanes)
5721}
5722
5723fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5724 let handles = handles(lanes);
5725 for (data, lane) in lanes.iter().zip(&handles) {
5726 for (i, c) in data.clips.iter().enumerate() {
5727 let Some(id) = c.link else { continue };
5728 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5729 return Err(
5730 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5731 );
5732 }
5733 }
5734 // ...and the same for the captions, in their own list on the same lane:
5735 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5736 // id could be doubled on.
5737 for (i, s) in data.subs.iter().enumerate() {
5738 let Some(id) = s.link else { continue };
5739 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5740 return Err(format!(
5741 "link {id} names two captions in the {} lane",
5742 lane.label()
5743 )
5744 .into());
5745 }
5746 }
5747 }
5748 Ok(())
5749}
5750
5751/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5752/// it go, one straddling it is split in two, one overlapping an edge is
5753/// trimmed. Source frames follow the trim, so what is left plays what it always
5754/// played. Leaves the lane sorted and disjoint.
5755///
5756/// A piece the hole cut is no longer the take its group id names -- and both
5757/// halves of a straddled placement carrying that id would be the same id twice
5758/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5759fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5760 let mut out = Vec::with_capacity(clips.len() + 1);
5761 for c in clips.drain(..) {
5762 // Disjoint from the hole: untouched.
5763 if c.end() <= start || c.start >= end {
5764 out.push(c);
5765 continue;
5766 }
5767 // The head that survives in front of the hole -- as much source as fits
5768 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5769 // which at real time is that room itself. Never *more*: a head that
5770 // outgrew its room would reach into the hole it is being cut out of,
5771 // which is exactly the overlap a slow clip punched at a frame its rate
5772 // cannot address used to leave (at 0.25x a single source frame is four
5773 // timeline frames, and three frames of room hold none of it). `None`
5774 // there means no remainder at all, and the piece simply goes.
5775 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5776 && c.start < start
5777 {
5778 out.push(Clip {
5779 fade_in: 0,
5780 fade_out: 0,
5781 transition_out: 0,
5782 out_frame: c.in_frame + keep.min(c.len()),
5783 link: None,
5784 ..c
5785 });
5786 }
5787 // ...and the tail behind it, which keeps reading up to where it would
5788 // have: measured from its out-point for the head's reason, so what it
5789 // occupies still ends where the whole clip did -- and dropped whole on
5790 // the same `None`.
5791 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5792 && c.end() > end
5793 {
5794 out.push(Clip {
5795 fade_in: 0,
5796 fade_out: 0,
5797 transition_out: 0,
5798 start: end,
5799 in_frame: c.out_frame - keep.min(c.len()),
5800 link: None,
5801 ..c
5802 });
5803 }
5804 }
5805 *clips = out;
5806}
5807
5808/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5809/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5810/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5811/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5812/// the caller.
5813fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5814 for &i in on {
5815 let clips = &mut lanes[i].clips;
5816 clear(clips, at, at + len);
5817 for c in clips.iter_mut().filter(|c| c.start >= at) {
5818 c.start -= len;
5819 }
5820 debug_assert!(sorted_disjoint(clips));
5821 // The subtitle lanes close the hole with everything else: a caption
5822 // left standing where the picture it belongs to was cut out is the
5823 // desync a lane model exists to make impossible.
5824 let subs = &mut lanes[i].subs;
5825 sub_clear(subs, at, at + len);
5826 for s in subs.iter_mut().filter(|s| s.start >= at) {
5827 s.start -= len;
5828 }
5829 debug_assert!(subs_sorted_disjoint(subs));
5830 }
5831}
5832
5833/// Every lane, as the index list the two above take: what "the whole timeline"
5834/// is spelled as, and the scope [`Project::ripple_delete`] and
5835/// [`Project::split`] have always had.
5836fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5837 (0..lanes.len()).collect()
5838}
5839
5840/// A caller's region list as a batch may use it: sorted by start, empty entries
5841/// dropped, and touching or overlapping entries merged into one.
5842///
5843/// Overlapping regions are the one thing a batch cannot take -- cutting the
5844/// second would cut frames the first already moved -- and a detector handing
5845/// back two that touch means one silence, not two cuts. Merged rather than
5846/// refused: this is arithmetic on a preview, not a user's mistake.
5847fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5848 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5849 sorted.sort_by_key(|&(at, _)| at);
5850 let mut out: Vec<(u32, u32)> = Vec::new();
5851 for (at, len) in sorted {
5852 let end = at.saturating_add(len);
5853 match out.last_mut() {
5854 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5855 _ => out.push((at, len)),
5856 }
5857 }
5858 out
5859}
5860
5861/// Slides everything from `at` on later by `len`, splitting a placement that
5862/// straddles `at` so the two halves end up on either side of the hole. The
5863/// insert half of a rippling paste. The two halves lose the group id for the
5864/// reason [`clear`] gives.
5865fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5866 if let Some(idx) = splittable(clips, at) {
5867 let mut tail = clips[idx];
5868 // The cut in *source* frames, at the clip's own rate. `splittable` has
5869 // already refused a frame the rate cannot address, which is why
5870 // [`Project::paste`] refuses one too rather than opening room inside a
5871 // clip that cannot be cut there.
5872 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5873 tail.start = at;
5874 tail.link = None;
5875 clips[idx].out_frame = tail.in_frame;
5876 clips[idx].link = None;
5877 clips.insert(idx + 1, tail);
5878 }
5879 for c in clips.iter_mut().filter(|c| c.start >= at) {
5880 c.start += len;
5881 }
5882}
5883
5884/// Absolute, symlink-resolved when the file is reachable; the path as given
5885/// when it is not -- an unreadable path still deserves an index, it simply
5886/// dedups by spelling.
5887pub(crate) fn canonical(path: &Path) -> PathBuf {
5888 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5889}
5890
5891#[cfg(test)]
5892mod tests {
5893 use super::*;
5894
5895 const FPS: f64 = 30.0;
5896 /// Never opened -- `Project` is pure data, so a path that does not exist is
5897 /// simply a path that dedups by spelling.
5898 const FILE: &str = "/nonexistent/a.mp4";
5899 const FILE2: &str = "/nonexistent/b.mp4";
5900
5901 /// A contiguous placement, group id ignored: what most assertions compare.
5902 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5903 Clip {
5904 fade_in: 0,
5905 fade_out: 0,
5906 transition_out: 0,
5907 visualizer: 0,
5908 viz_paint: 0,
5909 start,
5910 in_frame,
5911 out_frame,
5912 source,
5913 link: None,
5914 eq: None,
5915 color: None,
5916 transform: None,
5917 fit: FitPolicy::default(),
5918 speed: Speed::NORMAL,
5919 }
5920 }
5921
5922 /// A caption placement for pure timeline tests: the track window is the
5923 /// same duration as the placement, so assertions can stay in frames.
5924 fn caption(start: u32, frames: u32) -> SubClip {
5925 SubClip {
5926 start,
5927 frames,
5928 track: 0,
5929 in_us: 0,
5930 out_us: i64::from(frames) * 1_000_000,
5931 link: None,
5932 }
5933 }
5934
5935 /// A subtitle palette row for tests that place captions on lanes.
5936 fn subtitle_track() -> SubtitleTrack {
5937 SubtitleTrack {
5938 path: FILE.into(),
5939 track: None,
5940 language: "eng".into(),
5941 name: String::new(),
5942 label: "eng".into(),
5943 cues: Vec::new(),
5944 bitmap: false,
5945 refused: None,
5946 }
5947 }
5948
5949 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5950 /// apart -- which is what makes the table's dedup and its prune visible.
5951 fn band_at(n: u32) -> EqParams {
5952 EqParams {
5953 bands: vec![crate::eq::Band {
5954 freq_hz: 1000.0,
5955 gain_db: f64::from(n) as f32 * 1.5,
5956 q: 0.707,
5957 kind: crate::eq::BandKind::Peak,
5958 }],
5959 }
5960 }
5961
5962 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5963 /// for the colour table.
5964 fn grade_at(n: u32) -> ColorParams {
5965 ColorParams {
5966 brightness: f64::from(n) as f32 * 0.05,
5967 ..Default::default()
5968 }
5969 }
5970
5971 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5972 /// twin for the transform table.
5973 fn transform_at(n: u32) -> TransformParams {
5974 TransformParams {
5975 pos_x: f64::from(n) as f32 * 0.05,
5976 ..Default::default()
5977 }
5978 }
5979
5980 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5981 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5982 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5983 }
5984
5985 /// Every lane with its group ids blanked, for comparing shape.
5986 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5987 p.lanes()
5988 .into_iter()
5989 .map(|l| {
5990 p.lane(l)
5991 .iter()
5992 .map(|c| Clip { link: None, ..*c })
5993 .collect()
5994 })
5995 .collect()
5996 }
5997
5998 /// The *source frame* every timeline frame reads, per lane -- the traversal
5999 /// a player performs. Deliberately not the clip index: a split changes which
6000 /// clip a frame belongs to, and nothing else.
6001 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
6002 (0..p.timeline_frames() + 2)
6003 .map(|f| {
6004 p.lanes()
6005 .into_iter()
6006 .map(|l| p.map(l, f).map(|(_, source)| source))
6007 .collect()
6008 })
6009 .collect()
6010 }
6011
6012 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
6013 /// fixture. Built through `split` so the constructor path is exercised too.
6014 fn three() -> Project {
6015 let mut p = Project::single(FILE, 9);
6016 assert!(p.split(3));
6017 assert!(p.split(5));
6018 assert_eq!(
6019 shape(&p),
6020 [
6021 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
6022 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
6023 ]
6024 );
6025 p
6026 }
6027
6028 #[test]
6029 fn single_is_the_whole_file_on_both_lanes() {
6030 let p = Project::single(FILE, 150);
6031 assert_eq!(p.clips().len(), 1);
6032 assert_eq!(p.lane(Lane::A1).len(), 1);
6033 assert_eq!(p.timeline_frames(), 150);
6034 assert_eq!(p.clip_spans(), vec![(0, 150)]);
6035 // grouped: video and audio carry the same link
6036 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
6037 assert!(p.clips()[0].link.is_some());
6038 // degenerate mapping: timeline == source
6039 assert_eq!(p.map_timeline(0), Some((0, 0)));
6040 assert_eq!(p.map_timeline(149), Some((0, 149)));
6041 assert_eq!(p.map_timeline(150), None);
6042 // never-empty invariant survives a bogus frame count
6043 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
6044 }
6045
6046 #[test]
6047 fn split_cuts_every_lane_and_regroups_it_back() {
6048 let mut p = Project::single(FILE, 9);
6049 let before = traversal(&p);
6050 let before_shape = shape(&p);
6051
6052 assert!(p.split(4));
6053 for l in p.lanes() {
6054 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
6055 }
6056 // The two sides are two groups, one per side, matching across the lanes.
6057 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
6058 assert_eq!(v[0].link, a[0].link);
6059 assert_eq!(v[1].link, a[1].link);
6060 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
6061 // A split changes no mapping, in either lane.
6062 assert_eq!(traversal(&p), before, "a split moves nothing");
6063
6064 assert!(p.regroup(4), "the inverse rejoins them");
6065 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
6066 assert_eq!(traversal(&p), before);
6067 assert_eq!(
6068 p.lane(Lane::V1)[0].link,
6069 p.lane(Lane::A1)[0].link,
6070 "and the rejoined clip is one group again"
6071 );
6072 }
6073
6074 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
6075 /// the very first frame of a fade-in, unity at its last, equal-power
6076 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
6077 /// at all.
6078 #[test]
6079 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
6080 let f = Fade {
6081 elapsed: 0,
6082 fade_in: 10,
6083 fade_out: 10,
6084 total: 40,
6085 };
6086 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
6087 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
6088 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
6089 assert!(
6090 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
6091 "equal-power midpoint is sin(pi/4)"
6092 );
6093 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
6094 // The fade-out is the same curve, mirrored, counting down from the
6095 // clip's end: unity at the frame the ramp starts, the same
6096 // equal-power midpoint, and -- since `total` itself is one past the
6097 // clip's last valid frame -- the very last frame is one step short of
6098 // the silence a fade-in's own frame `0` lands on exactly.
6099 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
6100 assert!(
6101 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
6102 "the fade-out's own equal-power midpoint"
6103 );
6104 assert!(
6105 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
6106 "one step short of silence at the clip's last playable frame"
6107 );
6108 }
6109
6110 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
6111 /// not adjacent, and otherwise sets the shared edge's fades and nothing
6112 /// else.
6113 #[test]
6114 fn crossfade_only_joins_adjacent_audio_clips() {
6115 let mut p = Project::single(FILE, 20);
6116 assert!(p.split(10));
6117 assert!(
6118 !p.crossfade(Lane::V1, 0, 5),
6119 "video is not an audio lane"
6120 );
6121 assert!(
6122 !p.crossfade(Lane::A1, 1, 5),
6123 "there is no clip after idx 1"
6124 );
6125 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
6126 let a = p.lane(Lane::A1);
6127 assert_eq!(a[0].fade_out, 5);
6128 assert_eq!(a[1].fade_in, 5);
6129 assert_eq!(a[0].fade_in, 0);
6130 assert_eq!(a[1].fade_out, 0);
6131
6132 // A gap between two clips is not adjacency, even on an audio lane.
6133 let mut p2 = Project::single(FILE, 1);
6134 let a2 = p2.add_lane(LaneKind::Audio);
6135 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
6136 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
6137 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
6138 }
6139
6140 /// The rule [`Project::write_split`] follows for the edge the razor makes:
6141 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
6142 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
6143 /// mirror image.
6144 #[test]
6145 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
6146 let mut p = Project::single(FILE, 20);
6147 assert!(p.set_fade_in(Lane::V1, 0, 15));
6148 assert!(p.set_fade_out(Lane::V1, 0, 15));
6149 assert!(p.split(5));
6150 let v = p.lane(Lane::V1);
6151 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
6152 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
6153 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
6154 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
6155 }
6156
6157 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
6158 /// no successor, and two clips that do not touch, and otherwise clamps
6159 /// the dissolve to the shorter of the two clips it spans.
6160 #[test]
6161 fn set_transition_out_only_dissolves_adjacent_video_clips() {
6162 let mut p = Project::single(FILE, 20);
6163 assert!(p.split(15), "a short 5-frame tail to clamp against");
6164 assert!(
6165 !p.set_transition_out(Lane::A1, 0, 5),
6166 "audio is not a video lane"
6167 );
6168 assert!(
6169 !p.set_transition_out(Lane::V1, 1, 5),
6170 "there is no clip after idx 1"
6171 );
6172 assert!(
6173 p.set_transition_out(Lane::V1, 0, 100),
6174 "the two halves are adjacent"
6175 );
6176 assert_eq!(
6177 p.transition_out_of(Lane::V1, 0),
6178 5,
6179 "clamped to the shorter neighbour's 5 frames"
6180 );
6181
6182 // A gap between two clips is not adjacency, even on the video lane.
6183 let mut p2 = Project::single(FILE, 1);
6184 let v2 = p2.add_lane(LaneKind::Video);
6185 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
6186 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
6187 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
6188 }
6189
6190 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
6191 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
6192 /// only the half that kept the clip's original *end* keeps the dissolve,
6193 /// re-clamped to its own now-shorter length; the head the cut just made
6194 /// has no successor to dissolve into and starts flat.
6195 #[test]
6196 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
6197 let mut p = Project::single(FILE, 20);
6198 assert!(
6199 !p.set_transition_out(Lane::V1, 0, 0),
6200 "one clip on the lane, no successor to dissolve into yet"
6201 );
6202 // Give the clip a dissolve by hand, then cut it in two.
6203 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
6204 assert!(p.split(5));
6205 let v = p.lane(Lane::V1);
6206 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
6207 assert_eq!(
6208 v[1].transition_out, 15,
6209 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
6210 );
6211 }
6212
6213 /// The music video's own path: the take comes apart into halves that carry
6214 /// ids of their own, one undo puts it back, and two clips over the same
6215 /// frames become one take again by hand.
6216 #[test]
6217 fn a_take_comes_apart_and_goes_back_together() {
6218 let mut p = Project::single(FILE, 9);
6219 let one = p.clips()[0].link.expect("a fresh project is one take");
6220 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
6221
6222 // A third lane in the same group -- and the merge case with it: a
6223 // placement is in no group, and grouping it in leaves *one* group.
6224 let v2 = p.add_lane(LaneKind::Video);
6225 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6226 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
6227 p.group(Lane::V1, 0, v2, 0)
6228 .expect("the same frames, one lane over");
6229 let id = p.clips()[0].link.expect("still a group");
6230 assert!(
6231 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6232 "one id over the three, not two groups sharing a span"
6233 );
6234 links_are_consistent(&p.lanes).expect("one id, one span");
6235
6236 // Detached by the sound: every half of the group, not only the two.
6237 assert!(p.ungroup(Lane::A1, 0));
6238 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
6239 assert!(
6240 ids.iter().all(Option::is_some),
6241 "a half keeps an id of its own"
6242 );
6243 assert!(
6244 ids.iter()
6245 .enumerate()
6246 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
6247 "and no two halves are the same group any more: {ids:?}"
6248 );
6249 links_are_consistent(&p.lanes).expect("a lone id is legal");
6250
6251 // One snapshot for the whole detach.
6252 assert!(p.undo());
6253 assert!(
6254 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6255 "one undo puts the whole group back"
6256 );
6257
6258 // And back together by hand: the two the pointer named, and only them.
6259 assert!(p.ungroup(Lane::V1, 0));
6260 p.group(Lane::V1, 0, Lane::A1, 0)
6261 .expect("both cover [0, 9)");
6262 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
6263 assert_ne!(
6264 p.lane(v2)[0].link,
6265 p.lane(Lane::V1)[0].link,
6266 "the third half stayed detached"
6267 );
6268 links_are_consistent(&p.lanes).expect("one id, one span");
6269 }
6270
6271 /// What a group may not be, and what a detach has nothing to take apart --
6272 /// none of which may cost an undo step.
6273 #[test]
6274 fn a_group_is_one_span_and_one_clip_per_lane() {
6275 let mut p = three();
6276 let before = shape(&p);
6277 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
6278
6279 assert!(
6280 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
6281 "two clips of one lane are never one take"
6282 );
6283 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
6284 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
6285 assert!(
6286 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
6287 "{spans}"
6288 );
6289 assert!(
6290 spans.contains("trim them to matching bounds first"),
6291 "{spans}"
6292 );
6293 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
6294
6295 // A half nothing else is grouped with is already detached, a placement
6296 // is in no group at all, and an index that is not there has nothing to
6297 // detach either.
6298 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
6299 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
6300 assert!(p.lift(Lane::A1, 0));
6301 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
6302 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
6303
6304 // Two undos, one per edit: not one of the refusals pushed a snapshot.
6305 assert!(p.undo());
6306 assert!(p.undo());
6307 assert_eq!(shape(&p), before);
6308 }
6309
6310 /// Where a re-rate puts a playhead: the scene under the cursor stays the
6311 /// scene under the cursor, measured the way a viewer would -- the source
6312 /// frame playing at the playhead is the same frame after the write, at
6313 /// every playhead position the re-rate can catch one.
6314 #[test]
6315 fn a_re_rate_keeps_the_frame_under_the_playhead() {
6316 let caption = |start: u32, frames: u32| SubClip {
6317 start,
6318 frames,
6319 track: 0,
6320 in_us: 0,
6321 out_us: i64::from(frames) * 1_000_000,
6322 link: None,
6323 };
6324 let track = || SubtitleTrack {
6325 path: FILE.into(),
6326 track: None,
6327 language: "eng".into(),
6328 name: String::new(),
6329 label: "eng".into(),
6330 cues: Vec::new(),
6331 bitmap: false,
6332 refused: None,
6333 };
6334 // A group of a 300-frame clip and a caption offset 30 frames into it.
6335 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
6336 let s1 = p.add_lane(LaneKind::Subtitle);
6337 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
6338 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6339
6340 // The frame playing at `at`: which clip, and which source frame of it.
6341 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
6342 p.span_at(Lane::V1, at)
6343 .and_then(|s| s.from.map(|(source, from)| (source, from)))
6344 };
6345
6346 // Inside the held clip: the source frame under the playhead is the
6347 // same one after the re-rate, at 2x and at half speed both.
6348 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
6349 let at = 120;
6350 let before = playing(&p, at).expect("a clip under the playhead");
6351 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
6352 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
6353 .expect("room for it");
6354 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
6355 assert_eq!(before, after, "{what}: the same source frame plays");
6356 // ...and the write itself is untouched by the question.
6357 assert!(p.undo(), "{what}: one step back");
6358 }
6359
6360 // Past the group -- the clip ends at 300 and the caption at 270, so
6361 // from 300 on nothing is re-timed under the playhead: unmoved.
6362 for at in [300u32, 301, 1_000] {
6363 assert_eq!(
6364 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
6365 Some(at),
6366 "at {at}: outside every member, unmoved"
6367 );
6368 }
6369 // The boundary is exact: the held clip's own last frame (299) maps
6370 // to its new one (149 -- the last frame inside [0, 150), where the
6371 // shrunken clip's last source frame plays), and its first stays put.
6372 assert_eq!(
6373 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
6374 Some(149)
6375 );
6376 assert_eq!(
6377 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
6378 Some(0)
6379 );
6380 // A spot the caption shares with the clip maps by the clip (it is
6381 // what is *playing* there): the held clip's own proportion, which on
6382 // this fixture is also its head.
6383 assert_eq!(
6384 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
6385 Some(45),
6386 "the clip under the caption owns the spot"
6387 );
6388 }
6389
6390 /// A playhead inside another clip member of the group: that member keeps
6391 /// its own head, so the mapping is by its proportion and not the held
6392 /// clip's -- and the frame under the cursor is still the frame that was.
6393 #[test]
6394 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
6395 let mut p = Project::single(FILE, 300);
6396 // A second clip, grouped with the first but starting 300 later: the
6397 // head the group shares and its own differ by exactly that.
6398 let v2 = p.add_lane(LaneKind::Video);
6399 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
6400 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
6401 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
6402
6403 let at = 450; // inside the second member, 150 past its head
6404 let before = p.span_at(v2, at).and_then(|s| s.from);
6405 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
6406 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6407 .expect("room for it");
6408 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
6409 assert_eq!(before, after, "the second member's own frame plays");
6410 // ...and the mapping itself: 150 past its head halves, the head stays.
6411 assert_eq!(mapped, Some(375));
6412 }
6413
6414 /// The link counter a load seeds sits past every id the file names,
6415 /// captions included: a hand-grouped caption may carry the highest id there
6416 /// is, and a counter that read the clips alone would hand it to the next
6417 /// group that asked -- silently grouping the caption with clips it never
6418 /// met.
6419 #[test]
6420 fn the_link_counter_sits_past_a_caption_only_id() {
6421 let track = || SubtitleTrack {
6422 path: FILE.into(),
6423 track: None,
6424 language: "eng".into(),
6425 name: String::new(),
6426 label: "eng".into(),
6427 cues: Vec::new(),
6428 bitmap: false,
6429 refused: None,
6430 };
6431 let mut p = Project::single(FILE, 9);
6432 p.add_lane(LaneKind::Subtitle);
6433 let caption = SubClip {
6434 start: 0,
6435 frames: 6,
6436 track: 0,
6437 in_us: 0,
6438 out_us: 6_000_000,
6439 // The highest id in the file, and only a caption carries it.
6440 link: Some(1),
6441 };
6442 let mut p = p
6443 .with_subtitles(vec![track()])
6444 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
6445 .expect("a caption may carry the file's highest id");
6446
6447 // A new group on lanes the caption is not on mints the next id -- which
6448 // must not be the caption's.
6449 let v2 = p.add_lane(LaneKind::Video);
6450 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6451 p.group_all(&[(Lane::V1, 0), (v2, 0)])
6452 .expect("the clips group");
6453 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
6454 assert_ne!(
6455 minted,
6456 1,
6457 "the caption's id is not re-issued to clips"
6458 );
6459 assert_eq!(
6460 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
6461 Some(1),
6462 "the caption keeps its own group"
6463 );
6464 assert!(links_are_consistent(&p.lanes).is_ok());
6465 }
6466
6467 /// A rate re-times the caption members of the group by the ratio it gives
6468 /// the held clip: the span on the timeline compresses about the held clip's
6469 /// head, the words' own window untouched -- and one undo puts it back.
6470 #[test]
6471 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
6472 let caption = |start: u32, frames: u32| SubClip {
6473 start,
6474 frames,
6475 track: 0,
6476 in_us: 0,
6477 out_us: i64::from(frames) * 1_000_000,
6478 link: None,
6479 };
6480 let track = || SubtitleTrack {
6481 path: FILE.into(),
6482 track: None,
6483 language: "eng".into(),
6484 name: String::new(),
6485 label: "eng".into(),
6486 cues: Vec::new(),
6487 bitmap: false,
6488 refused: None,
6489 };
6490 let grouped = || {
6491 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6492 let s1 = p.add_lane(LaneKind::Subtitle);
6493 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6494 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6495 (p, s1)
6496 };
6497
6498 // An aligned take, doubled: the caption plays in half the frames.
6499 let (mut p, s1) = grouped();
6500 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6501 .expect("room for it");
6502 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
6503 let s = p.sub_lane(s1)[0];
6504 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
6505 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
6506 assert!(links_are_consistent(&p.lanes).is_ok());
6507 assert!(p.undo());
6508 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
6509
6510 // An offset group, slowed to half: the caption's *offset from the held
6511 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
6512 // 0.5x, and still ends where the clip does.
6513 let (mut p, s1) = grouped();
6514 p.lift_sub(s1, 0);
6515 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
6516 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6517 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
6518 .expect("room for it");
6519 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
6520 let s = p.sub_lane(s1)[0];
6521 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
6522 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
6523
6524 // A stretch that runs the caption into its neighbour is refused, by
6525 // lane and frame, and costs no undo step.
6526 let (mut p, s1) = grouped();
6527 p.lift_sub(s1, 0);
6528 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6529 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
6530 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6531 let history = p.history.len();
6532 let err = p
6533 .set_speed(Lane::V1, 0, Speed::from_permille(500))
6534 .unwrap_err()
6535 .to_string();
6536 assert!(
6537 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
6538 "{err}"
6539 );
6540 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
6541 }
6542
6543 /// The silence scan's speed-up re-times the captions on a scoped lane with
6544 /// everything else: the piece inside the region plays in the region's new
6545 /// frames, and what sits behind the region slides up with the clips.
6546 #[test]
6547 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
6548 let caption = |start: u32, frames: u32| SubClip {
6549 start,
6550 frames,
6551 track: 0,
6552 in_us: 0,
6553 out_us: i64::from(frames) * 1_000_000,
6554 link: None,
6555 };
6556 let track = || SubtitleTrack {
6557 path: FILE.into(),
6558 track: None,
6559 language: "eng".into(),
6560 name: String::new(),
6561 label: "eng".into(),
6562 cues: Vec::new(),
6563 bitmap: false,
6564 refused: None,
6565 };
6566 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6567 let s1 = p.add_lane(LaneKind::Subtitle);
6568 // Words over the region [30, 60) and words behind it.
6569 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6570 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
6571
6572 // The region [30, 60) plays at 4x: 30 frames become 8, everything
6573 // behind slides up 22.
6574 // The scope is what the card's Take row says, caption lane included.
6575 p.speed_regions(
6576 &[(30, 30)],
6577 Speed::from_permille(4000),
6578 &[Lane::V1, Lane::A1, s1],
6579 )
6580 .expect("the region speeds up");
6581 let subs = p.sub_lane(s1);
6582 assert_eq!(
6583 (subs[0].start, subs[0].frames),
6584 (30, 8),
6585 "the piece inside plays in the region's new frames"
6586 );
6587 assert_eq!(
6588 (subs[1].start, subs[1].frames),
6589 (38, 30),
6590 "the piece behind slides up by what the region gave back"
6591 );
6592 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
6593 }
6594
6595 /// [`Project::speeded_playhead`]'s caption arm fires only when the
6596 /// playhead is inside a caption member and outside every clip member --
6597 /// a shape every other fixture avoids by keeping its caption inside the
6598 /// held clip. Here the caption overhangs the clip's tail, and the
6599 /// playhead standing in that overhang is answered by the caption's own
6600 /// piece: it scales about the held clip's head by the held clip's own
6601 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
6602 #[test]
6603 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
6604 let caption = |start: u32, frames: u32| SubClip {
6605 start,
6606 frames,
6607 track: 0,
6608 in_us: 0,
6609 out_us: i64::from(frames) * 1_000_000,
6610 link: None,
6611 };
6612 let track = || SubtitleTrack {
6613 path: FILE.into(),
6614 track: None,
6615 language: "eng".into(),
6616 name: String::new(),
6617 label: "eng".into(),
6618 cues: Vec::new(),
6619 bitmap: false,
6620 refused: None,
6621 };
6622 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6623 let s1 = p.add_lane(LaneKind::Subtitle);
6624 // The caption spans [80, 100) -- ten frames past the clip's own end
6625 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6626 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6627 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6628 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6629 // no clip member's old span reaches, is the caption's own question:
6630 // half of 95 is 47.5, rounded to 48.
6631 assert_eq!(
6632 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6633 Some(48),
6634 "the overhang frame answers through the caption's own piece"
6635 );
6636 }
6637
6638 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6639 /// map ([`map`]'s architecture law): a caption's landed span comes from
6640 /// the map's own ends, and the playhead standing at the caption's own
6641 /// last frame before the write has to land exactly where the write put
6642 /// it -- across clip lengths and rates that round differently, and an
6643 /// odd-length caption straddling the clip's own tail edge, the corner
6644 /// where `write_speed` used to answer a frame short.
6645 #[test]
6646 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6647 let caption = |start: u32, frames: u32| SubClip {
6648 start,
6649 frames,
6650 track: 0,
6651 in_us: 0,
6652 out_us: i64::from(frames) * 1_000_000,
6653 link: None,
6654 };
6655 let track = || SubtitleTrack {
6656 path: FILE.into(),
6657 track: None,
6658 language: "eng".into(),
6659 name: String::new(),
6660 label: "eng".into(),
6661 cues: Vec::new(),
6662 bitmap: false,
6663 refused: None,
6664 };
6665 for &len in &[90u32, 91, 177, 300, 301] {
6666 for &permille in &[500u16, 2000, 2500, 3000] {
6667 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6668 let s1 = p.add_lane(LaneKind::Subtitle);
6669 // An odd-length caption straddling the clip's tail edge: its
6670 // own last frame lands past the held clip.
6671 let c_start = len.saturating_sub(3);
6672 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6673 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6674 let speed = Speed::from_permille(permille);
6675 let last = c_start + 7 - 1;
6676 let mapped = p
6677 .speeded_playhead(Lane::V1, 0, speed, last)
6678 .expect("the caption is there");
6679 if p.set_speed(Lane::V1, 0, speed).is_err() {
6680 continue; // a refusal changes nothing: not this law's cell
6681 }
6682 let landed = p.sub_lane(s1)[0];
6683 if permille >= 1000 {
6684 // A speed-up compresses the timeline: many old frames
6685 // share one new frame, so the caption's own last old
6686 // frame lands flush with the write's own boundary --
6687 // the exact law [`write_speed`]'s worked drift-fix case
6688 // is stated against.
6689 assert_eq!(
6690 mapped,
6691 landed.end() - 1,
6692 "len {len} permille {permille}: the playhead at the caption's own \
6693 last frame lands where the write actually put it"
6694 );
6695 } else {
6696 // A slow-down expands it: one old frame becomes several
6697 // new ones, and `apply` answers where that frame's own
6698 // block *starts*, not where the caption's last new
6699 // frame (the end of that same block) sits -- a
6700 // one-frame gap inherent to the piece's own semantics,
6701 // not a drift between the two callers. Both still have
6702 // to agree the answer sits inside the caption the write
6703 // actually landed.
6704 assert!(
6705 (landed.start..landed.end()).contains(&mapped),
6706 "len {len} permille {permille}: the playhead lands inside the \
6707 caption the write actually put ({landed:?}), got {mapped}"
6708 );
6709 }
6710 }
6711 }
6712 }
6713
6714 /// A grouped caption's cues re-time with its clip: the placement's window
6715 /// crossed the timeline at its own proportion before any rate, and a
6716 /// re-rate changes that proportion (the frames compress, the window does
6717 /// not). A cue eight seconds into a window played at 2x crosses the screen
6718 /// four seconds in -- and at unity every cue lands exactly where it always
6719 /// did, byte for byte.
6720 #[test]
6721 fn a_grouped_captions_cues_re_time_with_its_clip() {
6722 let track = SubtitleTrack {
6723 path: FILE.into(),
6724 track: None,
6725 language: "eng".into(),
6726 name: String::new(),
6727 label: "eng".into(),
6728 cues: vec![crate::subtitle::Cue {
6729 start_us: 8_000_000,
6730 end_us: 9_000_000,
6731 text: "late line".into(),
6732 image: None,
6733 }],
6734 bitmap: false,
6735 refused: None,
6736 };
6737 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6738 let s1 = p.add_lane(LaneKind::Subtitle);
6739 // Ten seconds of the track over ten seconds of timeline: unity.
6740 p.place_sub(
6741 s1,
6742 0,
6743 SubClip {
6744 start: 0,
6745 frames: 300,
6746 track: 0,
6747 in_us: 0,
6748 out_us: 10_000_000,
6749 link: None,
6750 },
6751 )
6752 .expect("placed");
6753
6754 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6755 let unity = p.sub_lane_cues(s1, FPS);
6756 assert_eq!(
6757 unity
6758 .iter()
6759 .map(|c| (c.start_us, c.end_us, &*c.text))
6760 .collect::<Vec<_>>(),
6761 [(8_000_000, 9_000_000, "late line")],
6762 "a unity placement maps exactly as it always did"
6763 );
6764
6765 // Grouped with the clip and re-rated to 2x: the same window now crosses
6766 // in half the time, so the cue at 8s of it lands 4s in.
6767 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6768 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6769 .expect("room for it");
6770 let re_timed = p.sub_lane_cues(s1, FPS);
6771 assert_eq!(
6772 re_timed
6773 .iter()
6774 .map(|c| (c.start_us, c.end_us))
6775 .collect::<Vec<_>>(),
6776 [(4_000_000, 4_500_000)],
6777 "the cue crosses with the clip's new rate"
6778 );
6779 }
6780
6781 /// A video arriving on a timeline of words mutates none of them: the
6782 /// import's rippling insert used to open room on the subtitle lanes too,
6783 /// splitting a caption it landed inside and sliding the rest behind the
6784 /// video -- the hand asked for an add, and got a cut it never made. The
6785 /// words keep their own clock; co-travel is what a group is for.
6786 #[test]
6787 fn an_arriving_clip_never_touches_the_captions() {
6788 let caption = |start: u32, frames: u32| SubClip {
6789 start,
6790 frames,
6791 track: 0,
6792 in_us: i64::from(start) * 1_000_000 / 30,
6793 out_us: i64::from(start + frames) * 1_000_000 / 30,
6794 link: None,
6795 };
6796 let track = || SubtitleTrack {
6797 path: FILE.into(),
6798 track: None,
6799 language: "eng".into(),
6800 name: String::new(),
6801 label: "eng".into(),
6802 cues: Vec::new(),
6803 bitmap: false,
6804 refused: None,
6805 };
6806 // A timeline of words alone: 60 frames of caption, no media clips.
6807 let mut p = Project::single(FILE, 60)
6808 .with_subtitles(vec![track()]);
6809 for l in [Lane::V1, Lane::A1] {
6810 while !p.lane(l).is_empty() {
6811 p.lift(l, 0);
6812 }
6813 }
6814 let s1 = p.add_lane(LaneKind::Subtitle);
6815 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6816 let before = p.sub_lane(s1).to_vec();
6817
6818 // The video lands BEFORE the caption's span: nothing moves.
6819 let vid = clip(0, 0, 30, 0);
6820 assert!(p.paste(0, vid), "the video goes down at the head");
6821 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6822
6823 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6824 // byte the placement the hand made.
6825 assert!(p.paste(15, vid), "a second video lands inside the caption");
6826 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6827 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6828 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6829 assert!(links_are_consistent(&p.lanes).is_ok());
6830 }
6831
6832 /// The region's caption pieces re-time by mapped boundaries forced apart:
6833 /// rounding start and length independently can land two cues on one frame,
6834 /// and the artifact is clamped -- one frame each, in order, none past the
6835 /// region's new end -- never an overlap on the lane.
6836 #[test]
6837 fn a_regions_caption_pieces_never_round_onto_one_another() {
6838 let caption = |start: u32, frames: u32| SubClip {
6839 start,
6840 frames,
6841 track: 0,
6842 in_us: 0,
6843 out_us: i64::from(frames) * 1_000_000,
6844 link: None,
6845 };
6846 let track = |n| SubtitleTrack {
6847 path: FILE.into(),
6848 track: None,
6849 language: "eng".into(),
6850 name: String::new(),
6851 label: format!("eng{n}"),
6852 cues: Vec::new(),
6853 bitmap: false,
6854 refused: None,
6855 };
6856 // Three lanes, one repro shape each: adjacent one-frame cues, a
6857 // three-frame pair, and the region's last cue against the first
6858 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6859 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6860 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6861 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6862 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6863 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6864 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6865 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6866 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6867
6868 let mut scope = vec![Lane::V1, Lane::A1];
6869 scope.extend(lanes.iter().copied());
6870 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6871 .expect("the region speeds up");
6872 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6873 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6874 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6875 };
6876 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6877 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6878 // and the walk pushes the second to where the first ends.
6879 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6880 // The last cue of the region ends exactly where the region now does
6881 // (frame 15), and the caption behind it lands on that same frame:
6882 // touching, never overlapping.
6883 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6884 for &lane in &lanes {
6885 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6886 }
6887 }
6888
6889 /// The scope law names a caption half too: a scoped cut that would move one
6890 // track of a group whose caption sits outside the scope is refused.
6891 #[test]
6892 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6893 let caption = |start: u32, frames: u32| SubClip {
6894 start,
6895 frames,
6896 track: 0,
6897 in_us: 0,
6898 out_us: i64::from(frames) * 1_000_000,
6899 link: None,
6900 };
6901 let track = || SubtitleTrack {
6902 path: FILE.into(),
6903 track: None,
6904 language: "eng".into(),
6905 name: String::new(),
6906 label: "eng".into(),
6907 cues: Vec::new(),
6908 bitmap: false,
6909 refused: None,
6910 };
6911 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6912 let s1 = p.add_lane(LaneKind::Subtitle);
6913 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6914 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6915
6916 // The subtitle lane is not in the scope, so the group's caption half
6917 // sits outside it: refused, in the law's own words.
6918 let err = p
6919 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6920 .unwrap_err()
6921 .to_string();
6922 assert!(
6923 err.contains("is one take with the S1 caption at frame 0"),
6924 "{err}"
6925 );
6926
6927 // ...and with the caption's lane in the scope, the cut carries it:
6928 // the words over the hole go, and the words behind slide up.
6929 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6930 .expect("the whole group is in the scope");
6931 let subs = p.sub_lane(s1);
6932 assert_eq!(
6933 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6934 [(0, 10), (10, 75)],
6935 "the caption is cut and shifted with the clips"
6936 );
6937 }
6938
6939 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6940 /// mates riding along, the offsets kept, the refusals in words.
6941 #[test]
6942 fn a_hand_built_group_holds_clips_and_a_caption() {
6943 let caption = |start: u32, frames: u32| SubClip {
6944 start,
6945 frames,
6946 track: 0,
6947 in_us: 0,
6948 out_us: i64::from(frames) * 1_000_000,
6949 link: None,
6950 };
6951 let track = || SubtitleTrack {
6952 path: FILE.into(),
6953 track: None,
6954 language: "eng".into(),
6955 name: String::new(),
6956 label: "eng".into(),
6957 cues: Vec::new(),
6958 bitmap: false,
6959 refused: None,
6960 };
6961 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6962 let v2 = p.add_lane(LaneKind::Video);
6963 let s1 = p.add_lane(LaneKind::Subtitle);
6964 // A layer at its own offset, and a caption over the head of the take.
6965 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6966 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6967
6968 // Too few, one lane twice, and an index that is not there: words, no
6969 // snapshot.
6970 let history = p.history.len();
6971 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6972 assert!(p
6973 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6974 .unwrap_err()
6975 .to_string()
6976 .contains("V1 is picked twice"));
6977 assert!(p
6978 .group_all(&[(Lane::V1, 0), (s1, 9)])
6979 .unwrap_err()
6980 .to_string()
6981 .contains("no subtitle 9"));
6982 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6983
6984 // The group: the picture, the layer, and the caption -- and the sound
6985 // the picture was already grouped with comes along unasked.
6986 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6987 .expect("three picks, three lanes");
6988 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6989 for lane in [Lane::V1, Lane::A1, v2] {
6990 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6991 }
6992 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6993 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6994 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6995 assert!(links_are_consistent(&p.lanes).is_ok());
6996 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6997
6998 // ...and one undo takes it apart again.
6999 assert!(p.undo());
7000 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
7001
7002 // Detach names a caption like it names a clip: every member an id of
7003 // its own, which is never `None` (see `ungroup`).
7004 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
7005 assert!(p.ungroup(s1, 0));
7006 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
7007 assert!(loose_sub.is_some() && loose_clip.is_some());
7008 assert_ne!(loose_sub, loose_clip);
7009 assert!(links_are_consistent(&p.lanes).is_ok());
7010 }
7011
7012 /// Two captions on one sub lane, each already grouped with a *different*
7013 /// clip: `group_all` over both those clips would merge the two existing
7014 /// groups into one id and leave both captions on `s1` carrying it --
7015 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
7016 /// group closes. Refused by name, and nothing moves.
7017 #[test]
7018 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
7019 let caption = |start: u32, frames: u32| SubClip {
7020 start,
7021 frames,
7022 track: 0,
7023 in_us: 0,
7024 out_us: i64::from(frames) * 1_000_000,
7025 link: None,
7026 };
7027 let track = || SubtitleTrack {
7028 path: FILE.into(),
7029 track: None,
7030 language: "eng".into(),
7031 name: String::new(),
7032 label: "eng".into(),
7033 cues: Vec::new(),
7034 bitmap: false,
7035 refused: None,
7036 };
7037 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7038 let v2 = p.add_lane(LaneKind::Video);
7039 let s1 = p.add_lane(LaneKind::Subtitle);
7040 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
7041 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
7042 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
7043 // V1 grouped with the first caption, v2 with the second -- two
7044 // separate groups, each already one member per lane.
7045 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7046 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
7047 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
7048
7049 let history = p.history.len();
7050 let err = p
7051 .group_all(&[(Lane::V1, 0), (v2, 0)])
7052 .unwrap_err()
7053 .to_string();
7054 assert!(err.contains("one placement per lane"), "{err}");
7055 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
7056 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
7057 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
7058 assert!(links_are_consistent(&p.lanes).is_ok());
7059 }
7060
7061 /// A split hands the caption of a group the same ids it hands the clips:
7062 /// the left halves keep the group, the right halves share a fresh one.
7063 #[test]
7064 fn a_split_cuts_a_grouped_caption_with_its_clips() {
7065 let caption = |start: u32, frames: u32| SubClip {
7066 start,
7067 frames,
7068 track: 0,
7069 in_us: 0,
7070 out_us: i64::from(frames) * 1_000_000,
7071 link: None,
7072 };
7073 let track = || SubtitleTrack {
7074 path: FILE.into(),
7075 track: None,
7076 language: "eng".into(),
7077 name: String::new(),
7078 label: "eng".into(),
7079 cues: Vec::new(),
7080 bitmap: false,
7081 refused: None,
7082 };
7083 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7084 let s1 = p.add_lane(LaneKind::Subtitle);
7085 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
7086 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7087 let take = p.lane(Lane::V1)[0].link.expect("the group id");
7088
7089 assert!(p.split(4));
7090 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
7091 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
7092 assert_eq!(left.frames, 4);
7093 assert_eq!(
7094 right.link,
7095 p.lane(Lane::V1)[1].link,
7096 "the caption's tail shares the clips' fresh id"
7097 );
7098 assert_ne!(right.link, Some(take));
7099 assert!(links_are_consistent(&p.lanes).is_ok());
7100
7101 // Regroup at the seam restores the take, caption included.
7102 assert!(p.regroup(4));
7103 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
7104 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
7105 }
7106
7107 /// Deleting a member of a hand-built group takes the group: every
7108 /// member's own span out of its own lane, hole closed -- the lanes may
7109 /// end up out of step, which is what one undo restores together.
7110 #[test]
7111 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
7112 let caption = |start: u32, frames: u32| SubClip {
7113 start,
7114 frames,
7115 track: 0,
7116 in_us: 0,
7117 out_us: i64::from(frames) * 1_000_000,
7118 link: None,
7119 };
7120 let track = || SubtitleTrack {
7121 path: FILE.into(),
7122 track: None,
7123 language: "eng".into(),
7124 name: String::new(),
7125 label: "eng".into(),
7126 cues: Vec::new(),
7127 bitmap: false,
7128 refused: None,
7129 };
7130 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7131 let s1 = p.add_lane(LaneKind::Subtitle);
7132 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7133 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7134 // A neighbour on a lane the group does not touch.
7135 let v2 = p.add_lane(LaneKind::Video);
7136 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
7137
7138 // By the picture or by the caption, the same whole-group delete.
7139 assert!(p.delete_sub_in(s1, 0));
7140 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
7141 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
7142 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
7143 assert!(links_are_consistent(&p.lanes).is_ok());
7144 assert!(p.undo(), "one step puts the group back");
7145 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
7146 }
7147
7148 /// The delete law, one statement for every anchor: a caption deleted
7149 /// WITH its group ripples its lane exactly as its clip siblings do --
7150 /// the hole closes and what follows slides up -- while a caption lifted
7151 /// alone leaves its gap, as it always has. And the delete of a grouped
7152 /// clip takes the group from whichever member was clicked.
7153 #[test]
7154 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
7155 let caption = |start: u32, frames: u32| SubClip {
7156 start,
7157 frames,
7158 track: 0,
7159 in_us: 0,
7160 out_us: i64::from(frames) * 1_000_000,
7161 link: None,
7162 };
7163 let track = || SubtitleTrack {
7164 path: FILE.into(),
7165 track: None,
7166 language: "eng".into(),
7167 name: String::new(),
7168 label: "eng".into(),
7169 cues: Vec::new(),
7170 bitmap: false,
7171 refused: None,
7172 };
7173 // V+A+S grouped, with a second caption BEHIND the group's caption:
7174 // closing the hole is what the second caption's position says.
7175 let group = || {
7176 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7177 let s1 = p.add_lane(LaneKind::Subtitle);
7178 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
7179 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
7180 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7181 (p, s1)
7182 };
7183
7184 // Deleted by the picture: all three lanes close.
7185 let (mut p, s1) = group();
7186 assert!(p.delete_in(Lane::V1, 0));
7187 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
7188 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
7189 assert_eq!(
7190 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
7191 [60],
7192 "the caption's lane closed by its own span: the follower slid up"
7193 );
7194 assert!(p.undo(), "one step");
7195 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
7196
7197 // By the sound: the same whole-group delete.
7198 let (mut p, s1) = group();
7199 assert!(p.delete_in(Lane::A1, 0));
7200 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7201 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
7202
7203 // By the caption itself: the same again.
7204 let (mut p, s1) = group();
7205 assert!(p.delete_sub_in(s1, 0));
7206 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7207 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
7208 assert!(links_are_consistent(&p.lanes).is_ok());
7209
7210 // A caption lifted ALONE still leaves its gap: the ungrouped law,
7211 // unchanged.
7212 let (mut p, s1) = group();
7213 assert!(p.ungroup(s1, 0), "the caption stands alone");
7214 assert!(p.lift_sub(s1, 0));
7215 assert_eq!(
7216 p.sub_lane(s1)[0].start, 90,
7217 "the follower stayed put: a lone caption's lift is a gap"
7218 );
7219 }
7220
7221 /// Dragging a grouped caption carries its clips, one delta for all of them
7222 /// -- and a caption in no group refuses an overlap exactly as it always did.
7223 #[test]
7224 fn dragging_a_grouped_caption_carries_its_group() {
7225 let caption = |start: u32, frames: u32| SubClip {
7226 start,
7227 frames,
7228 track: 0,
7229 in_us: 0,
7230 out_us: i64::from(frames) * 1_000_000,
7231 link: None,
7232 };
7233 let track = || SubtitleTrack {
7234 path: FILE.into(),
7235 track: None,
7236 language: "eng".into(),
7237 name: String::new(),
7238 label: "eng".into(),
7239 cues: Vec::new(),
7240 bitmap: false,
7241 refused: None,
7242 };
7243 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7244 let s1 = p.add_lane(LaneKind::Subtitle);
7245 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7246 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7247
7248 // Same lane, further along: everyone moves by the same eight frames.
7249 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
7250 assert_eq!(p.sub_lane(s1)[0].start, 10);
7251 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
7252 assert!(links_are_consistent(&p.lanes).is_ok());
7253
7254 // ...and an ungrouped caption is the caption it always was.
7255 assert!(p.ungroup(s1, 0));
7256 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
7257 let s1 = q.add_lane(LaneKind::Subtitle);
7258 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
7259 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
7260 assert!(q
7261 .move_sub(s1, 0, s1, 3)
7262 .unwrap_err()
7263 .to_string()
7264 .contains("already covers"));
7265 }
7266
7267 /// A trim carries a group's caption by the same delta as its clips, clamped
7268 /// to the caption's own walls -- the offsets between the members survive.
7269 #[test]
7270 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
7271 let caption = |start: u32, frames: u32| SubClip {
7272 start,
7273 frames,
7274 track: 0,
7275 in_us: 0,
7276 out_us: i64::from(frames) * 1_000_000,
7277 link: None,
7278 };
7279 let track = || SubtitleTrack {
7280 path: FILE.into(),
7281 track: None,
7282 language: "eng".into(),
7283 name: String::new(),
7284 label: "eng".into(),
7285 cues: Vec::new(),
7286 bitmap: false,
7287 refused: None,
7288 };
7289 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7290 let s1 = p.add_lane(LaneKind::Subtitle);
7291 // The caption sits two frames into the take and ends one early. The
7292 // source runs past the clip, or there is no tail to pull out.
7293 let src = &[20];
7294 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
7295 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7296
7297 // The tail goes out by three: the clip to 12, the caption to 11.
7298 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
7299 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
7300 assert_eq!(
7301 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
7302 (2, 11),
7303 "the caption follows by the delta"
7304 );
7305 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
7306
7307 // The head comes in by two: everyone's start moves two along.
7308 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
7309 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
7310 assert!(links_are_consistent(&p.lanes).is_ok());
7311 }
7312
7313 #[test]
7314 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
7315 let mut p = three();
7316 let before = shape(&p);
7317 assert!(!p.split(0), "timeline 0 has nothing before it");
7318 assert!(!p.split(3), "existing boundary");
7319 assert!(!p.split(5), "existing boundary");
7320 assert!(!p.split(9), "one past the last frame");
7321 assert!(!p.split(1_000));
7322 assert_eq!(shape(&p), before);
7323 // one undo lands before the *second* split, so the refusals pushed nothing
7324 assert!(p.undo());
7325 assert_eq!(p.clips().len(), 2, "refused splits push no history");
7326
7327 // ...and a frame that is a gap in both lanes has nothing to split.
7328 let mut p = three();
7329 assert!(p.lift(Lane::V1, 1));
7330 assert!(p.lift(Lane::A1, 1));
7331 assert!(!p.split(4), "a gap is not a clip");
7332 }
7333
7334 #[test]
7335 fn regroup_refuses_what_a_split_could_not_have_made() {
7336 let mut p = three();
7337 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
7338 assert!(p.regroup(5));
7339 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
7340 // A boundary with a gap on one side, and one where the sources do not
7341 // meet, are both refused.
7342 let mut p = three();
7343 assert!(p.lift(Lane::V1, 1));
7344 assert!(p.lift(Lane::A1, 1));
7345 assert!(!p.regroup(3), "nothing starts at 3 any more");
7346 let mut p = three();
7347 for l in p.lanes() {
7348 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
7349 }
7350 assert!(!p.regroup(3), "source 100 does not follow source 3");
7351 assert!(!p.regroup(0), "nothing ends at 0");
7352 assert!(!p.regroup(1_000));
7353 }
7354
7355 #[test]
7356 fn map_and_spans_sweep_every_boundary() {
7357 let p = three();
7358 assert_eq!(p.timeline_frames(), 9);
7359 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
7360 // contiguous source here, so the clip index is what actually moves
7361 let expect = [
7362 (0, (0, 0)),
7363 (1, (0, 1)),
7364 (2, (0, 2)),
7365 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
7366 (4, (1, 4)),
7367 (5, (2, 5)),
7368 (6, (2, 6)),
7369 (7, (2, 7)),
7370 (8, (2, 8)),
7371 ];
7372 for (t, want) in expect {
7373 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
7374 }
7375 assert_eq!(p.map_timeline(9), None);
7376 // A span is the rest of the clip from where it was asked about.
7377 assert_eq!(
7378 p.span_at(Lane::V1, 6),
7379 Some(Span {
7380 start: 6,
7381 len: 3,
7382 from: Some((0, 6)),
7383 speed: Speed::NORMAL
7384 })
7385 );
7386 assert_eq!(p.span_at(Lane::V1, 9), None);
7387 }
7388
7389 /// The fit policy is one byte *in* the clip rather than an index into a
7390 /// table like the eq and the grade: there is nothing for a table to share.
7391 /// It costs the clip nothing at all -- the fields before it (a `usize`
7392 /// source and two `Option<u16>`s) already left the struct padded to 40
7393 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
7394 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
7395 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
7396 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
7397 /// words after it pads out to the next multiple of 8: 56 bytes total.
7398 /// The transform index is a third `Option<u16>`, same reason as the eq and
7399 /// colour ones before it -- it lands in bytes already spent on padding, so
7400 /// the struct still costs 56.
7401 /// The visualizer look is the first field whose own width outgrows the
7402 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
7403 /// the clip's own four), so the words after it come to 60 and the
7404 /// alignment rounds them to 64 -- one word more than a clip used to cost.
7405 /// This is the assert that says so: a clip that grows a word grows every
7406 /// undo snapshot and every clipboard copy with it.
7407 #[test]
7408 fn a_fit_policy_costs_the_clip_no_word() {
7409 assert_eq!(
7410 std::mem::size_of::<Clip>(),
7411 64,
7412 "Clip changed size: {} bytes",
7413 std::mem::size_of::<Clip>()
7414 );
7415 }
7416
7417 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
7418 /// anything in `three()` so it is recognisable wherever it lands.
7419 const PASTED: Clip = Clip {
7420 fade_in: 0,
7421 fade_out: 0,
7422 transition_out: 0,
7423 visualizer: 0,
7424 viz_paint: 0,
7425 start: 0,
7426 in_frame: 100,
7427 out_frame: 102,
7428 source: 0,
7429 link: None,
7430 eq: None,
7431 color: None,
7432 transform: None,
7433 fit: FitPolicy::Fit,
7434 speed: Speed::NORMAL,
7435 };
7436
7437 #[test]
7438 fn paste_mid_clip_splits_around_it() {
7439 let mut p = three();
7440 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
7441 assert_eq!(p.timeline_frames(), 11);
7442 assert_eq!(
7443 shape(&p)[0],
7444 vec![
7445 clip(0, 0, 3, 0),
7446 clip(3, 3, 5, 0),
7447 clip(5, 5, 6, 0),
7448 clip(6, 100, 102, 0),
7449 clip(8, 6, 9, 0),
7450 ]
7451 );
7452 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
7453 // The pasted frames are exactly where they were asked for, and the
7454 // split-off remainder resumes after them.
7455 assert_eq!(p.map_timeline(6), Some((3, 100)));
7456 assert_eq!(p.map_timeline(7), Some((3, 101)));
7457 assert_eq!(p.map_timeline(8), Some((4, 6)));
7458 }
7459
7460 #[test]
7461 fn paste_at_boundary_zero_and_end() {
7462 let mut p = three();
7463 assert!(p.paste(3, PASTED), "existing boundary: no split");
7464 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
7465 assert_eq!(p.map_timeline(3), Some((1, 100)));
7466
7467 let mut p = three();
7468 assert!(p.paste(0, PASTED));
7469 assert_eq!(p.map_timeline(0), Some((0, 100)));
7470 assert_eq!(p.map_timeline(2), Some((1, 0)));
7471
7472 // At the end: appended, there being nothing in front to leave black.
7473 let mut p = three();
7474 assert!(p.paste(9, PASTED));
7475 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
7476 // Past it: down on the frame it was asked for, black in front of it --
7477 // a row let go on the open bed lands under the ghost that promised it.
7478 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
7479 assert!(p.paste(1_000, PASTED));
7480 assert_eq!(p.timeline_frames(), 1_002);
7481 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
7482 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
7483
7484 // An empty clip is the one thing refused, and it pushes no history.
7485 let mut p = three();
7486 assert!(!p.paste(4, clip(0, 7, 7, 0)));
7487 assert_eq!(p.clips().len(), 3);
7488 }
7489
7490 /// The data-loss paste: a clip of a source with no picture used to land on
7491 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
7492 /// carried it was refused on the way back in ("a box with a larger size").
7493 #[test]
7494 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
7495 let mut p = three();
7496 let wav = p.import("/nonexistent/song.wav", 0);
7497 let copied = Clip {
7498 fade_in: 0,
7499 fade_out: 0,
7500 transition_out: 0,
7501 visualizer: 0,
7502 viz_paint: 0,
7503 source: wav,
7504 ..PASTED
7505 };
7506 assert!(p.paste(3, copied));
7507 // The room is opened on every lane, or the two would slide apart...
7508 assert_eq!(p.timeline_frames(), 11);
7509 assert_eq!(
7510 shape(&p)[0],
7511 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
7512 "the video lane got room and nothing else"
7513 );
7514 // ...but the clip itself only reaches the lane that can play it.
7515 assert_eq!(
7516 shape(&p)[1],
7517 vec![
7518 clip(0, 0, 3, 0),
7519 clip(3, 100, 102, wav),
7520 clip(5, 3, 5, 0),
7521 clip(7, 5, 9, 0)
7522 ]
7523 );
7524 // A source with a picture is unchanged: still the grouped pair.
7525 let mut p = three();
7526 assert!(p.paste(3, PASTED));
7527 assert_eq!(shape(&p)[0], shape(&p)[1]);
7528 }
7529
7530 /// A hand-written file may hold a clip that ends at the very last frame
7531 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
7532 /// to wrap its start round to the front of the lane: an overlap in debug, a
7533 /// project no reload would accept in release.
7534 #[test]
7535 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
7536 let far = clip(u32::MAX - 90, 0, 90, 0);
7537 let parts = |c: Clip| {
7538 Project::from_parts(
7539 vec![Source::new(FILE, 0)],
7540 two(vec![c], vec![c]),
7541 Vec::new(),
7542 Vec::new(),
7543 Vec::new(),
7544 )
7545 .expect("valid parts")
7546 };
7547 let mut p = parts(far);
7548 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
7549 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
7550 assert!(!p.undo(), "...and pushes no history either");
7551 assert!(
7552 !p.paste(u32::MAX, PASTED),
7553 "appending has nowhere to go either: the timeline ends at the last frame"
7554 );
7555 // With room for exactly those frames the same paste is taken.
7556 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
7557 assert!(p.paste(0, PASTED));
7558 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
7559 }
7560
7561 #[test]
7562 fn paste_undoes_in_one_step() {
7563 let mut p = three();
7564 let before = shape(&p);
7565 assert!(p.paste(6, PASTED));
7566 assert!(p.undo());
7567 assert_eq!(shape(&p), before, "a paste is one undo step");
7568 }
7569
7570 #[test]
7571 fn a_copy_outlives_the_clip_it_came_from() {
7572 let mut p = three();
7573 let copied = p.clips()[1]; // [3,5)
7574 assert!(p.delete(1));
7575 // Just a frame range: the source is still on disk either way.
7576 assert!(p.paste(0, copied));
7577 assert_eq!(p.map_timeline(0), Some((0, 3)));
7578 assert_eq!(p.timeline_frames(), 9);
7579 }
7580
7581 #[test]
7582 fn delete_closes_the_gap_on_both_lanes() {
7583 let mut p = three();
7584 assert!(p.delete(1));
7585 assert_eq!(p.timeline_frames(), 7);
7586 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
7587 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
7588 // timeline 3 used to be source 3; the gap closed so it is source 5 now
7589 assert_eq!(p.map_timeline(3), Some((1, 5)));
7590 assert_eq!(p.map_timeline(6), Some((1, 8)));
7591 assert_eq!(p.map_timeline(7), None);
7592 }
7593
7594 #[test]
7595 fn delete_first_last_and_only() {
7596 let mut p = three();
7597 assert!(p.delete(0));
7598 assert_eq!(p.map_timeline(0), Some((0, 3)));
7599 assert_eq!(p.timeline_frames(), 6);
7600
7601 let mut p = three();
7602 assert!(p.delete(2));
7603 assert_eq!(p.timeline_frames(), 5);
7604 assert_eq!(p.map_timeline(4), Some((1, 4)));
7605
7606 assert!(!p.delete(2), "index past the end");
7607 assert!(p.delete(1));
7608 assert!(p.delete(0), "and the last remaining clip goes too");
7609 assert_eq!(p.clips().len(), 0);
7610 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
7611 assert!(!p.delete(0), "there is nothing left to delete");
7612 assert!(p.undo(), "one gesture, one undo");
7613 assert_eq!(p.clips().len(), 1);
7614 }
7615
7616 /// The offset model's point: one lane loses a clip, the other does not move.
7617 #[test]
7618 fn a_lift_leaves_a_gap_and_moves_nothing() {
7619 let mut p = three();
7620 let video_before = shape(&p)[0].clone();
7621 assert!(p.lift(Lane::A1, 1));
7622 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7623 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7624 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7625 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7626 assert_eq!(p.map(Lane::A1, 4), None);
7627 assert_eq!(
7628 p.span_at(Lane::A1, 3),
7629 Some(Span {
7630 start: 3,
7631 len: 2,
7632 from: None,
7633 speed: Speed::NORMAL
7634 })
7635 );
7636 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7637 assert!(p.undo());
7638 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7639 }
7640
7641 #[test]
7642 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7643 let mut p = three();
7644 assert!(p.lift(Lane::A1, 2));
7645 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7646 assert_eq!(
7647 p.span_at(Lane::A1, 5),
7648 Some(Span {
7649 start: 5,
7650 len: 4,
7651 from: None,
7652 speed: Speed::NORMAL
7653 }),
7654 "the audio lane holds silence to the end of the picture"
7655 );
7656 assert_eq!(p.span_at(Lane::A1, 9), None);
7657 // Every lane covers the timeline exactly, gaps included.
7658 for l in p.lanes() {
7659 let spans = p.spans_from(l, 0);
7660 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7661 assert_eq!(spans[0].start, 0);
7662 }
7663 }
7664
7665 /// The timeline is emptiable: the last placement comes off like any other,
7666 /// the project holds "nothing on any lane" as a state, and one undo per
7667 /// gesture brings it back.
7668 #[test]
7669 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7670 let mut p = Project::single(FILE, 9);
7671 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7672 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7673 assert_eq!(p.timeline_frames(), 0);
7674 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7675 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7676 assert!(!p.lift(Lane::A1, 0), "index past the end");
7677 assert!(p.undo(), "and the last lift comes back");
7678 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7679 // A saved-and-loaded empty timeline is a project like any other, and it
7680 // still names the file its frame rate came from.
7681 assert!(p.lift(Lane::V1, 0));
7682 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7683 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7684 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7685 assert_eq!(back.timeline_frames(), 0);
7686 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7687 }
7688
7689 /// What a keyboard selection walks: one answer per lane, gaps included --
7690 /// the composite's own answer is one lane's and cannot say what the audio
7691 /// lane holds under the same playhead.
7692 #[test]
7693 fn lane_clip_at_answers_for_each_lane_separately() {
7694 let mut p = Project::single(FILE, 9);
7695 assert!(p.split(3), "both lanes split");
7696 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7697 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7698 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7699 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7700 // A gap on one lane leaves the other's clip selectable there.
7701 assert!(p.lift(Lane::A1, 0));
7702 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7703 assert_eq!(
7704 p.lane_clip_at(Lane::A1, 3),
7705 Some(0),
7706 "indices moved with it"
7707 );
7708 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7709 // A lane that is not there is not a panic.
7710 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7711 }
7712
7713 #[test]
7714 fn place_overwrites_only_its_own_lane() {
7715 let mut p = three();
7716 let audio_before = shape(&p)[1].clone();
7717 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7718 // is trimmed, nothing shifts.
7719 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7720 assert_eq!(
7721 shape(&p)[0],
7722 vec![
7723 clip(0, 0, 3, 0),
7724 clip(3, 3, 4, 0),
7725 clip(4, 100, 102, 0),
7726 clip(6, 6, 9, 0),
7727 ]
7728 );
7729 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7730 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7731
7732 // Placed inside one clip, it splits it in two.
7733 let mut p = Project::single(FILE, 9);
7734 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7735 assert_eq!(
7736 shape(&p)[0],
7737 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7738 );
7739 // ...and placed past the end it makes a gap, which is the whole point.
7740 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7741 assert_eq!(p.timeline_frames(), 22);
7742 assert_eq!(
7743 p.span_at(Lane::V1, 9),
7744 Some(Span {
7745 start: 9,
7746 len: 11,
7747 from: None,
7748 speed: Speed::NORMAL
7749 })
7750 );
7751 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7752 }
7753
7754 /// A file with sound let go over a further video track: both halves go down,
7755 /// on the same frames, and the audio row is added when the `+ V` button left
7756 /// the project without one. One undo takes the lane and both clips back.
7757 #[test]
7758 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7759 let mut p = three();
7760 let v2 = p.add_lane(LaneKind::Video);
7761 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7762
7763 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7764 let a2 = Lane::new(LaneKind::Audio, 1);
7765 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7766 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7767 assert_eq!(p.lane(v2)[0].start, 4);
7768 assert_eq!(p.lane(v2)[0].end(), 6);
7769 assert_eq!(
7770 p.lane(v2)[0].link,
7771 p.lane(a2)[0].link,
7772 "one take, not two placements"
7773 );
7774 assert!(p.lane(v2)[0].link.is_some());
7775 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7776 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7777
7778 // The pair overwrites its own two lanes and nothing else, exactly as a
7779 // one-lane place does.
7780 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7781 assert_eq!(p.lane(v2), p.lane(a2));
7782 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7783 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7784
7785 assert!(p.undo(), "one step for the second pair");
7786 assert_eq!(p.lane(v2).len(), 1);
7787 assert!(p.undo(), "one step for the first pair *and* its lane");
7788 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7789 assert!(p.lane(v2).is_empty());
7790
7791 // Refusals cost nothing: sound placed alone is `place`'s door.
7792 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7793 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7794 assert!(
7795 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7796 "a lane that is not there"
7797 );
7798 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7799 }
7800
7801 /// The drag between tracks: let go at the frames it already covers the clip
7802 /// keeps them, one undo takes it back, and every way it can be refused
7803 /// leaves the project untouched.
7804 #[test]
7805 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7806 let v2 = Lane::new(LaneKind::Video, 1);
7807 let mut p = three();
7808 assert_eq!(p.add_lane(LaneKind::Video), v2);
7809 let before = shape(&p);
7810
7811 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7812 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7813 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7814 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7815 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7816 // One snapshot: a single undo, and the lane list survives it.
7817 assert!(p.undo());
7818 assert_eq!(shape(&p), before);
7819
7820 // A lane that is not there, the lane and frame it is already at, an
7821 // index that is not there, and a move across kinds: all refused,
7822 // nothing changed.
7823 let history = p.history.len();
7824 for (from, idx, to, start) in [
7825 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7826 (Lane::V1, 1, Lane::V1, 3),
7827 (Lane::V1, 9, v2, 3),
7828 (Lane::V1, 1, Lane::A1, 3),
7829 (Lane::A1, 1, v2, 3),
7830 ] {
7831 assert!(
7832 !p.move_clip(from, idx, to, start),
7833 "{from:?} {idx} -> {to:?} at {start}"
7834 );
7835 }
7836 assert_eq!(shape(&p), before);
7837 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7838
7839 // Landing on another clip is refused rather than overwriting it: the
7840 // pointer named the lane, never the take already sitting there.
7841 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7842 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7843 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7844 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7845 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7846 }
7847
7848 /// The drag *along* a track, which is the one every other editor has: the
7849 /// clip lands on the frame the pointer let it go at, and stops dead against
7850 /// the neighbour rather than overwriting it.
7851 #[test]
7852 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7853 let sources = vec![Source::new(FILE, 0)];
7854 let lanes = vec![
7855 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7856 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7857 ];
7858 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7859 let before = shape(&p);
7860
7861 // Into the gap, exactly where it was let go -- nothing else moves.
7862 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7863 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7864 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7865 // Dragged past the clip in front of it: clamped to its wall, laid end
7866 // to end with it, never over it.
7867 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7868 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7869 // One undo per drag, and both of them together are the state it started
7870 // in -- the frames each clip plays never changed.
7871 assert!(p.undo() && p.undo());
7872 assert_eq!(shape(&p), before);
7873
7874 // A drop that changes nothing is a click, not an edit.
7875 let history = p.history.len();
7876 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7877 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7878 }
7879
7880 /// A drag carries the whole take: the sound half travels exactly as far as
7881 /// the picture does, and the tighter of their two walls stops both.
7882 #[test]
7883 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7884 let mut p = three();
7885 assert!(
7886 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7887 "room to the right"
7888 );
7889 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7890 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7891 // Something in the sound's way, and nothing at all in the picture's.
7892 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7893 let before = shape(&p);
7894
7895 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7896 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7897 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7898 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7899 assert!(p.undo());
7900 assert_eq!(shape(&p), before, "one undo for the whole take");
7901 }
7902
7903 /// The drag that does both at once -- another lane *and* another frame --
7904 /// which is what a pointer let go over a lane always names.
7905 #[test]
7906 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7907 let v2 = Lane::new(LaneKind::Video, 1);
7908 let mut p = three();
7909 assert_eq!(p.add_lane(LaneKind::Video), v2);
7910
7911 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7912 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7913 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7914 assert_eq!(
7915 p.lane(Lane::A1)[2].start,
7916 20,
7917 "its sound travelled the same distance"
7918 );
7919 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7920 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7921 }
7922
7923 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7924 /// [`three`] cuts up all nine of its frames.
7925 const SRC: &[u32] = &[9];
7926
7927 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7928 /// else on the lane moves, and every wall stops the edge rather than
7929 /// refusing the gesture.
7930 #[test]
7931 fn trimming_the_tail_stops_at_every_wall() {
7932 let mut p = three();
7933
7934 // Pulled in: a gap opens behind it and the clip after it stays put.
7935 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7936 assert_eq!(
7937 shape(&p)[0],
7938 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7939 );
7940 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7941 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7942
7943 // ...and back out, no further than the clip behind it.
7944 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7945 assert_eq!(
7946 shape(&p)[0][1],
7947 clip(3, 3, 5, 0),
7948 "stopped at the neighbour"
7949 );
7950 assert!(
7951 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7952 "already at the wall"
7953 );
7954
7955 // One frame of clip always survives, however far back the pointer went.
7956 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7957 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7958
7959 // The last clip has no neighbour, so what stops it is the file: nine
7960 // frames is nine frames.
7961 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7962 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7963 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7964 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7965 // A source nobody told us the length of may not grow at all -- an
7966 // out-point past the end of a file is a save that will not open again.
7967 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7968 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7969 }
7970
7971 /// The head pulled in takes the in-point with it -- what stays plays what it
7972 /// always played -- and stops at the source's own first frame.
7973 #[test]
7974 fn trimming_the_head_moves_the_in_point() {
7975 let mut p = three();
7976 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7977 assert_eq!(
7978 shape(&p)[0][0],
7979 clip(2, 2, 3, 0),
7980 "two frames off the front"
7981 );
7982 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7983 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7984 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7985 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7986 // One frame survives here too.
7987 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7988 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7989
7990 // A clip that does not begin at its source's first frame: its head goes
7991 // back to source frame 0 and not one frame further.
7992 let mut p = Project::single(FILE, 9);
7993 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7994 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7995 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7996 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7997 }
7998
7999 /// A clip whose in-point is *past* its own start -- what a ripple delete
8000 /// leaves, the piece in front of it gone and this one slid back to frame 0
8001 /// carrying the in-point the cut gave it. Its head has more source behind it
8002 /// than the timeline has room for, and the timeline's own first frame is the
8003 /// wall: asking is not an overflow, and the answer is 0.
8004 #[test]
8005 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
8006 let mut p = Project::single(FILE, 9);
8007 assert!(p.split(5));
8008 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
8009 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
8010
8011 assert_eq!(
8012 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
8013 Some((0, 3)),
8014 "back to frame 0 at most, and one frame of clip always survives"
8015 );
8016 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
8017 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
8018 assert_eq!(
8019 shape(&p)[0],
8020 vec![clip(2, 7, 9, 0)],
8021 "the in-point followed"
8022 );
8023 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
8024 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
8025 }
8026
8027 /// A still is trimmed from its head exactly as it is from its tail: it has
8028 /// no earlier frame to walk an in-point back to, so the wall is the length
8029 /// the caller's table allows it, measured back from the tail. Measured from
8030 /// the in-point -- which a placed picture has at 0 -- its left edge could
8031 /// never be dragged outwards at all.
8032 #[test]
8033 fn a_stills_head_stretches_out_like_its_tail() {
8034 const STILL: &str = "/nonexistent/card.png";
8035 /// What a still is held to, as `PlaybackSession` fills the table in.
8036 const CAP: &[u32] = &[60];
8037
8038 let mut p = Project::single(STILL, 20);
8039 assert!(p.lift(Lane::A1, 0), "a picture is silent");
8040 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
8041 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
8042
8043 // A source with no entry in the table may not grow, here as at the tail.
8044 assert_eq!(
8045 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
8046 Some((100, 119)),
8047 "a length nobody told us buys no head room"
8048 );
8049 assert_eq!(
8050 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
8051 Some((60, 119)),
8052 "back to a whole cap's worth, one frame of clip surviving"
8053 );
8054 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
8055 assert_eq!(
8056 shape(&p)[0][0],
8057 clip(80, 0, 40, 0),
8058 "twenty frames longer, and still read from the source's first frame"
8059 );
8060 // Past the cap is clamped, exactly as the tail is -- not refused.
8061 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
8062 assert_eq!(
8063 shape(&p)[0][0],
8064 clip(60, 0, 60, 0),
8065 "a cap's worth, no more"
8066 );
8067 // ...and the clip in front is the nearer wall of the two: no head trim
8068 // may open an overlap.
8069 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
8070 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
8071 assert_eq!(
8072 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
8073 Some((85, 119)),
8074 "up to the neighbour's last frame and not over it"
8075 );
8076 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
8077 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
8078 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
8079 }
8080
8081 /// Linked halves trim as one: a link is one span on however many lanes, so
8082 /// the sound follows the picture's edge -- and the tightest wall of the two
8083 /// is what stops both.
8084 #[test]
8085 fn linked_halves_trim_together() {
8086 let mut p = three();
8087 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
8088 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
8089
8090 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
8091 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
8092 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
8093 assert!(
8094 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
8095 "either half drags it"
8096 );
8097 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
8098 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8099
8100 // Something in the way on the *audio* lane stops the picture's tail as
8101 // well: the group can only go as far as its tightest member.
8102 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
8103 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
8104 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
8105 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
8106 links_are_consistent(&p.lanes).expect("still one span");
8107 }
8108
8109 /// A whole drag is one undo step -- the front-end commits once, at the
8110 /// release -- and an edge asked to stay where it is costs none at all.
8111 #[test]
8112 fn a_trim_is_one_undo_step() {
8113 let mut p = three();
8114 let before = shape(&p);
8115 let history = p.history.len();
8116
8117 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
8118 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
8119 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
8120 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
8121 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
8122 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
8123
8124 assert!(p.undo());
8125 assert_eq!(shape(&p), before, "both halves back, in one step");
8126 }
8127
8128 /// A moved half stays in its group: a link names a span, not a lane, so the
8129 /// picture on `V2` is still the same take as the sound under it on `A1`.
8130 #[test]
8131 fn move_clip_keeps_the_group() {
8132 let v2 = Lane::new(LaneKind::Video, 1);
8133 let mut p = three();
8134 p.add_lane(LaneKind::Video);
8135 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
8136 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
8137 assert!(p.move_clip(Lane::V1, 1, v2, 3));
8138 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
8139 links_are_consistent(&p.lanes).expect("one id per lane, one span");
8140 assert_eq!(
8141 p.lane(v2)[0].start,
8142 p.lane(Lane::A1)[1].start,
8143 "and still covers the same span as its sound"
8144 );
8145 }
8146
8147 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
8148 /// head of a lane, between two clips, inside a clip, past the last one,
8149 /// and on a lane holding nothing at all.
8150 #[test]
8151 fn gap_at_finds_the_hole_a_frame_sits_in() {
8152 let mut p = Project::single(FILE, 1);
8153 let v = p.add_lane(LaneKind::Video);
8154 // Empty lane: nothing before and nothing after -- not a gap, since
8155 // there is nothing to ripple toward.
8156 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
8157
8158 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
8159 // Before the only clip: the gap runs from the timeline's own head.
8160 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
8161 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
8162 // Inside the clip: not a gap.
8163 assert_eq!(p.gap_at(v, 5), None);
8164 assert_eq!(p.gap_at(v, 7), None);
8165 // Past the only clip: the open end of the lane, not a gap -- there is
8166 // nothing after it to slide back.
8167 assert_eq!(p.gap_at(v, 8), None);
8168 assert_eq!(p.gap_at(v, 100), None);
8169
8170 assert!(p.place(v, 12, clip(12, 0, 2, 0)), "a second clip at [12,14)");
8171 // Between the two: the gap [8,12).
8172 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
8173 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
8174 assert_eq!(p.gap_at(v, 14), None, "still the open end");
8175
8176 assert!(
8177 p.place(v, 8, clip(8, 0, 4, 0)),
8178 "fills [8,12) exactly, meeting both neighbours"
8179 );
8180 assert_eq!(p.gap_at(v, 8), None, "adjacent clips leave no frame to name a gap");
8181 assert_eq!(p.gap_at(v, 11), None);
8182 }
8183
8184 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
8185 /// menu named: the clip after the gap slides back on that lane, a clip on
8186 /// another lane at the very same frame range does not move, and the whole
8187 /// close is one press of undo.
8188 #[test]
8189 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
8190 let mut p = Project::single(FILE, 1);
8191 let v = p.add_lane(LaneKind::Video);
8192 let a = p.add_lane(LaneKind::Audio);
8193 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
8194 assert!(
8195 p.place(a, 0, clip(0, 0, 3, 0)),
8196 "A clip at [0,3) -- outside the video lane's gap and this scope"
8197 );
8198 let before = shape(&p);
8199 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
8200 assert_eq!((start, len), (0, 5));
8201 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
8202 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
8203 assert_eq!(p.lane(a)[0].start, 0, "the untouched lane's clip did not move");
8204 assert!(p.undo(), "one press undoes the whole close");
8205 assert_eq!(shape(&p), before, "back to exactly where it was");
8206 }
8207
8208 /// A clip carrying an explicit link id -- what a
8209 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
8210 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
8211 /// already builds inline.
8212 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
8213 Clip {
8214 fade_in: 0,
8215 fade_out: 0,
8216 transition_out: 0,
8217 visualizer: 0,
8218 viz_paint: 0,
8219 start,
8220 in_frame,
8221 out_frame,
8222 source: 0,
8223 link: Some(link),
8224 eq: None,
8225 color: None,
8226 transform: None,
8227 fit: FitPolicy::default(),
8228 speed: Speed::NORMAL,
8229 }
8230 }
8231
8232 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
8233 /// bordered by a linked take whose `A1` half is empty across the very
8234 /// same stretch widens the scope to both lanes, so the ripple carries the
8235 /// take rather than tearing it -- and one undo puts both halves back.
8236 #[test]
8237 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
8238 let sources = vec![Source::new(FILE, 0)];
8239 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8240 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8241 let mut p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8242 .expect("valid parts");
8243 let before = shape(&p);
8244 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8245 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 2)), "the same stretch is empty on A1 too");
8246
8247 let scope = p
8248 .gap_take_scope(Lane::V1, 3, 2)
8249 .expect("a matching gap on both halves widens the scope");
8250 assert_eq!(scope.len(), 2, "the take's other lane joins");
8251 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
8252
8253 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
8254 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
8255 assert_eq!(p.lane(Lane::A1)[1].start, 3, "A1's far half rode along, in sync");
8256 assert!(p.undo(), "one press undoes the whole close");
8257 assert_eq!(shape(&p), before, "back to exactly where it was");
8258 }
8259
8260 /// The real design question: a take whose gap is not the *same size* on
8261 /// both lanes cannot ripple by one number without pulling a lane's clip
8262 /// out from under the other's sync -- refused by name, with the frame
8263 /// naming which lane is out of step, rather than silently taking real
8264 /// media off the shorter side.
8265 #[test]
8266 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
8267 let sources = vec![Source::new(FILE, 0)];
8268 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8269 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
8270 // shorter than V1's [3,5) -- a legal offset-preserving group, and
8271 // still one take.
8272 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
8273 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8274 .expect("valid parts");
8275 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8276 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
8277
8278 let err = p
8279 .gap_take_scope(Lane::V1, 3, 2)
8280 .expect_err("a mismatched gap cannot ripple by one number")
8281 .to_string();
8282 assert!(err.contains("A1"), "{err}");
8283 assert!(err.contains("out of sync"), "{err}");
8284 }
8285
8286 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
8287 /// there -- cannot close without cutting that audio out from under
8288 /// nothing asked to touch it: refused, not widened silently past.
8289 #[test]
8290 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
8291 let sources = vec![Source::new(FILE, 0)];
8292 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8293 // A1 plays through the whole span as one continuous clip, sharing
8294 // V1's first-half link: nothing empty at frame 3 there at all.
8295 let audio = vec![linked(0, 0, 9, 1)];
8296 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8297 .expect("valid parts");
8298 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8299 assert_eq!(p.gap_at(Lane::A1, 3), None, "A1 plays through, no gap there");
8300
8301 let err = p
8302 .gap_take_scope(Lane::V1, 3, 2)
8303 .expect_err("a solid partner cannot ripple with the gap")
8304 .to_string();
8305 assert!(err.contains("A1"), "{err}");
8306 assert!(err.contains("detach"), "{err}");
8307 }
8308
8309
8310 /// The sweep is the single-gap close repeated on one lane, but measured once
8311 /// and applied from the right. The differing gap lengths here expose a
8312 /// front-to-back bug: the last clip would be cut against a stale frame after
8313 /// the first gap shifted it.
8314 #[test]
8315 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
8316 let mut p = Project::single(FILE, 1);
8317 let v = p.add_lane(LaneKind::Video);
8318 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
8319 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
8320 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
8321 let before = shape(&p);
8322
8323 assert_eq!(p.gap_count(v), 3);
8324 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
8325 assert_eq!(report.closed, 3);
8326 assert!(report.skipped.is_empty());
8327 assert_eq!(
8328 p.lane(v),
8329 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
8330 "all gaps closed without eating source frames"
8331 );
8332 assert!(p.undo(), "one undo for the whole sweep");
8333 assert_eq!(shape(&p), before);
8334 }
8335
8336 /// Empty, already-contiguous and tail-only lanes are not controls that do
8337 /// work. A single clip with a head gap does close, because there is a real
8338 /// placement to ripple back.
8339 #[test]
8340 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
8341 let mut p = Project::single(FILE, 9);
8342 let v = p.add_lane(LaneKind::Video);
8343 let history = p.history.len();
8344 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
8345 assert_eq!(report, GapSweep::default(), "an empty lane has no bounded gap");
8346 assert_eq!(p.history.len(), history, "no undo step for a no-op");
8347
8348 let mut p = Project::single(FILE, 9);
8349 let v = p.add_lane(LaneKind::Video);
8350 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
8351 let before = shape(&p);
8352 let report = p.close_all_gaps_on_lane(v).expect("single clip lane exists");
8353 assert_eq!(report.closed, 1, "the head gap closes");
8354 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8355 assert!(p.undo());
8356 assert_eq!(shape(&p), before);
8357
8358 let mut p = Project::single(FILE, 9);
8359 let history = p.history.len();
8360 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8361 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
8362 assert_eq!(p.history.len(), history);
8363
8364 let mut p = Project::single(FILE, 9);
8365 let v = p.add_lane(LaneKind::Video);
8366 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
8367 let history = p.history.len();
8368 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
8369 assert_eq!(report, GapSweep::default(), "the open-ended tail is not closed");
8370 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8371 assert_eq!(p.history.len(), history);
8372 }
8373
8374 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
8375 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
8376 /// while V1's [6,9) has only [6,8) empty on A1.
8377 #[test]
8378 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
8379 let sources = vec![Source::new(FILE, 0)];
8380 let video = vec![
8381 linked(0, 0, 2, 1),
8382 linked(4, 4, 6, 2),
8383 clip(9, 9, 11, 0),
8384 ];
8385 let audio = vec![
8386 linked(0, 0, 2, 1),
8387 linked(4, 4, 6, 2),
8388 clip(8, 8, 11, 0),
8389 ];
8390 let mut p =
8391 Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8392 .expect("valid parts");
8393 let before = shape(&p);
8394
8395 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8396 assert_eq!(report.closed, 1);
8397 assert_eq!(report.skipped.len(), 1);
8398 assert_eq!(report.skipped[0].start, 6);
8399 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
8400 assert!(report.skipped[0].reason.contains("out of sync"), "{report:?}");
8401
8402 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
8403 assert_eq!(p.lane(Lane::A1)[1].start, 2, "and its other half stayed in sync");
8404 assert_eq!(p.lane(Lane::V1)[2].start, 7, "the skipped later gap remains");
8405 assert_eq!(p.lane(Lane::A1)[2].start, 6, "A1's shorter gap remains shorter");
8406 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
8407 assert!(p.undo(), "one undo restores every closed gap");
8408 assert_eq!(shape(&p), before);
8409 }
8410
8411 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
8412 /// their own caption storage: head gaps and gaps between cues count, an
8413 /// empty lane and the tail after the last cue do not.
8414 #[test]
8415 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
8416 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8417 let s = p.add_lane(LaneKind::Subtitle);
8418 assert_eq!(p.gap_at(s, 0), None, "an empty subtitle lane has nothing to close");
8419
8420 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8421 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
8422 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
8423 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
8424 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
8425
8426 p.place_sub(s, 12, caption(0, 2)).expect("second cue at [12,14)");
8427 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
8428 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
8429 assert_eq!(p.gap_at(s, 14), None, "tail after the last cue is still open-ended");
8430 }
8431
8432 /// Closing a caption gap ripples the subtitle lane only. It is not a media
8433 /// take close, so the video and audio lanes keep their frame positions.
8434 #[test]
8435 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
8436 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8437 let s = p.add_lane(LaneKind::Subtitle);
8438 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8439 let before_clips = shape(&p);
8440 let before_subs = p.sub_lane(s).to_vec();
8441
8442 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
8443 assert_eq!((start, len), (0, 5));
8444 p.cut_regions(&[(start, len)], &[s]).expect("caption lane gap closes");
8445
8446 assert_eq!(shape(&p), before_clips, "media lanes did not move");
8447 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
8448 assert!(p.undo(), "one undo restores the caption close");
8449 assert_eq!(shape(&p), before_clips);
8450 assert_eq!(p.sub_lane(s), before_subs);
8451 }
8452
8453 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
8454 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
8455 /// history entry for empty or already-contiguous lanes.
8456 #[test]
8457 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
8458 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8459 let s = p.add_lane(LaneKind::Subtitle);
8460 let history = p.history.len();
8461 let report = p.close_all_gaps_on_lane(s).expect("empty subtitle lane exists");
8462 assert_eq!(report, GapSweep::default(), "empty subtitle lane has no bounded gap");
8463 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
8464
8465 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
8466 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
8467 p.place_sub(s, 14, caption(0, 1)).expect("middle gap [9,14), tail after 15");
8468 let before = p.sub_lane(s).to_vec();
8469
8470 assert_eq!(p.gap_count(s), 3);
8471 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8472 assert_eq!(report.closed, 3);
8473 assert!(report.skipped.is_empty());
8474 assert_eq!(
8475 p.sub_lane(s),
8476 &[caption(0, 2), caption(2, 2), caption(4, 1)],
8477 "all bounded caption gaps closed without touching windows"
8478 );
8479 assert!(p.undo(), "one undo restores every caption gap");
8480 assert_eq!(p.sub_lane(s), before);
8481
8482 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8483 let s = p.add_lane(LaneKind::Subtitle);
8484 p.place_sub(s, 0, caption(0, 3)).expect("contiguous at the head");
8485 let history = p.history.len();
8486 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8487 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
8488 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
8489 assert_eq!(p.history.len(), history);
8490 }
8491
8492 #[test]
8493 fn ripple_delete_spans_partial_clips() {
8494 let mut p = three();
8495 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
8496 assert!(p.ripple_delete(2, 4));
8497 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
8498 assert_eq!(shape(&p)[1], shape(&p)[0]);
8499 assert_eq!(p.timeline_frames(), 5);
8500 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
8501 assert!(p.undo());
8502 assert_eq!(shape(&p), shape(&three()));
8503 // One that takes everything is a delete like any other: the timeline
8504 // empties, and the undo it cost brings it back whole.
8505 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
8506 assert_eq!(p.timeline_frames(), 0);
8507 assert!(
8508 !p.ripple_delete(0, 100),
8509 "and a delete with nothing left to take is not an undo step"
8510 );
8511 assert!(p.undo());
8512 assert_eq!(shape(&p), shape(&three()));
8513 }
8514
8515 #[test]
8516 fn undo_restores_exactly() {
8517 let mut p = three();
8518 let after_splits = shape(&p);
8519 assert!(p.delete(1));
8520 assert!(p.undo());
8521 assert_eq!(shape(&p), after_splits);
8522
8523 // walk all the way back through both splits, then run dry
8524 assert!(p.undo());
8525 assert_eq!(p.clips().len(), 2);
8526 assert!(p.undo());
8527 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8528 assert!(!p.undo(), "empty history");
8529 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8530 }
8531
8532 #[test]
8533 fn redo_restores_exactly() {
8534 let mut p = three();
8535 assert!(p.delete(1));
8536 let after_delete = p.parts();
8537 assert!(p.undo());
8538 assert!(p.redo());
8539 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
8540 assert!(!p.redo(), "empty redo stack");
8541 }
8542
8543 #[test]
8544 fn edit_after_undo_empties_redo() {
8545 let mut p = three();
8546 assert!(p.delete(1));
8547 assert!(p.undo());
8548 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
8549 assert!(p.split(1), "a fresh edit");
8550 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
8551 assert!(!p.redo(), "so redo has nothing left");
8552 }
8553
8554 #[test]
8555 fn redo_on_empty_stack_is_false() {
8556 let mut p = three();
8557 assert!(!p.redo(), "nothing has been undone yet");
8558 }
8559
8560 /// Past the cap the *oldest* step goes, so a long session undoes exactly
8561 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
8562 #[test]
8563 fn history_stops_at_the_cap() {
8564 let mut p = Project::single(FILE, 400);
8565 for frame in 1..=150 {
8566 assert!(p.split(frame), "split {frame} is an edit");
8567 }
8568 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
8569 for step in 0..HISTORY_CAP {
8570 assert!(p.undo(), "undo {step} is inside the cap");
8571 }
8572 assert!(!p.undo(), "and the 101st has nothing left to take");
8573 // 100 undos off 150 splits is the timeline after the 50th: the older
8574 // steps were dropped, not the newer ones.
8575 assert_eq!(p.clips().len(), 51);
8576 }
8577
8578 /// Undo/redo by hand across a split must never merge two takes into one
8579 /// group by reusing an id.
8580 #[test]
8581 fn group_ids_are_never_reused() {
8582 let mut p = Project::single(FILE, 9);
8583 assert!(p.split(3));
8584 let first = p.clips()[1].link;
8585 assert!(p.undo());
8586 assert!(p.split(5));
8587 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
8588 }
8589
8590 #[test]
8591 fn segments_from_reads_the_audio_lane() {
8592 let p = three();
8593 // mid-clip: partial first segment, whole clips after it
8594 assert_eq!(
8595 p.segments_from(4, FPS),
8596 vec![
8597 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8598 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8599 ]
8600 );
8601 // on a boundary: nothing partial
8602 assert_eq!(
8603 p.segments_from(3, FPS),
8604 vec![
8605 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
8606 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8607 ]
8608 );
8609 // from the top: one entry per clip
8610 assert_eq!(p.segments_from(0, FPS).len(), 3);
8611 // last clip only
8612 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
8613 // past the end / unusable fps
8614 assert!(p.segments_from(9, FPS).is_empty());
8615 assert!(p.segments_from(0, 0.0).is_empty());
8616 assert!(p.segments_from(0, f64::NAN).is_empty());
8617 }
8618
8619 #[test]
8620 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
8621 let mut p = three();
8622 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
8623 assert_eq!(
8624 p.segments_from(0, FPS),
8625 vec![
8626 (Some(0), 0.0, 3.0 / 30.0),
8627 (None, 0.0, 2.0 / 30.0),
8628 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8629 ]
8630 );
8631 // The list still covers exactly the timeline: that is what stops the
8632 // master clock stalling at the hole.
8633 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8634 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
8635 // Starting inside the gap trims the silence, not the clip after it.
8636 assert_eq!(
8637 p.segments_from(4, FPS),
8638 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
8639 );
8640 // ...and a lane that is nothing but gap is a run of silence.
8641 assert!(p.lift(Lane::A1, 0));
8642 assert!(p.lift(Lane::A1, 0));
8643 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
8644 }
8645
8646 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
8647 /// of source 0 then [0,4) of source 1.
8648 fn two_sources() -> Project {
8649 let mut p = three();
8650 let s = p.import(FILE2, 0);
8651 assert_eq!(s, 1);
8652 assert!(p.append_clip(s, 4));
8653 p
8654 }
8655
8656 #[test]
8657 fn import_dedups_and_appends() {
8658 let mut p = Project::single(FILE, 9);
8659 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
8660 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
8661 assert_eq!(p.import(FILE2, 0), 1);
8662 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
8663 // ...but the same file on another audio stream is another source: it is
8664 // what a clip names, and a clip plays exactly one stream.
8665 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
8666 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
8667 assert_eq!(p.sources()[2].audio_stream, 1);
8668 assert!(p.append_clip(2, 4), "a stream entry is placeable");
8669 assert!(p.undo());
8670 assert_eq!(p.sources().len(), 3);
8671 assert!(!p.append_clip(3, 5), "unknown source index");
8672 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
8673
8674 // Two spellings of one real file are one source: this is the case the
8675 // raw-path comparison above would get wrong.
8676 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
8677 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
8678 let mut p = Project::single(here, 9);
8679 assert_eq!(p.import(detour, 0), 0);
8680 assert_eq!(p.sources().len(), 1);
8681 }
8682
8683 #[test]
8684 fn append_clip_is_one_undo_step() {
8685 let mut p = two_sources();
8686 assert_eq!(p.timeline_frames(), 13);
8687 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
8688 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
8689 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
8690 assert!(p.undo());
8691 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
8692 assert_eq!(
8693 p.sources().len(),
8694 2,
8695 "the orphan source entry stays -- indexes are forever"
8696 );
8697 // ...and it is still usable, so a redo-by-hand costs no reimport.
8698 assert!(p.append_clip(1, 0));
8699 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
8700 }
8701
8702 #[test]
8703 fn edits_carry_the_source_along() {
8704 let mut p = two_sources();
8705 // A split inside the second source splits into two source-1 clips.
8706 assert!(p.split(11));
8707 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
8708 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
8709
8710 // A source-1 clip pasted into source-0 territory keeps its file, and so
8711 // does the source-0 half that got split off around it.
8712 let copied = p.clips()[4];
8713 assert!(p.paste(1, copied));
8714 assert_eq!(p.clips()[1].source, 1);
8715 assert_eq!(p.clips()[1].in_frame, 2);
8716 assert_eq!(p.clips()[2].source, 0);
8717 assert!(p.undo());
8718 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
8719 }
8720
8721 #[test]
8722 fn segments_from_names_the_source() {
8723 let p = two_sources();
8724 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
8725 assert_eq!(
8726 p.segments_from(4, FPS),
8727 vec![
8728 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8729 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8730 (Some(1), 0.0, 4.0 / 30.0),
8731 ]
8732 );
8733 // Mid-clip in source 1: only that source is left.
8734 assert_eq!(
8735 p.segments_from(10, FPS),
8736 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
8737 );
8738 assert!(p.segments_from(13, FPS).is_empty());
8739 // Segments still cover exactly the timeline across the join.
8740 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8741 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
8742 }
8743
8744 #[test]
8745 fn segments_follow_deletes_and_fps() {
8746 let mut p = three();
8747 assert!(p.delete(0));
8748 // source seconds, not timeline: deleting the head does not shift them
8749 let segs = p.segments_from(0, 25.0);
8750 assert_eq!(
8751 segs,
8752 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
8753 );
8754 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
8755 assert!(
8756 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
8757 "segments must cover exactly the timeline: {played}"
8758 );
8759 }
8760
8761 #[test]
8762 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
8763 // Import a second file, undo it: source 1 is now an orphan.
8764 let mut p = two_sources();
8765 assert!(p.undo());
8766 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8767 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
8768 assert!(eq.is_empty(), "and a project with no equalizer writes none");
8769 assert!(color.is_empty(), "nor a colour it never graded with");
8770 assert_eq!(
8771 lanes,
8772 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
8773 "the clips are untouched"
8774 );
8775
8776 // Three sources where only the middle one is orphaned: the survivors
8777 // renumber, and the clips follow.
8778 let mut p = Project::single(FILE, 9);
8779 assert_eq!(p.import(FILE2, 0), 1);
8780 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
8781 assert!(p.append_clip(2, 4));
8782 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8783 assert_eq!(
8784 sources,
8785 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
8786 );
8787 assert_eq!(
8788 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
8789 [0, 1]
8790 );
8791 // ...and what comes out is loadable, with the same timeline.
8792 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8793 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
8794 assert_eq!(reloaded.sources().len(), 2);
8795 }
8796
8797 /// Taking a file out of the library: refused by name -- lanes and counts --
8798 /// while a clip still plays from it, and once nothing does, the entry goes
8799 /// and every clip that indexed past it is renumbered onto the short list.
8800 #[test]
8801 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
8802 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
8803 // plus a second stream of FILE as source 2 with a take of its own.
8804 let mut p = two_sources();
8805 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
8806 assert!(p.append_clip(2, 4));
8807
8808 let refusal = p
8809 .remove_source(1)
8810 .expect_err("a source with clips on it cannot go")
8811 .to_string();
8812 assert!(refusal.contains(FILE2), "names the file: {refusal}");
8813 assert!(
8814 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
8815 "names the lanes holding it: {refusal}"
8816 );
8817 assert!(refusal.contains("still plays"), "{refusal}");
8818 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
8819 assert_eq!(shape(&p)[0][3].source, 1);
8820
8821 // Delete FILE2's take -- the whole span, on every lane -- and the entry
8822 // is free to go. Source 2's clips become source 1's.
8823 assert!(p.delete_in(Lane::V1, 3));
8824 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
8825 p.remove_source(1).expect("nothing plays FILE2 any more");
8826 assert_eq!(
8827 p.sources(),
8828 [Source::new(FILE, 0), Source::new(FILE, 1)],
8829 "the middle entry is gone"
8830 );
8831 assert_eq!(
8832 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
8833 [0, 0, 0, 1],
8834 "the clips past it renumbered"
8835 );
8836 assert_eq!(
8837 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
8838 [0, 0, 0, 1],
8839 "on every lane"
8840 );
8841 // What is left is a project that still loads, which is the whole point
8842 // of renumbering rather than leaving a hole.
8843 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8844 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8845 }
8846
8847 /// The two edges of a removal: it retires the undo stack (the corner-cut on
8848 /// [`Project::remove_source`]), and the last entry goes like any other
8849 /// once nothing plays it -- a project may name no file at all.
8850 #[test]
8851 fn remove_source_retires_undo_and_empties_the_library() {
8852 let mut p = two_sources();
8853 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
8854 assert!(!p.history.is_empty(), "there is something to undo");
8855 p.remove_source(1).expect("nothing plays FILE2");
8856 assert!(
8857 p.history.is_empty(),
8858 "a snapshot naming the removed source must not survive it"
8859 );
8860 assert!(!p.undo(), "and so there is nothing left to undo");
8861
8862 // The last file standing is held to the one rule every row is -- what
8863 // plays cannot go -- and to no other.
8864 assert_eq!(p.sources().len(), 1);
8865 let refusal = p
8866 .remove_source(0)
8867 .expect_err("its clips are still on the lanes")
8868 .to_string();
8869 assert!(refusal.contains("still plays"), "{refusal}");
8870 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
8871 while p.delete_in(Lane::V1, 0) {}
8872 p.remove_source(0)
8873 .expect("the last row goes like any other");
8874 assert!(
8875 p.sources().is_empty(),
8876 "a project may name no file at all: an empty library over an empty timeline"
8877 );
8878 assert_eq!(p.timeline_frames(), 0);
8879 assert!(
8880 p.remove_source(0).is_err(),
8881 "and an index that is not there is refused, not panicked on"
8882 );
8883 }
8884
8885 /// A clip's equalizer is the clip's: it survives every edit that copies a
8886 /// placement, and it comes back with an undo.
8887 #[test]
8888 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
8889 let mut p = three();
8890 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
8891 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
8892 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8893 assert!(
8894 p.eq_of(Lane::V1, 0).is_none(),
8895 "one clip, not the lane above"
8896 );
8897
8898 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
8899 assert!(p.split(1));
8900 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8901 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
8902 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
8903
8904 // A clipboard copy carries it -- onto another lane, at that.
8905 let copied = p.lane(Lane::A1)[1];
8906 assert!(p.place(Lane::V1, 20, copied));
8907 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
8908 assert!(p.undo());
8909 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
8910
8911 // ...and a change to one is one undo step, in both directions.
8912 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
8913 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
8914 assert!(p.undo());
8915 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8916 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
8917 assert!(p.eq_of(Lane::A1, 0).is_none());
8918 assert!(p.undo());
8919 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8920
8921 // Two refusals, neither of which costs an undo step.
8922 let mut nan = band_at(1);
8923 nan.bands[0].q = f32::INFINITY;
8924 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
8925 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
8926 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8927 assert!(p.undo());
8928 assert_eq!(
8929 p.lane(Lane::A1).len(),
8930 3,
8931 "one step back is before the split"
8932 );
8933 assert!(p.undo());
8934 assert!(
8935 p.eq_of(Lane::A1, 0).is_none(),
8936 "and the next is before the setting: the refusals pushed none"
8937 );
8938 }
8939
8940 /// The table is append-only within a session, exactly as the sources are, so
8941 /// an undone setting is still in it -- and a save is where it goes.
8942 #[test]
8943 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
8944 let mut p = three();
8945 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
8946 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
8947 assert!(p.undo(), "back to the first setting");
8948 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
8949
8950 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8951 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
8952 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
8953 assert_eq!(lanes[0].1[1].eq, None);
8954
8955 // One curve on three clips is one entry: settings that are equal share.
8956 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
8957 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
8958 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8959 assert_eq!(eq.len(), 1, "equal settings share their entry");
8960 assert_eq!(lanes[1].1[2].eq, Some(0));
8961 reloads(&p, "an equalizer that outlived an undo");
8962 }
8963
8964 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8965 /// grade is the clip's, through every edit that copies a placement.
8966 #[test]
8967 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
8968 let mut p = three();
8969 assert!(
8970 p.color_of(Lane::V1, 0).is_none(),
8971 "a fresh clip is ungraded"
8972 );
8973 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8974 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8975 assert!(
8976 p.color_of(Lane::A1, 0).is_none(),
8977 "one clip, not the lane below"
8978 );
8979 assert!(
8980 p.eq_of(Lane::V1, 0).is_none(),
8981 "and a grade is not an equalizer"
8982 );
8983
8984 // Cutting a graded clip must not grade half of it: both halves inherit.
8985 assert!(p.split(1));
8986 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8987 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
8988 assert!(
8989 p.color_of(Lane::V1, 2).is_none(),
8990 "the clip after it is ungraded"
8991 );
8992
8993 // A clipboard copy carries it -- onto another lane, at that.
8994 let copied = p.lane(Lane::V1)[1];
8995 assert!(p.place(Lane::A1, 20, copied));
8996 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
8997 assert!(p.undo());
8998 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8999
9000 // ...and a change to one is one undo step, in both directions.
9001 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
9002 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
9003 assert!(p.undo());
9004 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9005 assert!(
9006 p.set_color(Lane::V1, 0, None),
9007 "and taking it off is an edit"
9008 );
9009 assert!(p.color_of(Lane::V1, 0).is_none());
9010 assert!(p.undo());
9011 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9012
9013 // Two refusals, neither of which costs an undo step.
9014 let nan = ColorParams {
9015 contrast: f32::NAN,
9016 ..grade_at(1)
9017 };
9018 assert!(
9019 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
9020 "no clip there"
9021 );
9022 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
9023 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
9024 assert!(p.undo());
9025 assert_eq!(
9026 p.lane(Lane::V1).len(),
9027 3,
9028 "one step back is before the split"
9029 );
9030 assert!(p.undo());
9031 assert!(
9032 p.color_of(Lane::V1, 0).is_none(),
9033 "and the next is before the grade: the refusals pushed none"
9034 );
9035 }
9036
9037 /// A slider drag is one gesture: the press snapshots, every sample after it
9038 /// only regrades, and the single undo lands on what the clip was *before*
9039 /// the hand touched it -- not one step back down the drag.
9040 #[test]
9041 fn a_whole_colour_drag_undoes_in_one_step() {
9042 let mut p = three();
9043 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
9044 for n in 2..=8 {
9045 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
9046 }
9047 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
9048 assert!(p.undo());
9049 assert!(
9050 p.color_of(Lane::V1, 0).is_none(),
9051 "one undo is the whole gesture, back to ungraded"
9052 );
9053
9054 // The live write refuses what the snapshotting one refuses, and a
9055 // refusal still costs no history either way.
9056 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
9057 assert!(!p.set_color_live(
9058 Lane::V1,
9059 0,
9060 Some(ColorParams {
9061 contrast: f32::NAN,
9062 ..grade_at(1)
9063 })
9064 ));
9065 assert!(p.undo());
9066 assert_eq!(
9067 p.lane(Lane::V1).len(),
9068 2,
9069 "the next step back is the split before the drag: no sample pushed one"
9070 );
9071 }
9072
9073 /// A drag across the colour wheel is one gesture -- the look's twin of
9074 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
9075 /// sample after it only repaints, and the single undo lands on the look
9076 /// the clip had *before* the hand touched it. The committing setter is
9077 /// still exactly one step, refusals included.
9078 #[test]
9079 fn a_whole_look_drag_undoes_in_one_step() {
9080 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
9081 let mut p = three();
9082 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
9083 for hue in 2..=8u8 {
9084 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
9085 }
9086 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
9087 assert!(p.undo());
9088 assert_eq!(
9089 p.lane(Lane::V1)[0].viz_paint,
9090 0,
9091 "one undo is the whole gesture, back to the default look"
9092 );
9093
9094 // The live write refuses an index that is not there -- and a refusal
9095 // costs no history -- while one committing write is one step back.
9096 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
9097 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
9098 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
9099 assert!(p.undo());
9100 assert_eq!(
9101 p.lane(Lane::V1)[0].viz_paint,
9102 0,
9103 "the committing setter is one undo step, no more"
9104 );
9105 }
9106
9107 /// The colour table is append-only within a session, exactly as the eq one
9108 /// is -- and a save is where an undone grade goes.
9109 #[test]
9110 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
9111 let mut p = three();
9112 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
9113 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
9114 assert!(p.undo(), "back to the first grade");
9115 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
9116
9117 let (_, lanes, _, color, _) = p.without_orphan_sources();
9118 assert_eq!(
9119 color,
9120 vec![grade_at(1)],
9121 "what nothing plays is not written"
9122 );
9123 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
9124 assert_eq!(lanes[0].1[1].color, None);
9125
9126 // One grade on three clips is one entry: settings that are equal share.
9127 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
9128 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
9129 let (_, lanes, _, color, _) = p.without_orphan_sources();
9130 assert_eq!(color.len(), 1, "equal grades share their entry");
9131 assert_eq!(lanes[1].1[2].color, Some(0));
9132 reloads(&p, "a colour that outlived an undo");
9133
9134 // An equalizer and a grade on one clip are two independent tables.
9135 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
9136 let (_, lanes, eq, color, _) = p.without_orphan_sources();
9137 assert_eq!((eq.len(), color.len()), (1, 1));
9138 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
9139 }
9140
9141 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
9142 /// placement is the clip's, through every edit that copies one.
9143 #[test]
9144 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
9145 let mut p = three();
9146 assert!(
9147 p.transform_of(Lane::V1, 0).is_none(),
9148 "a fresh clip is untransformed"
9149 );
9150 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9151 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9152 assert!(
9153 p.transform_of(Lane::A1, 0).is_none(),
9154 "one clip, not the lane below"
9155 );
9156 assert!(
9157 p.color_of(Lane::V1, 0).is_none(),
9158 "and a placement is not a grade"
9159 );
9160
9161 // Cutting a transformed clip must not transform half of it: both
9162 // halves inherit.
9163 assert!(p.split(1));
9164 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9165 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
9166 assert!(
9167 p.transform_of(Lane::V1, 2).is_none(),
9168 "the clip after it is untransformed"
9169 );
9170
9171 // A clipboard copy carries it -- onto another lane, at that.
9172 let copied = p.lane(Lane::V1)[1];
9173 assert!(p.place(Lane::A1, 20, copied));
9174 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
9175 assert!(p.undo());
9176 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
9177
9178 // ...and a change to one is one undo step, in both directions.
9179 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
9180 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
9181 assert!(p.undo());
9182 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9183 assert!(
9184 p.set_transform(Lane::V1, 0, None),
9185 "and taking it off is an edit"
9186 );
9187 assert!(p.transform_of(Lane::V1, 0).is_none());
9188 assert!(p.undo());
9189 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9190
9191 // Two refusals, neither of which costs an undo step.
9192 let nan = TransformParams {
9193 scale: f32::NAN,
9194 ..transform_at(1)
9195 };
9196 assert!(
9197 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
9198 "no clip there"
9199 );
9200 assert!(
9201 !p.set_transform(Lane::V1, 0, Some(nan)),
9202 "not a finite value"
9203 );
9204 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9205 assert!(p.undo());
9206 assert_eq!(
9207 p.lane(Lane::V1).len(),
9208 3,
9209 "one step back is before the split"
9210 );
9211 assert!(p.undo());
9212 assert!(
9213 p.transform_of(Lane::V1, 0).is_none(),
9214 "and the next is before the placement: the refusals pushed none"
9215 );
9216 }
9217
9218 /// The transform table is append-only within a session, exactly as the eq
9219 /// and colour ones are -- and a save is where an undone placement goes.
9220 #[test]
9221 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
9222 let mut p = three();
9223 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
9224 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9225 assert!(p.undo(), "back to the first placement");
9226 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
9227
9228 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9229 assert_eq!(
9230 transform,
9231 vec![transform_at(1)],
9232 "what nothing plays is not written"
9233 );
9234 assert_eq!(
9235 lanes[0].1[0].transform,
9236 Some(0),
9237 "and the survivor renumbers"
9238 );
9239 assert_eq!(lanes[0].1[1].transform, None);
9240
9241 // One placement on three clips is one entry: settings that are equal
9242 // share.
9243 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
9244 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
9245 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9246 assert_eq!(transform.len(), 1, "equal placements share their entry");
9247 assert_eq!(lanes[1].1[2].transform, Some(0));
9248 reloads(&p, "a transform that outlived an undo");
9249
9250 // A grade and a placement on one clip are two independent tables.
9251 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
9252 let (_, lanes, _, color, transform) = p.without_orphan_sources();
9253 assert_eq!((color.len(), transform.len()), (1, 1));
9254 assert_eq!(
9255 (lanes[0].1[0].color, lanes[0].1[0].transform),
9256 (Some(0), Some(0))
9257 );
9258 }
9259
9260 /// Not a claim about correctness but about cost: a clip is copied on every
9261 /// paste, every undo snapshot and every lane clone, so its size is worth
9262 /// knowing. The eq index fit the padding a `Copy` clip already had; the
9263 /// colour one did not, and the struct grew a word. The transform index is
9264 /// a third `Option<u16>`, and it fits the padding the fit policy and the
9265 /// transition byte already left behind, so the struct did not grow again.
9266 /// The packed visualizer look is a `u64` -- the strand colour has bytes
9267 /// above the clip's own four -- and nothing left in the struct is wide
9268 /// enough to hold it, so it grew a word again.
9269 #[test]
9270 fn a_clip_is_still_a_small_copy() {
9271 assert_eq!(
9272 std::mem::size_of::<Clip>(),
9273 64,
9274 "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"
9275 );
9276 }
9277
9278 #[test]
9279 fn from_parts_has_no_history_and_checks_the_invariants() {
9280 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
9281 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
9282 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
9283 .expect("valid parts");
9284 assert_eq!(p.clips(), three().clips());
9285 assert!(!p.undo(), "a loaded project has nothing to undo");
9286 assert!(p.split(4), "...and is editable from there");
9287 assert!(p.undo());
9288
9289 // A lane may be empty, and so may every lane -- an emptied timeline is a
9290 // project. No lane at all is not one: there would be nothing to place on.
9291 assert!(
9292 Project::from_parts(
9293 sources.clone(),
9294 two(video.clone(), Vec::new()),
9295 Vec::new(),
9296 Vec::new(),
9297 Vec::new(),
9298 )
9299 .is_ok()
9300 );
9301 assert!(
9302 Project::from_parts(
9303 sources.clone(),
9304 two(Vec::new(), Vec::new()),
9305 Vec::new(),
9306 Vec::new(),
9307 Vec::new(),
9308 )
9309 .is_ok()
9310 );
9311 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
9312 let bad: [Vec<Clip>; 5] = [
9313 vec![clip(0, 0, 3, 1)], // source that is not there
9314 vec![clip(0, 3, 3, 0)], // empty clip
9315 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
9316 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
9317 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
9318 ];
9319 for clips in bad {
9320 assert!(
9321 Project::from_parts(
9322 sources.clone(),
9323 two(clips.clone(), Vec::new()),
9324 Vec::new(),
9325 Vec::new(),
9326 Vec::new(),
9327 )
9328 .is_err(),
9329 "{clips:?}"
9330 );
9331 assert!(
9332 Project::from_parts(
9333 sources.clone(),
9334 two(video.clone(), clips.clone()),
9335 Vec::new(),
9336 Vec::new(),
9337 Vec::new(),
9338 )
9339 .is_err()
9340 );
9341 // ...and on a third lane, which is checked by the same walk.
9342 assert!(
9343 Project::from_parts(
9344 sources.clone(),
9345 vec![
9346 (LaneKind::Video, video.clone()),
9347 (LaneKind::Audio, audio.clone()),
9348 (LaneKind::Video, clips),
9349 ],
9350 Vec::new(),
9351 Vec::new(),
9352 Vec::new(),
9353 )
9354 .is_err()
9355 );
9356 }
9357 // An equalizer index no table entry answers, and a table entry the file
9358 // format could not have written, are refused at this door too.
9359 let eqd = |i: u16| {
9360 vec![Clip {
9361 fade_in: 0,
9362 fade_out: 0,
9363 transition_out: 0,
9364 visualizer: 0,
9365 viz_paint: 0,
9366 eq: Some(i),
9367 ..video[0]
9368 }]
9369 };
9370 assert!(
9371 Project::from_parts(
9372 sources.clone(),
9373 two(eqd(0), Vec::new()),
9374 Vec::new(),
9375 Vec::new(),
9376 Vec::new(),
9377 )
9378 .is_err()
9379 );
9380 let mut nan = band_at(1);
9381 nan.bands[0].freq_hz = f32::NAN;
9382 assert!(
9383 Project::from_parts(
9384 sources.clone(),
9385 two(eqd(0), Vec::new()),
9386 vec![nan],
9387 Vec::new(),
9388 Vec::new(),
9389 )
9390 .is_err()
9391 );
9392 let loaded = Project::from_parts(
9393 sources.clone(),
9394 two(eqd(0), Vec::new()),
9395 vec![band_at(1)],
9396 Vec::new(),
9397 Vec::new(),
9398 )
9399 .expect("an eq the table holds");
9400 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
9401
9402 // The same two refusals for a colour, at the same door.
9403 let graded = |i: u16| {
9404 vec![Clip {
9405 fade_in: 0,
9406 fade_out: 0,
9407 transition_out: 0,
9408 visualizer: 0,
9409 viz_paint: 0,
9410 color: Some(i),
9411 fit: FitPolicy::default(),
9412 speed: Speed::NORMAL,
9413 ..video[0]
9414 }]
9415 };
9416 assert!(
9417 Project::from_parts(
9418 sources.clone(),
9419 two(graded(0), Vec::new()),
9420 Vec::new(),
9421 Vec::new(),
9422 Vec::new(),
9423 )
9424 .is_err(),
9425 "a colour index no entry answers"
9426 );
9427 assert!(
9428 Project::from_parts(
9429 sources.clone(),
9430 two(graded(0), Vec::new()),
9431 Vec::new(),
9432 vec![ColorParams {
9433 tint: f32::NAN,
9434 ..grade_at(1)
9435 }],
9436 Vec::new(),
9437 )
9438 .is_err(),
9439 "a value the file format could not have written"
9440 );
9441 let loaded = Project::from_parts(
9442 sources.clone(),
9443 two(graded(0), Vec::new()),
9444 Vec::new(),
9445 vec![grade_at(1)],
9446 Vec::new(),
9447 )
9448 .expect("a colour the table holds");
9449 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
9450
9451 // Group ids survive a load, and the next split gets a fresh one.
9452 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
9453 assert!(p.split(4));
9454 assert!(p.clips().iter().all(|c| c.link.is_some()));
9455 }
9456
9457 /// The grouping rules, at the untrusted door and after every edit that can
9458 /// touch a link. A link id is at most one placement per lane -- a clip or a
9459 /// caption, whichever carries it -- and no sequence of edits may produce
9460 /// otherwise, because what an edit produces is what a save writes and a load
9461 /// reads.
9462 ///
9463 /// Amended for the offset-preserving group: the members keep their own
9464 /// spans, so two placements of one id covering different frames is *legal*
9465 /// -- it is what a hand-built group is -- and the only refusal left is the
9466 /// doubled id inside one lane.
9467 #[test]
9468 fn a_link_id_is_never_two_clips_of_one_lane() {
9469 let sources = vec![Source::new(FILE, 0)];
9470 let linked = |start, in_frame, out_frame, link| Clip {
9471 fade_in: 0,
9472 fade_out: 0,
9473 transition_out: 0,
9474 visualizer: 0,
9475 viz_paint: 0,
9476 start,
9477 in_frame,
9478 out_frame,
9479 source: 0,
9480 link: Some(link),
9481 eq: None,
9482 color: None,
9483 transform: None,
9484 fit: FitPolicy::default(),
9485 speed: Speed::NORMAL,
9486 };
9487
9488 // The door: a doubled id inside one lane, refused by name.
9489 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
9490 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
9491 .expect_err("refused")
9492 .to_string()
9493 };
9494 assert!(
9495 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
9496 .contains("link 7 names two clips in the V1 lane"),
9497 "a duplicate id inside one lane is refused by name"
9498 );
9499 // ...and the same doubling on a subtitle lane, in its own words: a
9500 // caption is the other placement an id may name.
9501 let caption = |start: u32, frames: u32, link| SubClip {
9502 start,
9503 frames,
9504 track: 0,
9505 in_us: 0,
9506 out_us: i64::from(frames) * 1_000_000,
9507 link: Some(link),
9508 };
9509 let subs = LaneData {
9510 clips: Vec::new(),
9511 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
9512 ..LaneData::new(LaneKind::Subtitle, Vec::new())
9513 };
9514 assert_eq!(
9515 links_are_consistent(&[subs]).unwrap_err().to_string(),
9516 "link 7 names two captions in the S1 lane"
9517 );
9518 // A pair covering *different* frames is legal now: the members of a
9519 // hand-built group keep their own spans, and what binds them is the id.
9520 let apart = Project::from_parts(
9521 sources.clone(),
9522 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
9523 Vec::new(),
9524 Vec::new(),
9525 Vec::new(),
9526 );
9527 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
9528 // A one-sided link is *not* an error: it is what a lift leaves behind.
9529 let mut p = Project::single(FILE, 9);
9530 assert!(p.lift(Lane::A1, 0));
9531 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
9532 assert!(
9533 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
9534 "a lifted lane's project has to load again"
9535 );
9536
9537 // The edits: nothing below may break either rule.
9538 let consistent = |p: &Project, what: &str| {
9539 assert!(
9540 links_are_consistent(&p.lanes).is_ok(),
9541 "{what}: {:?}",
9542 p.lanes
9543 );
9544 };
9545 let mut p = three();
9546 let copied = p.clips()[0];
9547 assert!(
9548 copied.link.is_some(),
9549 "the clipboard clip carries its group"
9550 );
9551 assert!(p.lift(Lane::V1, 0));
9552 assert!(p.place(Lane::V1, 0, copied));
9553 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
9554 assert_eq!(
9555 p.clips().iter().filter(|c| c.link == copied.link).count(),
9556 0,
9557 "a placement belongs to no group, so it cannot duplicate one"
9558 );
9559 consistent(&p, "lift + place twice");
9560 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
9561 consistent(&p, "place through a grouped clip");
9562 assert!(p.paste(6, copied), "a rippling paste through another");
9563 consistent(&p, "paste");
9564 assert!(p.split(2));
9565 consistent(&p, "split");
9566 assert!(p.ripple_delete(1, 3));
9567 consistent(&p, "ripple_delete");
9568 assert!(p.undo());
9569 consistent(&p, "undo");
9570 }
9571
9572 /// What an edit produces is what a save writes, so *every* state the public
9573 /// API can reach has to load again. The two the verifier panel found where
9574 /// it did not: a split and a regroup handed one group id to two clips that
9575 /// were not the same span, because the lanes had been edited apart.
9576 #[test]
9577 fn every_reachable_state_reloads() {
9578 let mut p = Project::single(FILE, 150);
9579 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
9580 assert!(p.split(10), "the lanes are cut apart at 10");
9581 reloads(&p, "place on one lane, then split");
9582
9583 let mut p = Project::single(FILE, 150);
9584 assert!(p.split(30));
9585 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
9586 assert!(p.regroup(30), "only the audio lane can rejoin");
9587 assert!(p.split(60));
9588 reloads(&p, "lift, regroup one lane, split");
9589
9590 // Two audio streams of one file, both placed: two source entries with
9591 // one path between them, which is the state a stream picked out of the
9592 // library reaches -- and the state a save has to write and read back.
9593 let mut p = Project::single(FILE, 150);
9594 let second = p.import(FILE, 1);
9595 assert_eq!(second, 1, "the same file on another stream is a new source");
9596 assert!(p.append_clip(second, 150));
9597 assert!(p.split(200));
9598 reloads(
9599 &p,
9600 "a second audio stream of the same file, placed and split",
9601 );
9602 let (sources, ..) = p.without_orphan_sources();
9603 assert_eq!(
9604 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
9605 [0, 1],
9606 "both entries survive the orphan prune: both are played"
9607 );
9608 }
9609
9610 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
9611 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
9612 /// is the stamp playback puts on a decoded source frame -- and the *last*
9613 /// source frame the pump is still holding at a timeline frame has to be
9614 /// exactly the one the export encoded there, at every rate. Anything else is
9615 /// A/V drift that grows with the clip, and no test of either side alone
9616 /// would see it.
9617 ///
9618 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
9619 /// is a better answer than the floor/floor this had: floor/floor put the
9620 /// preview a whole held frame off the export at slow rates.)
9621 #[test]
9622 fn speed_maps_both_ways() {
9623 for permille in (250..=4000).step_by(1) {
9624 let speed = Speed::from_permille(permille);
9625 assert_eq!(speed.permille(), permille, "no clamping in range");
9626 for d in 0..200u32 {
9627 let want = speed.source_at(d);
9628 // What the pump shows at `d` is the last frame whose stamp has
9629 // come due -- and it is `want`, the frame the export encodes
9630 // there. Slowed, that is the frame it is still holding; sped up,
9631 // it is the newest of the several that arrived.
9632 let held = (0..=want + 8)
9633 .filter(|&s| speed.timeline_at(s) <= d)
9634 .next_back();
9635 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
9636 }
9637 for n in 1..300u32 {
9638 // A footprint is never zero: a clip occupying no timeline frame
9639 // is a placement the lane invariants cannot hold.
9640 let frames = speed.frames(n);
9641 assert!(frames >= 1, "{speed} of {n} frames");
9642 // ...and its last timeline frame never reads past the clip.
9643 assert!(
9644 speed.source_at(frames - 1) < n,
9645 "{speed}: the last timeline frame of {n} reads past the clip"
9646 );
9647 // The trim inverse never overshoots the room it was given, and
9648 // answers for every room a footprint can be.
9649 let fit = speed.fit(frames).expect("a clip fits its own footprint");
9650 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
9651 // A room narrower than one source frame's own footprint holds
9652 // nothing, and says so rather than rounding something into it.
9653 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
9654 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
9655 }
9656 }
9657 // Real time is the identity map, byte for byte.
9658 for d in 0..1000 {
9659 assert_eq!(Speed::NORMAL.source_at(d), d);
9660 assert_eq!(Speed::NORMAL.timeline_at(d), d);
9661 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
9662 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
9663 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
9664 }
9665 // The one door: no zero, no reverse, nothing past the ends.
9666 assert_eq!(Speed::from_permille(0), Speed::MIN);
9667 assert_eq!(Speed::from_permille(249), Speed::MIN);
9668 assert_eq!(Speed::from_permille(4001), Speed::MAX);
9669 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
9670 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
9671 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
9672 }
9673
9674 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
9675 /// export encodes at a timeline frame is the one playback is holding there,
9676 /// a file is as long in timeline frames as the seconds it lasts, and the two
9677 /// compose so a speeded clip at another rate is exactly both.
9678 #[test]
9679 fn rate_composes_with_speed() {
9680 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
9681 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
9682 // the identity map or a single-rate project would move.
9683 for (source_fps, timeline_fps) in [
9684 (24000. / 1001., 30.),
9685 (30., 24000. / 1001.),
9686 (60., 30.),
9687 (25., 30.),
9688 (30., 30.),
9689 ] {
9690 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
9691 for n in 0..2000u32 {
9692 let source = rate.source_at(n);
9693 // The stamp is the *first* timeline-rate frame that shows it, so
9694 // the picture on screen at `n` is the picture encoded at `n`.
9695 let held = (0..=source + 4)
9696 .filter(|&s| rate.timeline_at(s) <= n)
9697 .next_back();
9698 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
9699 }
9700 // A file of `count` frames is `timeline_at(count)` frames long here,
9701 // and its last one still reads a frame the file has.
9702 for count in 1..500u32 {
9703 let frames = rate.timeline_at(count);
9704 assert!(frames >= 1, "a file is never zero frames long");
9705 assert!(
9706 rate.source_at(frames - 1) < count,
9707 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
9708 );
9709 }
9710 // No drift: the mapping is one exact division of the *rate itself*,
9711 // not an accumulation and not a rounded rate, so an hour in is as
9712 // true as the first second. (Held to the real ratio of the two rates
9713 // the caller asked for -- `as_f64` would be true of a wrong rate.)
9714 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
9715 let want = f64::from(n) * source_fps / timeline_fps;
9716 assert!(
9717 (f64::from(rate.source_at(n)) - want).abs() < 1.,
9718 "{source_fps} on {timeline_fps}: frame {n} drifted"
9719 );
9720 }
9721 }
9722 // The timeline's own rate is the identity, whichever way it is written.
9723 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
9724 assert!(
9725 Rate::from_fps(30.0004, 30.)
9726 .expect("30.0004 over 30")
9727 .is_real_time(),
9728 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
9729 );
9730 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
9731 // one thing `matches_timeline` refuses a file for now that the rate gate
9732 // is gone.
9733 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
9734 assert!(Rate::from_fps(30., f64::NAN).is_err());
9735 for n in 0..1000 {
9736 assert_eq!(Rate::REAL_TIME.source_at(n), n);
9737 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
9738 }
9739 // ...and the composition, in the order the decoder's door applies it:
9740 // the speed picks the clip's (timeline-rate) frame, the rate picks the
9741 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
9742 // timeline frames per frame shown, each of them exactly 800/1001 of a
9743 // file frame.
9744 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
9745 let speed = Speed::from_permille(2000);
9746 for d in 0..100u32 {
9747 assert_eq!(
9748 rate.source_at(speed.source_at(d)),
9749 (u64::from(d) * 2 * 800 / 1001) as u32,
9750 "2x of a 23.976 fps file at timeline frame {d}"
9751 );
9752 }
9753 }
9754
9755 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
9756 /// source frames per timeline frame and still starts at its own in-point,
9757 /// and a half-speed one shows every source frame twice.
9758 #[test]
9759 fn a_rate_maps_timeline_frames_onto_source_frames() {
9760 let mut p = Project::single(FILE, 40);
9761 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9762 .expect("room enough");
9763 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
9764 assert_eq!(
9765 p.map(Lane::V1, 0),
9766 Some((0, 0)),
9767 "and it starts where it did"
9768 );
9769 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
9770 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
9771 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
9772 // The span a decoder is handed: as many source frames as it will read,
9773 // which is the last shown frame's own and not one more -- timeline frame
9774 // 19 shows source frame 38, so 39 frames are read and the 40th is a
9775 // picture nothing would display.
9776 let span = p.span_at(Lane::V1, 0).expect("a span");
9777 assert_eq!((span.len, span.source_len()), (20, 39));
9778 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
9779 // ...and the same clip the other way round.
9780 let mut p = Project::single(FILE, 40);
9781 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9782 .expect("room enough");
9783 assert_eq!(p.timeline_frames(), 80);
9784 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
9785 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
9786 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
9787 assert_eq!(
9788 p.map(Lane::V1, 79),
9789 Some((0, 39)),
9790 "and the last timeline frame is still inside the source range"
9791 );
9792 }
9793
9794 /// A trim of a speeded clip is still a trim of its *source*, and the edge
9795 /// still stops at the wall: the room a rate leaves is measured in timeline
9796 /// frames and the range it commits in source ones.
9797 #[test]
9798 fn trimming_a_speeded_clip_stays_inside_its_room() {
9799 let mut p = Project::single(FILE, 40);
9800 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9801 .expect("room enough");
9802 // A second clip butted against the first, so the wall is a real one.
9803 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
9804 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
9805 assert_eq!(room, (1, 20), "out to the neighbour and no further");
9806 assert!(
9807 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
9808 "clamped to the wall, which is where the edge already is"
9809 );
9810 let c = p.clips()[0];
9811 assert_eq!(c.end(), 20, "so nothing moved");
9812 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
9813 // ...and in: half the timeline frames is half the source range.
9814 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
9815 let c = p.clips()[0];
9816 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
9817 assert_eq!(c.end(), 10, "and ten timeline frames of them");
9818 assert!(sorted_disjoint(p.clips()));
9819 }
9820
9821 /// The frames a rate cannot address: at half speed each source frame is on
9822 /// screen twice, and the cut between the two showings is not a cut in the
9823 /// file. Refused, so the two halves always add up to the clip that was cut.
9824 #[test]
9825 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
9826 let mut p = Project::single(FILE, 10);
9827 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9828 .expect("room enough");
9829 assert_eq!(p.timeline_frames(), 20);
9830 assert!(
9831 !p.split(3),
9832 "an odd frame is between two showings of one frame"
9833 );
9834 assert_eq!(p.clips().len(), 1, "and nothing was cut");
9835 assert!(p.split(4), "an even one is a frame boundary");
9836 let halves = p.clips().to_vec();
9837 assert_eq!(
9838 (halves[0].end(), halves[1].start, halves[1].end()),
9839 (4, 4, 20),
9840 "the halves meet, and still end where the clip did"
9841 );
9842 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
9843 assert!(p.regroup(4), "and the inverse puts it back");
9844 assert_eq!(p.clips().len(), 1);
9845 }
9846
9847 /// The same claim, swept: random op sequences off the public surface, the
9848 /// project reloaded after every one of them. A failure prints its seed, and
9849 /// the seed replays the whole sequence.
9850 #[test]
9851 fn random_edit_sequences_reload() {
9852 // Two thousand, not two hundred: the overlap a hole punched into a slow
9853 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
9854 // sequences, and a 200-seed sweep walked straight past it (it took a
9855 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
9856 // has no business being the narrow one.
9857 for seed in 0..2000u64 {
9858 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9859 let mut next = move |n: u32| {
9860 // xorshift64*: no dependency, and the seed replays it exactly.
9861 rng ^= rng << 13;
9862 rng ^= rng >> 7;
9863 rng ^= rng << 17;
9864 (rng >> 33) as u32 % n
9865 };
9866 let mut p = Project::single(FILE, 40);
9867 for step in 0..24 {
9868 let frame = next(44);
9869 // A clipboard copy carries the group id of the take it came from
9870 // -- the input that made a placement duplicate an id -- and, one
9871 // time in three, a rate of its own: a *speeded clip placed over
9872 // a speeded clip* is the shape whose remainders have to be run
9873 // through `Speed::fit`, and it is not a shape the lanes hand out
9874 // on their own often enough to be sure of.
9875 let mut copied = *p
9876 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
9877 .get(next(4) as usize)
9878 .unwrap_or(&clip(0, 0, 5, 0));
9879 if next(3) == 0 {
9880 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
9881 }
9882 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
9883 let idx = next(4) as usize;
9884 let _ = match next(16) {
9885 // A clip dragged along its own lane to wherever the pointer
9886 // let it go: the op that moves a placement without changing
9887 // what it plays, so what it may not do is land on top of the
9888 // neighbour it was dragged at.
9889 15 => p.move_clip(lane, idx, lane, frame),
9890 // ...and a second `place`, so a punch lands inside a clip
9891 // far more often than one op in fourteen would put it there.
9892 14 => p.place(lane, frame, copied),
9893 0 => p.split(frame),
9894 1 => p.regroup(frame),
9895 2 => p.lift(lane, idx),
9896 3 => p.place(lane, frame, copied),
9897 4 => p.paste(frame, copied),
9898 5 => p.ripple_delete(frame, next(9)),
9899 6 => p.delete(idx),
9900 7 => p.undo(),
9901 // An equalizer put on and taken off in the mix: what a clip
9902 // carries has to reload with it, and the entries an undo
9903 // orphans must not come back out of the prune.
9904 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9905 9 => p.set_eq(lane, idx, None),
9906 // ...and a colour grade in the same mix, for the same
9907 // reason: it rides on the clip and its orphans must go.
9908 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
9909 11 => p.set_color(lane, idx, None),
9910 // ...and a rate in with them, which is the one of the three
9911 // that moves *placements*: a clip that grew has to be
9912 // refused rather than overlap, and one that shrank leaves a
9913 // lane that still loads. Both are what `reloads` asks.
9914 12 => p
9915 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9916 .is_ok(),
9917 _ => p.append_clip(0, 1 + next(9)),
9918 };
9919 reloads(&p, &format!("seed {seed}, step {step}"));
9920 }
9921 }
9922 }
9923
9924 /// The save/load round trip a project must survive: the parts a save writes,
9925 /// handed back to the constructor a load goes through -- every lane of them,
9926 /// and the reloaded timeline has to be the same lanes in the same order.
9927 fn reloads(p: &Project, what: &str) {
9928 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
9929 match Project::from_parts(sources, lanes, eq, color, transform) {
9930 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
9931 Ok(back) => {
9932 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
9933 // Placements, not whole clips: an orphan prune renumbers the
9934 // sources a clip names, which is the point of it.
9935 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
9936 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
9937 };
9938 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
9939 // The prune renumbers the eq table too, so what has to survive
9940 // is the settings themselves, clip by clip.
9941 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
9942 p.lanes()
9943 .into_iter()
9944 .map(|l| {
9945 (0..p.lane(l).len())
9946 .map(|i| p.eq_of(l, i).cloned())
9947 .collect()
9948 })
9949 .collect()
9950 };
9951 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
9952 // The colour table renumbers in the same prune, so the same
9953 // claim: the params a clip names, not the index it names them by.
9954 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
9955 p.lanes()
9956 .into_iter()
9957 .map(|l| {
9958 (0..p.lane(l).len())
9959 .map(|i| p.color_of(l, i).copied())
9960 .collect()
9961 })
9962 .collect()
9963 };
9964 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
9965 // ...and the transform table, by the same claim again.
9966 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
9967 p.lanes()
9968 .into_iter()
9969 .map(|l| {
9970 (0..p.lane(l).len())
9971 .map(|i| p.transform_of(l, i).copied())
9972 .collect()
9973 })
9974 .collect()
9975 };
9976 assert_eq!(
9977 transforms(&back),
9978 transforms(p),
9979 "{what}: the transforms changed"
9980 );
9981 }
9982 }
9983 }
9984
9985 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
9986 /// -- each one sorted and disjoint, and one span per group id -- asserted
9987 /// directly, where the point is the invariant rather than the round trip.
9988 fn invariants_hold(p: &Project, what: &str) {
9989 for lane in p.lanes() {
9990 assert!(
9991 sorted_disjoint(p.lane(lane)),
9992 "{what}: {} is out of order or overlaps itself: {:?}",
9993 lane.label(),
9994 p.lane(lane)
9995 );
9996 }
9997 if let Err(e) = links_are_consistent(&p.lanes) {
9998 panic!("{what}: {e}\n{:?}", p.lanes);
9999 }
10000 }
10001
10002 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
10003 /// edited without any other lane hearing about it. A handle naming a lane
10004 /// that is not there reads as empty and refuses to mutate.
10005 #[test]
10006 fn a_third_lane_is_a_peer() {
10007 let mut p = three();
10008 assert_eq!(p.lane_count(LaneKind::Video), 1);
10009 assert_eq!(p.lane_count(LaneKind::Audio), 1);
10010 let v2 = p.add_lane(LaneKind::Video);
10011 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
10012 assert_eq!(v2.label(), "V2");
10013 assert_eq!(p.lane_count(LaneKind::Video), 2);
10014 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
10015 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
10016
10017 // A handle for a lane that is not there: empty, and no mutation takes.
10018 let v3 = Lane::new(LaneKind::Video, 2);
10019 assert!(p.lane(v3).is_empty());
10020 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
10021 assert!(!p.lift(v3, 0));
10022 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
10023
10024 // Placing on V2 moves nothing else, and the lane can outrun the rest.
10025 let before = shape(&p);
10026 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10027 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
10028 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
10029 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
10030 assert_eq!(
10031 p.timeline_frames(),
10032 16,
10033 "the last lane to end sets the length"
10034 );
10035 assert_eq!(p.map(v2, 5), Some((0, 21)));
10036 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
10037 assert_eq!(
10038 p.span_at(v2, 0),
10039 Some(Span {
10040 start: 0,
10041 len: 4,
10042 from: None,
10043 speed: Speed::NORMAL
10044 })
10045 );
10046 // Every lane still covers the whole timeline, gaps included.
10047 for l in p.lanes() {
10048 let spans = p.spans_from(l, 0);
10049 assert_eq!(
10050 spans.iter().map(|s| s.len).sum::<u32>(),
10051 16,
10052 "{}",
10053 l.label()
10054 );
10055 }
10056 // ...and playback still reads V1 and A1, whatever else is there.
10057 assert_eq!(p.clips(), p.lane(Lane::V1));
10058 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
10059 let segments = p.segments_from(0, FPS);
10060 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
10061 assert_eq!(
10062 segments[3],
10063 (None, 0.0, 7.0 / FPS),
10064 "A1 keeps the clock counting over the picture V2 added"
10065 );
10066 invariants_hold(&p, "place on V2");
10067
10068 // A lift is that lane's business too, and the lane list undoes.
10069 assert!(p.lift(v2, 0));
10070 assert!(p.lane(v2).is_empty());
10071 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
10072 assert!(p.undo());
10073 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
10074 assert!(p.undo());
10075 assert!(p.lane(v2).is_empty(), "the placement came off V2");
10076 assert!(p.undo(), "and one more step takes the lane itself back");
10077 assert_eq!(p.lane_count(LaneKind::Video), 1);
10078 assert_eq!(shape(&p), shape(&three()));
10079 }
10080
10081 /// The add taken back: an empty lane comes off, a lane holding clips never
10082 /// does (and says which clips), the last lane of a kind never does, the
10083 /// lanes below the one that went move up an `ord`, and one undo puts it
10084 /// back where it stood.
10085 #[test]
10086 fn an_empty_lane_comes_off_again() {
10087 let mut p = three();
10088 let v2 = p.add_lane(LaneKind::Video);
10089 let v3 = p.add_lane(LaneKind::Video);
10090 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
10091 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
10092 let history = p.history.len();
10093
10094 // The last lane of its kind stays: `V1`/`A1` are where an import and a
10095 // paste land, and a project missing one would swallow half of a file
10096 // dropped on it.
10097 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
10098 assert_eq!(
10099 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
10100 "there is no V10 to remove"
10101 );
10102
10103 // A lane with clips on it refuses and names them: a track removal never
10104 // deletes a take.
10105 let refusal = why(p.remove_lane(v3));
10106 assert!(refusal.contains("V3 still holds"), "{refusal}");
10107 assert!(refusal.contains(FILE), "{refusal}");
10108 assert!(refusal.contains("at frame 0"), "{refusal}");
10109 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
10110 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
10111
10112 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
10113 // all.
10114 p.remove_lane(v2).expect("V2 is empty");
10115 assert_eq!(p.lane_count(LaneKind::Video), 2);
10116 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
10117 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
10118 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
10119 invariants_hold(&p, "remove V2");
10120
10121 // ...and one stroke puts the empty lane back above it.
10122 assert!(p.undo());
10123 assert_eq!(p.lane_count(LaneKind::Video), 3);
10124 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
10125 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
10126 }
10127
10128 /// A track dragged to another place in the stack: the whole lane travels --
10129 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
10130 /// a video one, a lane that crosses one of its own kind swaps names with it
10131 /// (and swaps the composite with it), one undo puts the order back, and a
10132 /// save carries it.
10133 #[test]
10134 fn a_track_is_dragged_to_another_place_in_the_stack() {
10135 let mut p = three();
10136 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
10137 let before = shape(&p);
10138 let history = p.history.len();
10139
10140 // A1 over V1: the screen is rearranged and nothing else is. Both keep
10141 // their names -- neither crossed a lane of its own kind -- so every
10142 // handle a front-end holds still names the track it named before.
10143 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
10144 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
10145 assert_eq!(
10146 shape(&p),
10147 vec![before[1].clone(), before[0].clone()],
10148 "each lane's clips travelled with it, and none was remapped"
10149 );
10150 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
10151 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
10152 invariants_hold(&p, "A1 over V1");
10153
10154 // Nothing moves for a lane that is not there, a slot that is not, or a
10155 // lane already standing in the one it was pointed at.
10156 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
10157 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
10158 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
10159 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
10160
10161 // ...and one stroke puts the order back.
10162 assert!(p.undo());
10163 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
10164 assert_eq!(shape(&p), before);
10165
10166 // A second video lane over the first: display order *is* the stack, so
10167 // the last video lane covering a frame is the picture that shows.
10168 let v2 = p.add_lane(LaneKind::Video);
10169 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
10170 let over = shape(&p)[2].clone();
10171 assert_eq!(
10172 p.composite_span_at(0).map(|s| s.len),
10173 Some(5),
10174 "V2's five frames are what frame 0 shows"
10175 );
10176
10177 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
10178 // a position among the lanes of its kind. The picture that wins changes
10179 // with it: the take that was covering is the covered one now.
10180 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
10181 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
10182 assert_eq!(
10183 shape(&p),
10184 vec![over.clone(), before[0].clone(), before[1].clone()],
10185 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
10186 );
10187 assert_eq!(
10188 p.composite_span_at(0).map(|s| s.len),
10189 Some(3),
10190 "the lower video lane wins, and it is the old V1 now"
10191 );
10192 invariants_hold(&p, "V2 over V1");
10193
10194 // A save writes that order and a load takes it back.
10195 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10196 assert_eq!(
10197 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10198 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
10199 );
10200 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
10201 assert_eq!(back.lanes(), p.lanes());
10202 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
10203
10204 assert!(p.undo(), "and the stack goes back to how it stood");
10205 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
10206 }
10207
10208 /// The grouping rule across more than two lanes, under the offset model: a
10209 /// split *keeps* the group on the left halves and hands the right halves of
10210 /// that group one fresh id of their own -- a clip in no group comes out of
10211 /// the cut in none. So a take cut apart is two takes, one per side, and a
10212 /// lane that was never part of it stays out of both.
10213 #[test]
10214 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
10215 let mut p = Project::single(FILE, 9);
10216 let take = p.clips()[0].link.expect("a fresh project is one take");
10217 let v2 = p.add_lane(LaneKind::Video);
10218 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
10219 assert!(p.split(4));
10220 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
10221 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
10222 };
10223 let (left, right) = (side(&p, 0), side(&p, 1));
10224 // The lanes in order are V1, A1, V2: the take's two keep its id on the
10225 // left, and the placed clip never had one for the cut to keep.
10226 assert_eq!(
10227 left,
10228 vec![Some(take), Some(take), None],
10229 "the left halves keep the take"
10230 );
10231 // ...and the right halves of that take are one fresh group.
10232 assert_eq!(right[0], right[1]);
10233 assert_ne!(right[0], Some(take));
10234 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
10235 invariants_hold(&p, "split across three lanes");
10236
10237 // V2 ends early: the left halves still keep what each clip carried --
10238 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
10239 // shared by exactly the take's lanes.
10240 let mut p = Project::single(FILE, 9);
10241 let v2 = p.add_lane(LaneKind::Video);
10242 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
10243 assert!(p.split(3));
10244 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
10245 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
10246 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
10247 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
10248 invariants_hold(&p, "split where one lane ends early");
10249
10250 // The inverse rejoins each lane into the group its left half kept.
10251 assert!(p.regroup(3));
10252 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
10253 assert_eq!(
10254 p.lane(Lane::V1)[0].link,
10255 Some(take),
10256 "the take's id is back, not a fresh one"
10257 );
10258 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
10259 invariants_hold(&p, "regroup across three lanes");
10260 }
10261
10262 /// A group is one placement per lane, on however many lanes carry the id --
10263 /// not a video/audio pair and not a pairing by `ord` -- and the members may
10264 /// cover whatever frames they cover: the offset between them is what a
10265 /// hand-built group keeps. Lanes built by hand, because the rule is checked
10266 /// at the untrusted door and no edit can produce the one thing it refuses.
10267 #[test]
10268 fn a_group_may_span_any_lane() {
10269 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
10270 let one = |start: u32, end: u32, link| Clip {
10271 fade_in: 0,
10272 fade_out: 0,
10273 transition_out: 0,
10274 visualizer: 0,
10275 viz_paint: 0,
10276 start,
10277 in_frame: start,
10278 out_frame: end,
10279 source: 0,
10280 link: Some(link),
10281 eq: None,
10282 color: None,
10283 transform: None,
10284 fit: FitPolicy::default(),
10285 speed: Speed::NORMAL,
10286 };
10287 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
10288 let kinds = [
10289 LaneKind::Video,
10290 LaneKind::Audio,
10291 LaneKind::Video,
10292 LaneKind::Audio,
10293 ];
10294 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
10295 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
10296 };
10297 let take = || vec![one(0, 4, 7)];
10298 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
10299 // The same take on V1 + A2 only, the lanes between it empty: legal, the
10300 // way a lifted half is legal.
10301 let across = build([take(), Vec::new(), Vec::new(), take()]);
10302 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
10303 // ...and so is a group whose members disagree about their spans: the
10304 // offset between them is the hand's business, not the loader's.
10305 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
10306 assert!(
10307 links_are_consistent(&apart).is_ok(),
10308 "[0, 4) on V1 and [2, 6) on A2 are one group"
10309 );
10310 // One id twice in one lane is still that lane's error, by name.
10311 let twice = build([
10312 Vec::new(),
10313 Vec::new(),
10314 vec![one(0, 4, 7), one(4, 8, 7)],
10315 Vec::new(),
10316 ]);
10317 assert_eq!(
10318 links_are_consistent(&twice).unwrap_err().to_string(),
10319 "link 7 names two clips in the V2 lane"
10320 );
10321 }
10322
10323 /// Every lane a save writes comes out, in display order and with its kind --
10324 /// an empty one included, since it is state a front-end shows -- and a
10325 /// two-lane project still writes exactly the parts it always did.
10326 #[test]
10327 fn a_save_writes_every_lane_it_has() {
10328 let mut p = three();
10329 let before = p.without_orphan_sources();
10330 assert_eq!(before.1.len(), 2, "V1 and A1");
10331 let v2 = p.add_lane(LaneKind::Video);
10332 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10333 let a2 = p.add_lane(LaneKind::Audio);
10334 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10335 assert_eq!(
10336 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10337 [
10338 LaneKind::Video,
10339 LaneKind::Audio,
10340 LaneKind::Video,
10341 LaneKind::Audio
10342 ],
10343 "display order, not video-then-audio"
10344 );
10345 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
10346 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
10347 // ...and all four load again as the same four.
10348 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
10349 assert_eq!(back.lanes(), p.lanes());
10350 assert_eq!(back.lane(a2), p.lane(a2));
10351
10352 // Taking the lanes back leaves exactly what a two-lane save wrote.
10353 for _ in 0..3 {
10354 assert!(p.undo());
10355 }
10356 assert_eq!(
10357 p.without_orphan_sources(),
10358 before,
10359 "byte for byte the same parts a two-lane save always wrote"
10360 );
10361 }
10362
10363 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
10364 /// three lanes and grows more: every lane's own order and the one
10365 /// span-per-id rule after every op, *and* the reload the v4 format restored
10366 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
10367 /// project of any number of lanes.
10368 #[test]
10369 fn random_edit_sequences_keep_many_lanes_consistent() {
10370 for seed in 0..2000u64 {
10371 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
10372 let mut next = move |n: u32| {
10373 rng ^= rng << 13;
10374 rng ^= rng >> 7;
10375 rng ^= rng << 17;
10376 (rng >> 33) as u32 % n
10377 };
10378 let mut p = Project::single(FILE, 40);
10379 let v2 = p.add_lane(LaneKind::Video);
10380 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
10381 let lanes = [Lane::V1, Lane::A1, v2];
10382 for step in 0..24 {
10383 let frame = next(44);
10384 let copied = *p
10385 .lane(lanes[next(3) as usize])
10386 .get(next(4) as usize)
10387 .unwrap_or(&clip(0, 0, 5, 0));
10388 let lane = lanes[next(3) as usize];
10389 let idx = next(4) as usize;
10390 let _ = match next(14) {
10391 // The drag, in the mix: a clip dragged along its own lane
10392 // and onto another one, at a frame the pointer picked --
10393 // which is where the group rule and the sorted+disjoint one
10394 // meet, since every half travels the same distance.
10395 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
10396 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
10397 11 => p.set_eq(lane, idx, None),
10398 // A rate, which on many lanes is the group rule as well:
10399 // every clip carrying the link moves together or none of
10400 // them does, and `invariants_hold` is what says so.
10401 12 => p
10402 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
10403 .is_ok(),
10404 0 => p.split(frame),
10405 1 => p.regroup(frame),
10406 2 => p.lift(lane, idx),
10407 3 => p.place(lane, frame, copied),
10408 4 => p.paste(frame, copied),
10409 5 => p.ripple_delete(frame, next(9)),
10410 6 => p.delete(idx),
10411 7 => p.undo(),
10412 8 => {
10413 p.add_lane(if next(2) == 0 {
10414 LaneKind::Video
10415 } else {
10416 LaneKind::Audio
10417 });
10418 true
10419 }
10420 _ => p.append_clip(0, 1 + next(9)),
10421 };
10422 invariants_hold(&p, &format!("seed {seed}, step {step}"));
10423 reloads(&p, &format!("seed {seed}, step {step}"));
10424 }
10425 }
10426 }
10427
10428 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
10429 /// there, `V1` shows again on either side of it, and a frame no video lane
10430 /// covers is a gap however many lanes there are.
10431 #[test]
10432 fn the_composite_is_the_topmost_lane_with_a_clip() {
10433 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10434 let lanes = vec![
10435 // V1: the whole 30 frames of source 0.
10436 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10437 // V2: source 1 over the middle third.
10438 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
10439 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10440 ];
10441 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10442 assert_eq!(
10443 p.composite_spans_from(0),
10444 vec![
10445 Span {
10446 start: 0,
10447 len: 10,
10448 from: Some((0, 0)),
10449 speed: Speed::NORMAL
10450 },
10451 Span {
10452 start: 10,
10453 len: 10,
10454 from: Some((1, 5)),
10455 speed: Speed::NORMAL
10456 },
10457 Span {
10458 start: 20,
10459 len: 10,
10460 from: Some((0, 20)),
10461 speed: Speed::NORMAL
10462 },
10463 ],
10464 "V2 takes over for its own span and hands V1 back"
10465 );
10466 // A mid-span ask resolves the same way, which is what a seek does.
10467 assert_eq!(
10468 p.composite_span_at(15),
10469 Some(Span {
10470 start: 15,
10471 len: 5,
10472 from: Some((1, 10)),
10473 speed: Speed::NORMAL
10474 })
10475 );
10476 assert_eq!(p.composite_span_at(30), None, "past the end");
10477
10478 // A hole in V1 under V2's clip: black between the two, and black after
10479 // both run out (the audio lane is still holding the timeline open).
10480 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10481 let holed = vec![
10482 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
10483 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
10484 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10485 ];
10486 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
10487 assert_eq!(
10488 p.composite_spans_from(0),
10489 vec![
10490 Span {
10491 start: 0,
10492 len: 5,
10493 from: Some((0, 0)),
10494 speed: Speed::NORMAL
10495 },
10496 Span {
10497 start: 5,
10498 len: 5,
10499 from: None,
10500 speed: Speed::NORMAL
10501 },
10502 Span {
10503 start: 10,
10504 len: 10,
10505 from: Some((1, 0)),
10506 speed: Speed::NORMAL
10507 },
10508 Span {
10509 start: 20,
10510 len: 10,
10511 from: None,
10512 speed: Speed::NORMAL
10513 },
10514 ]
10515 );
10516
10517 // One video lane: the composite *is* that lane, span for span -- the
10518 // promise every existing two-lane project rests on.
10519 let p = Project::single(FILE, 30);
10520 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
10521 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
10522 }
10523
10524 /// Every audio lane holding something gets a play list, and only those.
10525 #[test]
10526 fn audio_segments_cover_every_lane_that_holds_something() {
10527 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10528 let lanes = vec![
10529 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10530 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10531 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
10532 (LaneKind::Audio, Vec::new()),
10533 ];
10534 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10535 let lists = p.audio_segments_from(0, FPS);
10536 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
10537 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
10538 // A2 is a gap up to frame 15, then the whole of source 1.
10539 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
10540
10541 // No audio lane holds anything: one all-gap list, so such a timeline
10542 // still plays silence against a master clock.
10543 let p = Project::from_parts(
10544 vec![Source::new(FILE, 0)],
10545 vec![
10546 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10547 (LaneKind::Audio, Vec::new()),
10548 ],
10549 vec![],
10550 vec![],
10551 Vec::new(),
10552 )
10553 .expect("valid parts");
10554 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
10555 }
10556
10557/// D4: removing a subtitle column used to clear the whole undo history,
10558/// because a placement names its track by index into the palette and the
10559/// reindex left every later entry naming the wrong one. The entry holds the
10560/// palette beside the lanes now, so the reindex undoes with it.
10561#[test]
10562fn removing_a_subtitle_column_undoes_with_its_reindex() {
10563 let track = |label: &str| SubtitleTrack {
10564 path: FILE.into(),
10565 track: None,
10566 language: "eng".into(),
10567 name: String::new(),
10568 label: label.into(),
10569 cues: Vec::new(),
10570 bitmap: false,
10571 refused: None,
10572 };
10573 let mut p = Project::single(FILE, 300)
10574 .with_subtitles(vec![track("one"), track("two"), track("three")]);
10575 assert_eq!(p.subtitles().len(), 3);
10576 let before = p.parts();
10577 let palette = p.subtitles().to_vec();
10578 // Column 0 goes, which renumbers the two behind it.
10579 p.remove_subtitles(0).expect("a column with nothing on it");
10580 assert_eq!(p.subtitles().len(), 2);
10581 assert_eq!(p.subtitles()[0].label, "two");
10582 assert!(p.undo(), "the removal is a step like any other cut");
10583 // The palette itself, and not only what `parts` happens to compare: this
10584 // is the assertion that cannot go vacuous if the restore below it ever
10585 // leaves a field of it behind.
10586 assert_eq!(p.subtitles(), palette.as_slice(), "the palette itself, back");
10587 assert_eq!(p.parts(), before, "the palette and the lanes, both back");
10588 assert!(p.redo(), "and forward again");
10589 assert_eq!(p.subtitles().len(), 2, "the column goes again");
10590 assert_eq!(p.subtitles()[0].label, "two");
10591 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
10592}
10593
10594}