forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

project.rs10408 lines, 454.4 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119);
120
121impl Speed {
122 /// Real time -- what every clip is until something says otherwise, and the
123 /// value every path in this engine short-circuits on.
124 pub const NORMAL: Speed = Speed(1000);
125 pub const MIN: Speed = Speed(250);
126 pub const MAX: Speed = Speed(4000);
127
128 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
129 /// unrepresentable rather than merely refused: nothing downstream divides
130 /// by a speed that could be nothing.
131 pub fn from_permille(permille: u16) -> Self {
132 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
133 }
134
135 pub fn permille(self) -> u16 {
136 self.0
137 }
138
139 pub fn is_normal(self) -> bool {
140 self == Self::NORMAL
141 }
142
143 /// As a multiplier, for the sound worker and for a label.
144 pub fn as_f64(self) -> f64 {
145 f64::from(self.0) / 1000.
146 }
147
148 /// How many *timeline* frames `source` source frames occupy at this rate --
149 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
150 /// clip that occupied no frames would be an empty placement, which the lane
151 /// invariant forbids and which nothing could ever click on again.
152 pub fn frames(self, source: u32) -> u32 {
153 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
154 n.clamp(1, u64::from(u32::MAX)) as u32
155 }
156
157 /// The mapping itself: which source frame of a clip the `offset`th timeline
158 /// frame of it plays. Floored, so the first timeline frame is the clip's own
159 /// in-point at every rate.
160 pub fn source_at(self, offset: u32) -> u32 {
161 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
162 }
163
164 /// Its inverse, for a decoder's frames on their way back out: which timeline
165 /// frame of the clip the `offset`th *source* frame of it lands on.
166 ///
167 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
168 /// decoded frame with this and shows the newest whose stamp has come due, so
169 /// what is on screen at timeline offset `d` is the last source frame with
170 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
171 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
172 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
173 /// the two the same way would put the preview a frame off the export at some
174 /// speeds and a whole held frame off at slow ones -- drift that no test of
175 /// either side alone would catch.
176 pub fn timeline_at(self, offset: u32) -> u32 {
177 (u64::from(offset) * 1000)
178 .div_ceil(u64::from(self.0))
179 .min(u64::from(u32::MAX)) as u32
180 }
181
182 /// The longest source range that still *fits* in `frames` timeline frames at
183 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
184 /// any room narrower than the four timeline frames one source frame occupies.
185 ///
186 /// What a trim commits and what a hole-punch leaves behind: rounding could
187 /// otherwise hand back a range wider than the room, and a clip that outgrew
188 /// its room would overlap its neighbour -- the one thing a lane may never do.
189 /// `None` is not an error, it is "no remainder": the caller drops that piece
190 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
191 /// is `frames` itself, so nothing about an unspeeded edit changes.
192 pub fn fit(self, frames: u32) -> Option<u32> {
193 if frames == 0 || self.frames(1) > frames {
194 return None;
195 }
196 let mut src = self.source_at(frames).max(1);
197 // At most a step or two: `frames` is monotone in `src` and the rounding
198 // above can only overshoot by one source frame's worth.
199 while src > 1 && self.frames(src) > frames {
200 src -= 1;
201 }
202 Some(src)
203 }
204
205 /// How many timeline frames `source` source frames of head (or tail) are
206 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
207 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
208 /// empty, but the room in front of one may well be.
209 pub fn room(self, source: u32) -> u32 {
210 match source {
211 0 => 0,
212 n => self.frames(n),
213 }
214 }
215
216 /// How many timeline frames from `offset` on show the **same** source frame:
217 /// one at real time and faster, more when the clip is slowed. What an export
218 /// encodes without decoding the same picture twice, and the count that makes
219 /// its frame walk exactly as long as the span.
220 pub fn repeats(self, offset: u32, len: u32) -> u32 {
221 let want = self.source_at(offset);
222 (offset..len)
223 .take_while(|&t| self.source_at(t) == want)
224 .count() as u32
225 }
226
227 /// Where in the source a cut `offset` timeline frames into a clip of `len`
228 /// source frames falls -- and `None` when this rate cannot address that
229 /// frame at all.
230 ///
231 /// At half speed a clip of ten source frames is twenty timeline frames long
232 /// and every source frame is on screen twice, so a cut between the two
233 /// showings of one frame is not a cut in the *file*: taking it would leave
234 /// two halves whose lengths no longer add up to the clip that was cut --
235 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
236 /// the model stays exact and the front-end can say why. At real time every
237 /// interior frame answers, which is the path a project without speeds is on.
238 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
239 let src = self.source_at(offset);
240 (src > 0
241 && src < len
242 && self.frames(src) == offset
243 && self.frames(len - src) == self.frames(len) - offset)
244 .then_some(src)
245 }
246}
247
248impl Default for Speed {
249 fn default() -> Self {
250 Self::NORMAL
251 }
252}
253
254impl std::fmt::Display for Speed {
255 /// `2.00x` -- what a card prints and what a clip box is marked with.
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{:.2}x", self.as_f64())
258 }
259}
260
261/// What a file's own frame rate is against the timeline's, as an exact
262/// rational: how many frames of the *file* one frame of the timeline is worth.
263///
264/// Every frame number in this module counts **timeline** frames -- a clip's
265/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
266/// timeline is as many frames long as the seconds it lasts, and every edit
267/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
268/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
269/// opens a worker with it and [`crate::export`] pulls pictures through it. The
270/// file's own numbering exists nowhere else.
271///
272/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
273/// export encodes at a timeline frame has to be the frame playback is holding
274/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
275/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
276///
277/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
278/// stays `800/1001` however far the timeline runs, where a rate rounded to
279/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
280/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
281///
282/// [`PlaybackSession`]: crate::PlaybackSession
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
284pub struct Rate {
285 /// Frames of the file...
286 source: u32,
287 /// ...per this many frames of the timeline it plays on. Never zero.
288 timeline: u32,
289}
290
291impl Rate {
292 /// A file shot at the timeline's own rate: every conversion below is the
293 /// identity, which is the path a single-rate project is on.
294 pub const REAL_TIME: Self = Self {
295 source: 1,
296 timeline: 1,
297 };
298
299 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
300 /// exactly.
301 ///
302 /// Both rates come out of a container as a division, so neither is ever the
303 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
304 /// already knows how to name one exactly -- it is the same pair the muxer
305 /// counts an export's frames in -- and this is that pair divided by that
306 /// pair, reduced. A rate no timescale can name is an `Err` in that
307 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
308 /// where a file carrying one is refused by name, beside the codec.
309 ///
310 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
311 /// timeline that had ever opened in this editor before mixed rates.
312 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
313 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
314 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
315 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
316 let num = u64::from(src_scale) * u64::from(tl_ticks);
317 let den = u64::from(src_ticks) * u64::from(tl_scale);
318 Ok(Self::reduced(num, den))
319 }
320
321 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
322 fn reduced(num: u64, den: u64) -> Self {
323 let g = gcd(num, den);
324 let (mut num, mut den) = (num / g, den / g);
325 // A ratio no pair of real frame rates produces, but the fields are `u32`
326 // so that every multiplication below fits a `u64` at any frame count.
327 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
328 (num, den) = (num.div_ceil(2), den.div_ceil(2));
329 }
330 Self {
331 source: num.max(1) as u32,
332 timeline: den.max(1) as u32,
333 }
334 }
335
336 /// The same file against a timeline that has itself been retimed: `self` is
337 /// its frames per frame of the old timeline and `k` is old frames per new
338 /// one, so this is its frames per frame of the *new* one -- exactly, without
339 /// going back through an `f64` fps that names neither rate
340 /// ([`crate::PlaybackSession::set_frame_rate`]).
341 pub fn then(self, k: Rate) -> Self {
342 Self::reduced(
343 u64::from(self.source) * u64::from(k.source),
344 u64::from(self.timeline) * u64::from(k.timeline),
345 )
346 }
347
348 pub fn is_real_time(self) -> bool {
349 self.source == self.timeline
350 }
351
352 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
353 /// is, given the timeline's, for a library row that names it.
354 pub fn as_f64(self) -> f64 {
355 f64::from(self.source) / f64::from(self.timeline)
356 }
357
358 /// Which frame of the file the `frame`th timeline-rate frame of it is:
359 /// floored, [`Speed::source_at`]'s half of the pair.
360 pub fn source_at(self, frame: u32) -> u32 {
361 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
362 .min(u64::from(u32::MAX)) as u32
363 }
364
365 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
366 /// timeline-rate frame that shows source frame `source_frame` -- which is
367 /// the stamp playback puts on a decoded picture, and, applied to a file's
368 /// frame *count*, how long that file is in timeline frames.
369 pub fn timeline_at(self, source_frame: u32) -> u32 {
370 (u64::from(source_frame) * u64::from(self.timeline))
371 .div_ceil(u64::from(self.source))
372 .min(u64::from(u32::MAX)) as u32
373 }
374}
375
376/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
377/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
378fn gcd(a: u64, b: u64) -> u64 {
379 match b {
380 0 => a.max(1),
381 b => gcd(b, a % b),
382 }
383}
384
385/// A half-open `[in_frame, out_frame)` range of frames of source
386/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
387/// Never empty.
388///
389/// Counted at the **timeline's** frame rate, not the file's: a source shot at
390/// another rate is converted at the decoder's door ([`Rate`]), so every edit
391/// here is frames of one clock.
392#[derive(Clone, Copy, PartialEq, Eq, Debug)]
393pub struct Clip {
394 /// Timeline frame the clip's first frame is shown at. Meaningless on a
395 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
396 /// with where the caller asked for.
397 pub start: u32,
398 pub in_frame: u32,
399 pub out_frame: u32,
400 /// Index into [`Project::sources`].
401 pub source: usize,
402 /// Group id: clips sharing one were split from the same take. `None` for a
403 /// clip that belongs to no group.
404 pub link: Option<u32>,
405 /// Index into the project's equalizer table
406 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
407 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
408 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
409 /// plain assignment. The table is append-only within a session, so an index
410 /// on a clipboard clip or inside an undo snapshot can never dangle.
411 pub eq: Option<u16>,
412 /// Index into the project's colour table
413 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
414 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
415 /// promises: `Copy`, append-only within a session, never dangling.
416 pub color: Option<u16>,
417 /// Index into the project's transform table
418 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
419 /// clip that plays at its fit policy's own placement. An index for
420 /// [`Clip::color`]'s reason and with the same promises.
421 pub transform: Option<u16>,
422 /// How this clip's picture meets a project canvas of another shape
423 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
424 /// two above: it is one byte with no parameters, so there is nothing for a
425 /// table to share, and a clip that is the project's own size never consults
426 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
427 /// where the aspect does not agree.
428 pub fit: FitPolicy,
429 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
430 /// eq and colour indexes: it is two bytes with nothing to share, and a table
431 /// would put a level of indirection between the mapping and the one number
432 /// every frame of it is divided by.
433 ///
434 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
435 /// the clip plays, so a trim and a split still address the file. What it
436 /// changes is how many *timeline* frames that range is spread over
437 /// ([`Clip::frames`]).
438 pub speed: Speed,
439 /// Timeline frames of ramp-up from silence at the clip's own start, inline
440 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
441 /// number with nothing to share, and every consumer (mixer, exporter) wants
442 /// it sitting right next to the frame range it shapes. Clamped to the
443 /// clip's own length by the setter -- never wider than the clip is long.
444 pub fade_in: u32,
445 /// Timeline frames of ramp-down to silence at the clip's own end. Same
446 /// promises as [`Clip::fade_in`].
447 pub fade_out: u32,
448 /// Timeline frames of cross-dissolve into the clip immediately after this
449 /// one on the same video lane, at this clip's own end -- `0` for a hard
450 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
451 /// reason, and clamped the same way by its setter
452 /// ([`Project::set_transition_out`]): never wider than this clip's own
453 /// length, nor than the successor it dissolves into. Meaningless -- and
454 /// left as whatever it was -- the moment the next clip stops abutting
455 /// this one; a reader that cares checks adjacency itself rather than
456 /// trusting this field alone, exactly as a stored fade is trusted only
457 /// because a clip's own length is checked beside it.
458 pub transition_out: u32,
459 /// Non-zero: this clip is a waveform of its source's sound, painted
460 /// onto a video lane. Bit 0 is the flag; bits 1-2 style; bit 3 fast.
461 /// Zero is an ordinary picture. Older project files have no field and
462 /// mean zero.
463 pub visualizer: u8,
464 /// Packed look: hue 0-255, sat 0-255, strands 0-255, glow 0-255 in the
465 /// low four bytes as they have been since v22, then the strand colour's
466 /// own bytes above them -- its hue at 32 and sat at 40
467 /// ([`crate::decode::viz_strand_hue_ui`]) -- with the top bit as
468 /// [`crate::decode::viz_strand_set`]. All-zero is the default (timeline
469 /// azure, full sat, 8 strands, glow 2, no strand colour of its own).
470 /// Older files have no field and mean zero; a v22 file's 32-bit value
471 /// is the low half of this one, byte for byte.
472 pub viz_paint: u64,
473}
474
475impl Clip {
476 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
477 /// reads out of its file -- not how long it is on the timeline, which is
478 /// [`Clip::frames`] and differs the moment it is speeded.
479 pub fn len(&self) -> u32 {
480 self.out_frame - self.in_frame
481 }
482
483 /// Timeline frames it occupies: its source range at its own speed, never
484 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
485 /// what it overlaps, how wide its box is -- is asked of this and not of
486 /// [`Clip::len`].
487 pub fn frames(&self) -> u32 {
488 self.speed.frames(self.len())
489 }
490
491 /// One past the last timeline frame it covers.
492 pub fn end(&self) -> u32 {
493 self.start + self.frames()
494 }
495}
496
497/// A file the timeline plays from, and *which* of its audio streams it plays:
498/// a file carrying one track per language is several sources, one per stream,
499/// sharing a path. Two entries differing only in the stream are two sources --
500/// they are what a clip names, and a clip plays exactly one stream.
501///
502/// The path is always canonical ([`Source::new`]), so the same file reached by
503/// two paths is one source.
504#[derive(Clone, Debug, PartialEq, Eq)]
505pub struct Source {
506 pub path: PathBuf,
507 /// Position among the file's audio tracks in file order, the numbering
508 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
509 /// single track, and for a silent one.
510 pub audio_stream: usize,
511}
512
513impl Source {
514 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
515 Self {
516 path: canonical(path.as_ref()),
517 audio_stream,
518 }
519 }
520}
521
522/// What a lane carries, which is what a *gap* in it means: black frames on a
523/// video lane, silence on an audio one, nothing over the picture on a subtitle
524/// one.
525#[derive(Clone, Copy, PartialEq, Eq, Debug)]
526pub enum LaneKind {
527 Video,
528 Audio,
529 /// Words over the picture, placed and trimmed like everything else
530 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
531 /// so a caption is dragged, cut, rippled and undone by the machinery every
532 /// other clip already goes through.
533 ///
534 /// It carries no [`Clip`] at all, and that is what keeps the media paths
535 /// free of it: [`Project::lane`] hands back an empty slice, so every
536 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
537 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
538 /// check it already had, [`Project::composite_span_at`] and
539 /// [`Project::audio_lanes`] never look at it, and the three doors that
540 /// could still put a picture on one -- [`Project::from_parts`],
541 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
542 Subtitle,
543}
544
545/// Which lane an operation acts on: a kind plus a 0-based position among the
546/// lanes of that kind, so [`Lane::V1`] is the first video lane and
547/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
548///
549/// A handle, not the lane itself. It stays meaningful while lanes are added,
550/// and one naming a lane that is not there reads as an empty lane and refuses
551/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
552/// bounds check of its own.
553#[derive(Clone, Copy, PartialEq, Eq, Debug)]
554pub struct Lane {
555 pub kind: LaneKind,
556 pub ord: usize,
557}
558
559impl Lane {
560 /// The first video lane: what a decoder plays and what an export renders.
561 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
562 /// The first audio lane: what the audio worker plays.
563 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
564 /// The first subtitle lane -- the one a project has only once something
565 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
566 /// alone.
567 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
568
569 pub const fn new(kind: LaneKind, ord: usize) -> Self {
570 Self { kind, ord }
571 }
572
573 /// `V1`, `A2`: how a lane is written in a header column and named in an
574 /// error about it.
575 pub fn label(self) -> String {
576 let kind = match self.kind {
577 LaneKind::Video => 'V',
578 LaneKind::Audio => 'A',
579 LaneKind::Subtitle => 'S',
580 };
581 format!("{kind}{}", self.ord + 1)
582 }
583}
584
585/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
586/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
587/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
588/// frames. Never empty at either end.
589///
590/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
591/// actually has, and placed by the same one number: the window is in the
592/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
593/// placement is in timeline frames like everything else on a lane. So the lane
594/// invariant is the lane's ([`subs_sorted_disjoint`] is
595/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
596/// else, and only the two calls that change a *duration* -- a trim, and the
597/// mapping out -- ever need the timeline's rate.
598///
599/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
600/// paste and an undo snapshot are a plain assignment and can never dangle.
601#[derive(Clone, Copy, PartialEq, Eq, Debug)]
602pub struct SubClip {
603 /// Timeline frame its first frame is shown at.
604 pub start: u32,
605 /// How many timeline frames it covers; `>= 1`. Held rather than derived
606 /// from the window because a [`Project`] has no frame rate -- the rate
607 /// enters at the door of the two calls that need it -- and every placement
608 /// question (where it ends, what it overlaps) is asked in frames.
609 pub frames: u32,
610 /// Index into [`Project::subtitles`]: *which* track's words these are.
611 pub track: usize,
612 /// The half-open window of that track it shows, in microseconds from the
613 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
614 /// timed in, so no conversion stands between a cue and the window that
615 /// keeps it.
616 pub in_us: i64,
617 pub out_us: i64,
618 /// Group id: `Some` exactly when a hand put this caption in a group with
619 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
620 /// no group, and what a cut cuts apart loses the one it had
621 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
622 /// clip is what makes the caption move, trim and delete with it.
623 pub link: Option<u32>,
624}
625
626impl SubClip {
627 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
628 /// what every overlap question is asked of.
629 pub fn end(&self) -> u32 {
630 self.start + self.frames
631 }
632
633 /// How much of its track it shows, in microseconds; `>= 1` by the
634 /// never-empty invariant.
635 pub fn window_us(&self) -> i64 {
636 self.out_us - self.in_us
637 }
638
639 /// Where in its window the timeline frame `frame` falls, in microseconds --
640 /// the cut a split, a ripple and a trim all land on.
641 ///
642 /// By proportion and not by the timeline's rate: the window and the frame
643 /// count measure the same stretch of time, so the fraction of the frames
644 /// before `frame` is the fraction of the microseconds before it. That is
645 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
646 /// without either of them learning an fps.
647 fn window_at(&self, frame: u32) -> i64 {
648 let into = i64::from(frame.saturating_sub(self.start));
649 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
650 }
651}
652
653/// One lane: what it is and what it holds. A struct rather than a bare
654/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
655/// compositing mode, a name -- and it belongs next to the clips it applies to.
656#[derive(Clone, Debug)]
657struct LaneData {
658 kind: LaneKind,
659 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
660 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
661 /// ever seeing a subtitle: they all read this list.
662 clips: Vec<Clip>,
663 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
664 /// empty on a video or audio one. Beside the clips rather than an enum over
665 /// them so that everything a lane *is* -- its place in the stack, its
666 /// label, its undo snapshot, its removal -- stays one code path for all
667 /// three kinds.
668 subs: Vec<SubClip>,
669 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
670 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
671 /// makes it a different thing from a clip's equalizer: it moves everything
672 /// on the track by the same amount, cuts included. Meaningless on a video
673 /// lane, where it is kept at 0 and asked by nothing.
674 gain_db: f32,
675}
676
677impl LaneData {
678 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
679 Self {
680 kind,
681 clips,
682 subs: Vec::new(),
683 gain_db: 0.0,
684 }
685 }
686
687 /// The two lanes a project starts with: `V1` then `A1`, in display order.
688 /// One place, because a freshly opened file is exactly this pair.
689 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
690 vec![
691 LaneData::new(LaneKind::Video, video),
692 LaneData::new(LaneKind::Audio, audio),
693 ]
694 }
695}
696
697/// The placements one group id names, split by the two lists a lane holds:
698/// what a drag, a trim and a delete each have to walk, now that a group may
699/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
700/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
701/// -- so the pairs are `(lane storage index, index into that lane's list)`.
702#[derive(Default)]
703struct Members {
704 clips: Vec<(usize, usize)>,
705 subs: Vec<(usize, usize)>,
706}
707
708impl Members {
709 /// Whether the group is the one placement and no more: what a lift leaves
710 /// behind, and what every whole-group question answers "not one" for.
711 fn alone(&self) -> bool {
712 self.clips.len() + self.subs.len() < 2
713 }
714}
715
716/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
717#[derive(Clone, Copy, PartialEq, Eq, Debug)]
718pub enum Edge {
719 /// Its first timeline frame; moving it changes where in the source the clip
720 /// starts reading, so the picture behind the edge slides with it.
721 Start,
722 /// One past its last timeline frame; moving it only says how much of the
723 /// source to keep.
724 End,
725}
726
727/// What a lane holds over one stretch of the timeline: either a placed clip or
728/// a gap. Returned already trimmed to the position it was asked about, so a
729/// caller can hand `len` straight to a decoder (or to a black-frame generator).
730#[derive(Clone, Copy, PartialEq, Eq, Debug)]
731pub struct Span {
732 /// Timeline frame the span starts at.
733 pub start: u32,
734 /// Frames it covers; `>= 1`.
735 pub len: u32,
736 /// `(source index, first source frame)`, or `None` for a gap -- which the
737 /// engine renders as black frames and as silence.
738 pub from: Option<(usize, u32)>,
739 /// The rate the clip this came off plays at ([`Clip::speed`]);
740 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
741 /// timeline frames whatever it says -- the speed is how many *source* frames
742 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
743 /// come back to the timeline.
744 pub speed: Speed,
745}
746
747impl Span {
748 /// One past the last timeline frame it covers.
749 pub fn end(&self) -> u32 {
750 self.start + self.len
751 }
752
753 /// How many source frames it reads: what a decoder is asked for and how wide
754 /// an audio window is. `len` at real time, and the one arithmetic both the
755 /// picture and the sound go through, so they cannot disagree about where a
756 /// speeded clip ends.
757 pub fn source_len(&self) -> u32 {
758 match self.from {
759 // The last timeline frame's own source frame is the last one needed
760 // -- never one more, which at a slow rate would read a frame the
761 // next clip owns and at a fast one would decode a picture nothing
762 // shows.
763 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
764 None => self.len,
765 }
766 }
767
768 /// Where a source frame of this span lands on the timeline: the stamp
769 /// playback puts on a decoded frame, through the ceil half of the pair
770 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
771 /// frame, so a frame before it stamps at the span's start.
772 pub fn timeline_at(&self, source_frame: u32) -> u32 {
773 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
774 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
775 }
776}
777
778/// What one speeded audio segment asks of the worker: how many source frames to
779/// consume per output frame, and how many seconds of timeline it has to fill.
780/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
781/// resampling at all.
782#[derive(Clone, Copy, PartialEq, Debug)]
783pub struct Stretch {
784 /// Source frames per output frame -- the speed as a multiplier.
785 pub step: f64,
786 /// What the segment owes the timeline, which is what it is padded or
787 /// trimmed to.
788 pub timeline_secs: f64,
789}
790
791/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
792/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
793/// against where in the *clip* -- not the segment, which may start mid-clip
794/// on a seek -- this segment's first frame lands.
795#[derive(Clone, Copy, PartialEq, Eq, Debug)]
796pub struct Fade {
797 /// How many of the clip's own frames already played before this
798 /// segment's first frame: `0` unless playback started mid-clip.
799 pub elapsed: u32,
800 /// The clip's [`Clip::fade_in`].
801 pub fade_in: u32,
802 /// The clip's [`Clip::fade_out`].
803 pub fade_out: u32,
804 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
805 /// which this segment may only cover the tail.
806 pub total: u32,
807}
808
809impl Fade {
810 /// The gain at clip-relative frame `pos`, an equal-power curve on each
811 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
812 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
813 /// ramp, so a fade lands on silence at its very first (or very last)
814 /// frame and reaches unity smoothly rather than at a constant slope --
815 /// the same curve [`Project::crossfade`] relies on to keep two clips'
816 /// sum around one level through the join. Both ramps multiply where a
817 /// clip is short enough for them to overlap.
818 fn gain_at(self, pos: u32) -> f32 {
819 let mut g = 1.0f32;
820 if self.fade_in > 0 && pos < self.fade_in {
821 let t = pos as f32 / self.fade_in as f32;
822 g *= (t * std::f32::consts::FRAC_PI_2).sin();
823 }
824 if self.fade_out > 0 {
825 let out_start = self.total.saturating_sub(self.fade_out);
826 if pos >= out_start {
827 let remaining = self.total.saturating_sub(pos);
828 let t = remaining as f32 / self.fade_out as f32;
829 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
830 }
831 }
832 g
833 }
834
835 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
836 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
837 pub fn apply(self, frames: &mut [f32], channels: usize) {
838 for (i, block) in frames.chunks_mut(channels).enumerate() {
839 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
840 for s in block {
841 *s *= g;
842 }
843 }
844 }
845
846 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
847 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
848 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
849 /// position is in) but [`Self::apply`] multiplies *audio* frames --
850 /// `channels`-wide sample blocks at whatever rate the mix is running at,
851 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
852 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
853 /// few milliseconds into any clip, so a fade-out silenced the rest of the
854 /// clip outright and a fade-in finished before a listener's ear caught up
855 /// -- audible on nothing shorter than a clip a few fps-frames long, which
856 /// is why 338 green tests never once ran the two curves out of step.
857 /// `ratio` is `sample_rate / fps`, applied once where the audio session
858 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
859 pub fn scaled(self, ratio: f64) -> Fade {
860 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
861 Fade {
862 elapsed: conv(self.elapsed),
863 fade_in: conv(self.fade_in),
864 fade_out: conv(self.fade_out),
865 total: conv(self.total),
866 }
867 }
868}
869
870/// What a save writes and a load takes back: the sources, every lane in
871/// display order with its kind, and the equalizer and colour tables their clips
872/// index into -- [`Project::without_orphan_sources`] out,
873/// [`Project::from_parts`] in.
874pub type Parts = (
875 Vec<Source>,
876 Vec<(LaneKind, Vec<Clip>)>,
877 Vec<EqParams>,
878 Vec<ColorParams>,
879 Vec<TransformParams>,
880);
881
882/// How many undo steps a project keeps. One gesture is one step, so 100 is past
883/// any chain a person walks back by hand, and the oldest step is dropped rather
884/// than the history growing without end: a snapshot is the whole lane list, so
885/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
886/// that grows for as long as the session lasts.
887const HISTORY_CAP: usize = 100;
888
889/// One gap a close-all sweep left open, with the frame it still starts on and
890/// the same refusal a single [`Project::gap_take_scope`] close would have said.
891#[derive(Clone, Debug, PartialEq, Eq)]
892pub struct GapSkip {
893 pub start: u32,
894 pub reason: String,
895}
896
897/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
898/// skipped gaps are the take-safety refusals the sweep did not hide.
899#[derive(Clone, Debug, Default, PartialEq, Eq)]
900pub struct GapSweep {
901 pub closed: usize,
902 pub skipped: Vec<GapSkip>,
903}
904
905/// The edit list plus its undo history.
906#[derive(Clone, Debug)]
907pub struct Project {
908 /// Append-only: never popped, never reordered. See the module docs.
909 sources: Vec<Source>,
910 /// In display order, which is the order [`Lane::ord`] counts in: the nth
911 /// lane of a kind here is that kind's `ord` n. Never empty.
912 lanes: Vec<LaneData>,
913 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
914 eq: Vec<EqParams>,
915 /// The same, for [`Clip::color`].
916 color: Vec<ColorParams>,
917 /// The same, for [`Clip::transform`].
918 transform: Vec<TransformParams>,
919 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
920 /// whole lane list, so adding a lane undoes as well. Bounded by
921 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
922 history: Vec<Vec<LaneData>>,
923 /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by
924 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
925 /// the undone steps came from. Not saved to `.edith`, matching `history`.
926 redo: Vec<Vec<LaneData>>,
927 /// Never rolled back by an undo: an id retired by an undone split must not
928 /// come back and group two clips that were never together.
929 next_link: u32,
930 /// The subtitle tracks this timeline shows, in the order they were added.
931 /// Not in the lane list and not in the history snapshots, for the reason
932 /// the limiter is not: which subtitles a project carries is a setting on
933 /// it, and it is saved as a *reference* to the file the cues came out of
934 /// ([`crate::subtitle`]).
935 subtitles: Vec<SubtitleTrack>,
936 /// The master limiter every lane's sound is summed *through*
937 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
938 /// is what the history snapshots hold: it is a setting on the mix, like the
939 /// project's resolution is a setting on the picture, and neither is an undo
940 /// step.
941 limiter: Limiter,
942 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
943 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
944 /// the resolution, and not in the lane snapshots for the same reason.
945 tone: crate::tonemap::Preset,
946}
947
948impl Project {
949 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
950 /// grouped -- the state of a freshly opened video, where the timeline is the
951 /// source. `frame_count` of 0 would break the never-empty invariant, so it
952 /// is clamped to one frame.
953 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
954 let clip = Clip {
955 fade_in: 0,
956 fade_out: 0,
957 transition_out: 0,
958 visualizer: 0,
959 viz_paint: 0,
960 start: 0,
961 in_frame: 0,
962 out_frame: frame_count.max(1),
963 source: 0,
964 link: Some(0),
965 eq: None,
966 color: None,
967 transform: None,
968 fit: FitPolicy::default(),
969 speed: Speed::NORMAL,
970 };
971 Self {
972 // A file is opened on its first audio stream: nothing has picked
973 // one yet, and every file with audio at all has that one.
974 sources: vec![Source::new(path, 0)],
975 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
976 eq: Vec::new(),
977 color: Vec::new(),
978 transform: Vec::new(),
979 history: Vec::new(),
980 redo: Vec::new(),
981 next_link: 1,
982 subtitles: Vec::new(),
983 limiter: Limiter::default(),
984 tone: crate::tonemap::Preset::default(),
985 }
986 }
987
988 /// A project rebuilt from a saved edit list -- the load half of
989 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
990 /// an `ord` is a lane's position among the lanes of that kind, exactly as
991 /// [`Project::lanes`] hands them back. History is *not* saved, so
992 /// [`Project::undo`] is `false` until the first edit of the new session.
993 /// This is the one door untrusted parts come in through, so every invariant
994 /// every other constructor keeps is checked here, by name and in release:
995 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
996 /// or a colour) that is not there, a clip whose end overflows, a lane that is
997 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
998 /// below.
999 ///
1000 /// A project whose lanes are all *empty* is not among them: an emptied
1001 /// timeline is a project like any other -- it plays black and silent, it
1002 /// saves, and it loads back. What a project cannot be is laneless, because
1003 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
1004 /// handle indexes into.
1005 pub fn from_parts(
1006 sources: Vec<Source>,
1007 lanes: Vec<(LaneKind, Vec<Clip>)>,
1008 eq: Vec<EqParams>,
1009 color: Vec<ColorParams>,
1010 transform: Vec<TransformParams>,
1011 ) -> crate::Result<Self> {
1012 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
1013 return Err(format!("eq {bad} holds a band that is not a finite number").into());
1014 }
1015 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
1016 return Err(format!("color {bad} holds a value that is not a finite number").into());
1017 }
1018 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
1019 return Err(format!("transform {bad} holds a value that is not a finite number").into());
1020 }
1021 if lanes.is_empty() {
1022 return Err("no lanes at all: that is not a project".into());
1023 }
1024 let lanes: Vec<LaneData> = lanes
1025 .into_iter()
1026 .map(|(kind, clips)| LaneData::new(kind, clips))
1027 .collect();
1028 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
1029 let name = lane.label();
1030 // A subtitle lane carries words and never a picture
1031 // ([`LaneKind::Subtitle`]); a file that puts one there names a
1032 // source on a lane that has nothing to play it with, and every
1033 // media path below would then read a clip off a lane it does not
1034 // know about.
1035 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
1036 return Err(format!(
1037 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
1038 data.clips.len()
1039 )
1040 .into());
1041 }
1042 for c in &data.clips {
1043 if c.out_frame <= c.in_frame {
1044 return Err(format!(
1045 "{name} clip at {} plays the empty range [{}, {})",
1046 c.start, c.in_frame, c.out_frame
1047 )
1048 .into());
1049 }
1050 if c.source >= sources.len() {
1051 return Err(format!(
1052 "{name} clip at {} names source {} of {}",
1053 c.start,
1054 c.source,
1055 sources.len()
1056 )
1057 .into());
1058 }
1059 if c.start.checked_add(c.frames()).is_none() {
1060 return Err(format!(
1061 "{name} clip at {} runs past the last frame there is",
1062 c.start
1063 )
1064 .into());
1065 }
1066 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1067 return Err(format!(
1068 "{name} clip at {} names eq {} of {}",
1069 c.start,
1070 c.eq.unwrap_or_default(),
1071 eq.len()
1072 )
1073 .into());
1074 }
1075 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1076 return Err(format!(
1077 "{name} clip at {} names color {} of {}",
1078 c.start,
1079 c.color.unwrap_or_default(),
1080 color.len()
1081 )
1082 .into());
1083 }
1084 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
1085 return Err(format!(
1086 "{name} clip at {} names transform {} of {}",
1087 c.start,
1088 c.transform.unwrap_or_default(),
1089 transform.len()
1090 )
1091 .into());
1092 }
1093 }
1094 if !sorted_disjoint(&data.clips) {
1095 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1096 }
1097 }
1098 links_are_consistent(&lanes)?;
1099 // The counter sits past every id the file names, on either of a lane's
1100 // lists: a v16 caption may carry the highest link there is, and a
1101 // re-issued id would silently group it with the next placement that
1102 // asks for one -- the loader refusing a save the editor just wrote.
1103 let next_link = lanes
1104 .iter()
1105 .flat_map(|l| {
1106 let clips = l.clips.iter().filter_map(|c| c.link);
1107 let subs = l.subs.iter().filter_map(|s| s.link);
1108 clips.chain(subs)
1109 })
1110 .max()
1111 // Saturating so a crafted file cannot make the counter wrap: at the
1112 // ceiling ids stop being fresh, which loses grouping, not memory.
1113 .map_or(0, |m| m.saturating_add(1));
1114 Ok(Self {
1115 sources: sources
1116 .iter()
1117 .map(|s| Source::new(&s.path, s.audio_stream))
1118 .collect(),
1119 lanes,
1120 eq,
1121 color,
1122 transform,
1123 history: Vec::new(),
1124 redo: Vec::new(),
1125 next_link,
1126 subtitles: Vec::new(),
1127 limiter: Limiter::default(),
1128 tone: crate::tonemap::Preset::default(),
1129 })
1130 }
1131
1132 /// The first video lane -- what an export renders and what a single-lane
1133 /// caller still means by "the clips".
1134 pub fn clips(&self) -> &[Clip] {
1135 self.lane(Lane::V1)
1136 }
1137
1138 /// The clips of `lane`, or nothing at all for a lane that is not there.
1139 pub fn lane(&self, lane: Lane) -> &[Clip] {
1140 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1141 }
1142
1143 /// Every lane's handle, in display order -- what a walk over "all lanes"
1144 /// iterates, and what a front-end lays out top to bottom.
1145 pub fn lanes(&self) -> Vec<Lane> {
1146 handles(&self.lanes)
1147 }
1148
1149 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1150 /// for every `ord` below it, and none at or above it.
1151 pub fn lane_count(&self, kind: LaneKind) -> usize {
1152 self.lanes.iter().filter(|l| l.kind == kind).count()
1153 }
1154
1155 /// Appends an empty lane of `kind` and hands back its handle. One undo
1156 /// step, because the lane list is state a front-end shows: an added lane
1157 /// that could not be taken back would be the one edit with no way out.
1158 /// Nothing plays differently until something is placed on it.
1159 ///
1160 /// An empty lane is a lane like any other -- so is a whole project of them
1161 /// ([`Project::from_parts`]); nothing plays until something is placed.
1162 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1163 self.snapshot();
1164 self.lanes.push(LaneData::new(kind, Vec::new()));
1165 Lane::new(kind, self.lane_count(kind) - 1)
1166 }
1167
1168 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1169 /// one undo step like it, which restores the lane where it stood.
1170 ///
1171 /// Refused, changing nothing, while the lane holds anything: the refusal
1172 /// names the clips (file and first frame), because a track removal that
1173 /// deleted takes with it would be the one edit nobody sees coming. Refused
1174 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1175 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1176 /// kind and *skips* a kind that is not there), so a project without one
1177 /// would swallow half of every file dropped on it, silently.
1178 ///
1179 /// The lanes below it move up one `ord`, so a handle a caller was holding
1180 /// (a selection, an open card) names the lane after it from here on -- the
1181 /// one thing a front-end owes this call.
1182 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1183 let Some(i) = self.index(lane) else {
1184 return Err(format!("there is no {} to remove", lane.label()).into());
1185 };
1186 // A subtitle lane is not in that rule: nothing lands on one by itself
1187 // -- a project starts without any and one is added when a caption is --
1188 // so the last of them comes off like any other empty track.
1189 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1190 return Err(format!(
1191 "{} is the only {} track: every import lands on it",
1192 lane.label(),
1193 match lane.kind {
1194 LaneKind::Video => "video",
1195 LaneKind::Audio => "audio",
1196 // Unreachable while the guard above lets the last subtitle
1197 // lane go, and its own word here so the sentence stays true
1198 // if that rule is ever relaxed.
1199 LaneKind::Subtitle => "subtitle",
1200 }
1201 )
1202 .into());
1203 }
1204 if !self.lanes[i].subs.is_empty() {
1205 // Three names and a count, exactly as the clips below get: the way
1206 // out of the refusal is the drag, so the words say so.
1207 let named: Vec<String> = self.lanes[i]
1208 .subs
1209 .iter()
1210 .take(3)
1211 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1212 .collect();
1213 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1214 0 => String::new(),
1215 n => format!(" and {n} more"),
1216 };
1217 return Err(format!(
1218 "{} still holds {}{rest}: delete those captions (or drag them to \
1219 another track) first",
1220 lane.label(),
1221 named.join(", ")
1222 )
1223 .into());
1224 }
1225 let clips = &self.lanes[i].clips;
1226 if !clips.is_empty() {
1227 // Three names and a count: a lane can hold forty clips and a
1228 // refusal nobody reads to the end says nothing at all.
1229 let named: Vec<String> = clips
1230 .iter()
1231 .take(3)
1232 .map(|c| {
1233 let name = self.sources.get(c.source).map_or_else(
1234 || format!("source {}", c.source),
1235 |s| s.path.display().to_string(),
1236 );
1237 format!("{name} at frame {}", c.start)
1238 })
1239 .collect();
1240 let rest = match clips.len().saturating_sub(named.len()) {
1241 0 => String::new(),
1242 n => format!(" and {n} more"),
1243 };
1244 return Err(format!(
1245 "{} still holds {}{rest}: delete those clips (or drag them to \
1246 another track) first",
1247 lane.label(),
1248 named.join(", ")
1249 )
1250 .into());
1251 }
1252 self.snapshot();
1253 self.lanes.remove(i);
1254 Ok(())
1255 }
1256
1257 /// Moves `lane` to display position `to` -- an index into
1258 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1259 /// the handle it answers to from now on. `None`, changing nothing and
1260 /// snapshotting nothing, for a lane that is not there, a position that is
1261 /// not, and a lane already standing in it.
1262 ///
1263 /// The whole track travels: its clips, its gain, its kind. Nothing is
1264 /// remapped, so no take changes lane and no group is broken -- this is the
1265 /// *order* of the lanes and nothing else, which is why one call is one undo
1266 /// step like an add or a removal.
1267 ///
1268 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1269 /// last video lane covering a frame, so moving one video lane past another
1270 /// changes which picture wins, in the preview and in an export alike. The
1271 /// audio lanes are summed and their sum does not care about order, so an
1272 /// audio track moved among the video ones is a rearrangement of the screen
1273 /// alone.
1274 ///
1275 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1276 /// position among the lanes of that kind), so a lane that crosses one of
1277 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1278 /// `V1`, clips and all -- while one that crosses only lanes of the other
1279 /// kind keeps its name. That is the returned handle: unchanged means every
1280 /// handle a caller holds still names the track it named before.
1281 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1282 let i = self.index(lane)?;
1283 if to >= self.lanes.len() || to == i {
1284 return None;
1285 }
1286 self.snapshot();
1287 let data = self.lanes.remove(i);
1288 self.lanes.insert(to, data);
1289 Some(handles(&self.lanes)[to])
1290 }
1291
1292 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1293 /// not there. The one place a handle becomes a position.
1294 fn index(&self, lane: Lane) -> Option<usize> {
1295 self.lanes
1296 .iter()
1297 .enumerate()
1298 .filter(|(_, l)| l.kind == lane.kind)
1299 .map(|(i, _)| i)
1300 .nth(lane.ord)
1301 }
1302
1303 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1304 let i = self.index(lane)?;
1305 Some(&mut self.lanes[i].clips)
1306 }
1307
1308 /// The files the clips index into, in import order; index 0 is the file the
1309 /// project was opened with.
1310 pub fn sources(&self) -> &[Source] {
1311 &self.sources
1312 }
1313
1314 /// The same list in the `(path, stream)` shape the audio engine indexes
1315 /// into -- [`crate::AudioSession::open_multi_streams`] and
1316 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1317 /// was placed with is the stream that plays *and* the stream that exports.
1318 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1319 self.sources
1320 .iter()
1321 .map(|s| (s.path.clone(), s.audio_stream))
1322 .collect()
1323 }
1324
1325 /// Index for `path` played on `audio_stream`, appending it if it is new.
1326 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1327 /// by two paths imports once and two streams of one file are two sources.
1328 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1329 /// no history: a source entry alone changes nothing playable.
1330 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1331 let source = Source::new(path, audio_stream);
1332 match self.sources.iter().position(|s| *s == source) {
1333 Some(idx) => idx,
1334 None => {
1335 self.sources.push(source);
1336 self.sources.len() - 1
1337 }
1338 }
1339 }
1340
1341 /// Append a whole-file clip of `source` to the end of every *media* lane,
1342 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1343 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1344 /// come in through [`Project::add_subtitles`], which is the palette.
1345 ///
1346 /// One history snapshot, so an import is one undo step, and undoing it
1347 /// leaves the (harmless) source entry behind, because indexes are forever.
1348 /// Refused for an unknown source index.
1349 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1350 if source >= self.sources.len() {
1351 return false;
1352 }
1353 self.snapshot();
1354 let start = self.timeline_frames();
1355 let clip = Clip {
1356 fade_in: 0,
1357 fade_out: 0,
1358 transition_out: 0,
1359 visualizer: 0,
1360 viz_paint: 0,
1361 start,
1362 in_frame: 0,
1363 out_frame: frame_count.max(1),
1364 source,
1365 link: Some(self.new_link()),
1366 eq: None,
1367 color: None,
1368 transform: None,
1369 fit: FitPolicy::default(),
1370 speed: Speed::NORMAL,
1371 };
1372 for data in self
1373 .lanes
1374 .iter_mut()
1375 .filter(|l| l.kind != LaneKind::Subtitle)
1376 {
1377 data.clips.push(clip);
1378 }
1379 true
1380 }
1381
1382 /// Drops a source entry -- the file a library row *is* -- and renumbers
1383 /// every clip that indexed past it, which is why this is more than a
1384 /// `Vec::remove`.
1385 ///
1386 /// Refused, changing nothing, while any clip still plays from it: the
1387 /// refusal names the lanes and how many clips each holds, so a caller can
1388 /// say what has to be deleted first. The *last* entry goes like any other
1389 /// -- a project may name no file at all, which is an empty library over an
1390 /// empty timeline (nothing can play, since a clip would have refused the
1391 /// removal). What a front-end does with that is its own decision: `edith`'s
1392 /// window goes back to the empty state it launches in, and
1393 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1394 /// refuses to write a project that names nothing, because no such file
1395 /// could be opened again.
1396 ///
1397 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1398 /// source index of its own -- a clipboard, which is the one thing outside
1399 /// this type that does -- has to fix it up or drop it, or a paste plays a
1400 /// different file. [`PlaybackSession::remove_source`] hands back the index
1401 /// that went for exactly that.
1402 ///
1403 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1404 /// snapshot older than the removal can name the very source being removed
1405 /// (delete a file's clips, then remove the file) and restoring it would
1406 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1407 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1408 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1409 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1410 /// exists) currently rules out.
1411 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1412 let Some(source) = self.sources.get(idx) else {
1413 return Err(format!("there is no source {idx} to remove").into());
1414 };
1415 let name = source.path.display().to_string();
1416 let used: Vec<String> = handles(&self.lanes)
1417 .into_iter()
1418 .zip(&self.lanes)
1419 .filter_map(
1420 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1421 0 => None,
1422 1 => Some(format!("{} (1 clip)", lane.label())),
1423 n => Some(format!("{} ({n} clips)", lane.label())),
1424 },
1425 )
1426 .collect();
1427 if !used.is_empty() {
1428 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1429 }
1430 self.sources.remove(idx);
1431 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1432 if c.source > idx {
1433 c.source -= 1;
1434 }
1435 }
1436 self.history.clear();
1437 Ok(())
1438 }
1439
1440 /// The sources a clip actually names, with the clips reindexed onto them
1441 /// -- what a save writes. Indexes are forever *inside* a session (see
1442 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1443 /// entry behind; writing that orphan to a project file would let a file
1444 /// nothing plays refuse a future load. New indexes are assigned in order of
1445 /// first use -- lane by lane, in display order -- so the same project always
1446 /// emits the same bytes.
1447 ///
1448 /// Every lane comes out, in display order and with its kind: that is what a
1449 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1450 /// takes back.
1451 ///
1452 /// The equalizer and colour tables are pruned the same way and for the same
1453 /// reason: an undone [`set_eq`](Project::set_eq) or
1454 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1455 /// and this is the one moment they can go -- the indexes that survive it are
1456 /// only the ones a clip names.
1457 ///
1458 /// One exception, and it is the emptied timeline's: a project no clip plays
1459 /// from still keeps its first source, if it has one. A file is what a
1460 /// reopened project scaffolds itself from -- the frame rate is written
1461 /// nowhere else -- so a save that pruned the last of them would write a
1462 /// project that cannot be loaded back at all.
1463 ///
1464 /// What comes out is *not* ordered by anything a reader may assume: first
1465 /// use, lane by lane, means the entry at index 0 can be a still or a song
1466 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1467 /// picks its rate and its audio reference by what a source *is*, never by
1468 /// where it sits.
1469 pub fn without_orphan_sources(&self) -> Parts {
1470 let mut moved = vec![None; self.sources.len()];
1471 let mut sources = Vec::new();
1472 let mut moved_eq = vec![None; self.eq.len()];
1473 let mut eq = Vec::new();
1474 let mut moved_color = vec![None; self.color.len()];
1475 let mut color = Vec::new();
1476 let mut moved_transform = vec![None; self.transform.len()];
1477 let mut transform = Vec::new();
1478 let mut lanes = self.lanes.clone();
1479 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1480 let old = c.source;
1481 c.source = match moved[old] {
1482 Some(new) => new,
1483 None => {
1484 sources.push(self.sources[old].clone());
1485 moved[old] = Some(sources.len() - 1);
1486 sources.len() - 1
1487 }
1488 };
1489 if let Some(old) = c.eq.map(usize::from) {
1490 c.eq = Some(match moved_eq[old] {
1491 Some(new) => new,
1492 None => {
1493 eq.push(self.eq[old].clone());
1494 let new = (eq.len() - 1) as u16;
1495 moved_eq[old] = Some(new);
1496 new
1497 }
1498 });
1499 }
1500 if let Some(old) = c.color.map(usize::from) {
1501 c.color = Some(match moved_color[old] {
1502 Some(new) => new,
1503 None => {
1504 color.push(self.color[old]);
1505 let new = (color.len() - 1) as u16;
1506 moved_color[old] = Some(new);
1507 new
1508 }
1509 });
1510 }
1511 if let Some(old) = c.transform.map(usize::from) {
1512 c.transform = Some(match moved_transform[old] {
1513 Some(new) => new,
1514 None => {
1515 transform.push(self.transform[old]);
1516 let new = (transform.len() - 1) as u16;
1517 moved_transform[old] = Some(new);
1518 new
1519 }
1520 });
1521 }
1522 }
1523 if sources.is_empty() {
1524 sources.extend(self.sources.first().cloned());
1525 }
1526 (
1527 sources,
1528 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1529 // comes out for one is an empty list, and its *place* in the display
1530 // order is what a save writes it for. What is on it travels beside
1531 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1532 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1533 eq,
1534 color,
1535 transform,
1536 )
1537 }
1538
1539 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1540 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1541 /// track moves by it, which is what makes it a different control from a
1542 /// clip's equalizer (one frequency range of one take) and from the master
1543 /// volume (what this machine monitors at, which no file carries).
1544 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1545 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1546 }
1547
1548 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1549 /// One undo step like every other edit -- it is in the lane list, so an
1550 /// undo restores it with the rest. `false`, and no history, for a lane that
1551 /// is not there, for a value that is not finite, and for one already set.
1552 ///
1553 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1554 /// a value nobody reads: words have no loudness, so a slider that appeared
1555 /// to move one would be a control with no effect. (A video lane's gain is
1556 /// meaningless in the same way but is kept settable: it is the pair `A1`
1557 /// carries for a take, and mixing reads it off the audio lane alone.)
1558 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1559 let Some(i) = self.index(lane) else {
1560 return false;
1561 };
1562 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1563 return false;
1564 }
1565 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1566 if self.lanes[i].gain_db == db {
1567 return false;
1568 }
1569 self.snapshot();
1570 self.lanes[i].gain_db = db;
1571 true
1572 }
1573
1574 /// Every lane's volume in dB, in display order -- what a save writes,
1575 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1576 ///
1577 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1578 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1579 /// one): a save zips the two lists, so a lane that is in one and not the
1580 /// other would hand every track below it the volume of the track above.
1581 pub fn lane_gains(&self) -> Vec<f32> {
1582 self.lanes.iter().map(|l| l.gain_db).collect()
1583 }
1584
1585 /// What is placed on every lane, in display order and in step with
1586 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1587 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1588 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1589 ///
1590 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1591 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1592 /// clip's source there is no orphan to prune and no index to move.
1593 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1594 self.lanes.iter().map(|l| l.subs.clone()).collect()
1595 }
1596
1597 /// The placements a *load* puts back, one list per lane in display order --
1598 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1599 /// same reason. Called *after*
1600 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1601 /// names.
1602 ///
1603 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1604 /// like it, by name and in release, because it is the same untrusted file:
1605 /// a placement on a lane that is not a subtitle lane, an empty span or an
1606 /// empty window, a track the palette does not have, a span running past the
1607 /// last frame there is, and a lane that is out of order or overlaps itself
1608 /// ([`place_sub`] refuses every one of those on the live timeline).
1609 ///
1610 /// [`place_sub`]: Project::place_sub
1611 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1612 let names = handles(&self.lanes);
1613 let palette = self.subtitles.len();
1614 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1615 let name = lane.label();
1616 if list.is_empty() {
1617 continue;
1618 }
1619 if data.kind != LaneKind::Subtitle {
1620 return Err(format!(
1621 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1622 subtitle track",
1623 list.len()
1624 )
1625 .into());
1626 }
1627 for s in &list {
1628 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1629 return Err(format!(
1630 "{name} caption at {} is empty: {} frames of [{}, {})",
1631 s.start, s.frames, s.in_us, s.out_us
1632 )
1633 .into());
1634 }
1635 if s.track >= palette {
1636 return Err(format!(
1637 "{name} caption at {} names subtitle track {} of {palette}",
1638 s.start, s.track
1639 )
1640 .into());
1641 }
1642 if s.start.checked_add(s.frames).is_none() {
1643 return Err(format!(
1644 "{name} caption at {} runs past the last frame there is",
1645 s.start
1646 )
1647 .into());
1648 }
1649 }
1650 if !subs_sorted_disjoint(&list) {
1651 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1652 }
1653 data.subs = list;
1654 // The counter also has to clear the ids these captions carry: this
1655 // is the door a load's placements come through, *after*
1656 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1657 // a hand-grouped caption may carry the highest id in the file.
1658 self.next_link = self.next_link.max(
1659 data.subs
1660 .iter()
1661 .filter_map(|s| s.link)
1662 .max()
1663 .map_or(0, |m| m.saturating_add(1)),
1664 );
1665 }
1666 Ok(self)
1667 }
1668
1669 /// The mix settings a *load* puts back: lane volumes in display order (a
1670 /// short list leaves the rest at unity) and the master limiter, both
1671 /// clamped as their setters clamp them.
1672 ///
1673 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1674 /// setters push an undo step, and a project that arrives one undo away from
1675 /// a state it was never in is a project whose first ctrl+z is a surprise.
1676 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1677 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1678 if db.is_finite() {
1679 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1680 }
1681 }
1682 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1683 self
1684 }
1685
1686 /// The HDR rendition a *load* puts back -- the same door
1687 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1688 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1689 self.tone = preset;
1690 self
1691 }
1692
1693 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1694 /// project setting, not a clip's: one picture, one look
1695 /// ([`crate::tonemap::Preset`]).
1696 pub fn tone(&self) -> crate::tonemap::Preset {
1697 self.tone
1698 }
1699
1700 /// Sets it. `false` for the one already in force, which is what keeps a
1701 /// re-pick of the current rendition from costing a reseek.
1702 ///
1703 /// corner-cut: not an undo step, for the reason the limiter and the project
1704 /// resolution are not -- it is not in the lane list the history snapshots.
1705 /// Upgrade path is the same one: a history entry holding the project's own
1706 /// settings beside the lanes.
1707 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1708 if self.tone == preset {
1709 return false;
1710 }
1711 self.tone = preset;
1712 true
1713 }
1714
1715 /// The subtitle tracks a *load* puts back, in the order they were saved --
1716 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1717 /// the same reason.
1718 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1719 self.subtitles = tracks;
1720 self
1721 }
1722
1723 /// What this timeline shows over the picture, in the order they were added:
1724 /// what a front-end lists and what a save writes.
1725 pub fn subtitles(&self) -> &[SubtitleTrack] {
1726 &self.subtitles
1727 }
1728
1729 /// Adds a track, unless the very same one -- same file, same track number
1730 /// inside it -- is already on the list. `false` for that repeat: importing
1731 /// the same `.srt` twice is one subtitle track, not two identical ones.
1732 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1733 if self
1734 .subtitles
1735 .iter()
1736 .any(|t| t.path == track.path && t.track == track.track)
1737 {
1738 return false;
1739 }
1740 self.subtitles.push(track.clone());
1741 true
1742 }
1743
1744 /// Takes the track at `idx` off the list -- what a row's own remove goes
1745 /// through, so whatever an import added can be taken back out. Refused by
1746 /// name for a row this project does not have, rather than a silent no-op:
1747 /// a front-end holding a stale index has picked the wrong row and needs to
1748 /// hear it.
1749 ///
1750 /// Every index past `idx` moves down by one, as [`remove_source`](
1751 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1752 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1753 /// it, or it names a different track afterwards. The placements on the
1754 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1755 /// index into this very list, so every one past `idx` is walked down with
1756 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1757 /// for its clips, for its reason.
1758 ///
1759 /// Refused, changing nothing, while anything placed on a subtitle lane
1760 /// plays *this* row: the placement would have to be deleted or retargeted,
1761 /// and either one is an edit nobody asked for. The refusal names the lane
1762 /// and the frame it is at, up to three of them --
1763 /// [`remove_source`](Project::remove_source) refuses the same way for the
1764 /// same silent corruption.
1765 ///
1766 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1767 /// history snapshots hold the lane list and subtitles are not on it
1768 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1769 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1770 /// door, which reads the subtitles of a file and nothing else -- and not a
1771 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1772 /// entry holding the project's own settings beside the lanes. The history
1773 /// is *cleared* rather than kept, as a source removal clears it: the
1774 /// snapshots hold the indexes as they were before the reindex, so an undo
1775 /// into one would put every placement past `idx` on the wrong track.
1776 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1777 if idx >= self.subtitles.len() {
1778 return Err(format!("there is no subtitle track {idx} to remove").into());
1779 }
1780 let placed: Vec<String> = handles(&self.lanes)
1781 .into_iter()
1782 .zip(&self.lanes)
1783 .flat_map(|(lane, data)| {
1784 data.subs
1785 .iter()
1786 .filter(move |s| s.track == idx)
1787 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1788 })
1789 .take(3)
1790 .collect();
1791 if !placed.is_empty() {
1792 return Err(format!(
1793 "{} is on the timeline ({}): delete those clips first",
1794 self.track_name(idx),
1795 placed.join(", ")
1796 )
1797 .into());
1798 }
1799 self.subtitles.remove(idx);
1800 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1801 if s.track > idx {
1802 s.track -= 1;
1803 }
1804 }
1805 self.history.clear();
1806 Ok(())
1807 }
1808
1809 /// What a refusal calls a palette row: the name the panel shows, and the
1810 /// index alone for a row that is not there.
1811 fn track_name(&self, track: usize) -> String {
1812 self.subtitles
1813 .get(track)
1814 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1815 }
1816
1817 /// The subtitle lanes in display order -- what a front-end lays out and
1818 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1819 /// [`audio_lanes`](Project::audio_lanes).
1820 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1821 self.lanes()
1822 .into_iter()
1823 .filter(|l| l.kind == LaneKind::Subtitle)
1824 .collect()
1825 }
1826
1827 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1828 /// for a subtitle track, and empty for every other lane and for one that is
1829 /// not there.
1830 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1831 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1832 }
1833
1834 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1835 /// twin, with one deliberate difference: it **refuses** an overlap instead
1836 /// of overwriting what it lands on.
1837 ///
1838 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1839 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1840 /// carries is a *window of a track* and where the hand let go, and the
1841 /// second of those is the argument. So a caller builds the placement once
1842 /// (from the palette row it dragged) and drops it at as many frames as it
1843 /// likes without rewriting the field each time.
1844 ///
1845 /// A picture placed over a picture hides it and the hidden one is still
1846 /// there to drag back out; two captions in one frame are two lines nobody
1847 /// asked to stack, and the words that lost are gone from the screen with
1848 /// nothing to show for it. So the refusal names the placement in the way,
1849 /// and the caller picks another frame or another lane -- which is what a
1850 /// second subtitle lane is for.
1851 ///
1852 /// One undo step on success, and none on any refusal: an empty window or an
1853 /// empty span, a track the palette does not have
1854 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1855 /// subtitle lane, a span that would run past the last frame there is, and
1856 /// the overlap above.
1857 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1858 if lane.kind != LaneKind::Subtitle {
1859 return Err(format!(
1860 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1861 the others",
1862 lane.label()
1863 )
1864 .into());
1865 }
1866 let Some(i) = self.index(lane) else {
1867 return Err(format!("there is no {} to place on", lane.label()).into());
1868 };
1869 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1870 return Err(format!(
1871 "that placement is empty: {} frames of [{}, {})",
1872 sub.frames, sub.in_us, sub.out_us
1873 )
1874 .into());
1875 }
1876 if sub.track >= self.subtitles.len() {
1877 return Err(format!(
1878 "it names subtitle track {} of {}",
1879 sub.track,
1880 self.subtitles.len()
1881 )
1882 .into());
1883 }
1884 // The placement belongs to no group, for [`place`]'s reason: a caption
1885 // dragged out of the palette arrives alone, and grouping it with what
1886 // is under it is a hand's decision ([`Project::group_all`]).
1887 let sub = SubClip {
1888 start: at,
1889 link: None,
1890 ..sub
1891 };
1892 if at.checked_add(sub.frames).is_none() {
1893 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1894 }
1895 if let Some(other) = self.lanes[i]
1896 .subs
1897 .iter()
1898 .find(|o| o.end() > sub.start && o.start < sub.end())
1899 {
1900 return Err(format!(
1901 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1902 on another subtitle track",
1903 lane.label(),
1904 other.start,
1905 other.start,
1906 other.end()
1907 )
1908 .into());
1909 }
1910 self.snapshot();
1911 let subs = &mut self.lanes[i].subs;
1912 let idx = subs.partition_point(|o| o.start < sub.start);
1913 subs.insert(idx, sub);
1914 debug_assert!(subs_sorted_disjoint(subs));
1915 Ok(())
1916 }
1917
1918 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1919 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1920 /// refused an overlap where that one clamps to it, for
1921 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1922 /// still and no picture under it that a landing would hide, so "as far as
1923 /// it goes" would silently be a frame nobody named.
1924 ///
1925 /// A caption *in* a group drags the group: one delta for every member --
1926 /// its clips and its other captions -- clamped to the room each of them
1927 /// has, exactly as a clip's drag always has. That is the point of putting
1928 /// a caption in a group: the words go where the picture goes.
1929 ///
1930 /// The window travels untouched: a caption dragged later says the same
1931 /// words later, exactly as a clip dragged later plays the same pictures
1932 /// later.
1933 ///
1934 /// One undo step on success; nothing changed and no step on a refusal --
1935 /// an index that is not there, a lane that is not a subtitle lane or is not
1936 /// there, and (for a caption in no group) an overlap. A drop that changes
1937 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1938 /// up and put it back has done nothing wrong, and a front-end showing every
1939 /// `Err` would say so.
1940 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1941 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1942 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1943 };
1944 if to.kind != LaneKind::Subtitle {
1945 return Err(format!(
1946 "{} is not a subtitle track: a caption cannot play on it",
1947 to.label()
1948 )
1949 .into());
1950 }
1951 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1952 return Err(format!("there is no {} to move onto", to.label()).into());
1953 };
1954 if (here, start) == (dest, sub.start) {
1955 // A pick-up-put-back: the drag ended where it began, which is not a
1956 // mistake to name -- `Ok`, and no undo step, because nothing
1957 // changed. A refusal here would toast a hand that did nothing.
1958 return Ok(());
1959 }
1960 if start.checked_add(sub.frames).is_none() {
1961 return Err(
1962 format!("a placement at frame {start} runs past the last frame there is").into(),
1963 );
1964 }
1965 // A grouped caption carries its group, clamped to the room the whole
1966 // group has rather than refused ([`Project::move_room]) -- one drag, one
1967 // delta, one undo step.
1968 let members = self.group_of(from, idx).expect("the subtitle was found");
1969 if !members.alone() {
1970 if members
1971 .subs
1972 .iter()
1973 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1974 {
1975 return Err(format!(
1976 "a group is one caption per track: {} already carries this group",
1977 to.label()
1978 )
1979 .into());
1980 }
1981 let want = i64::from(start) - i64::from(sub.start);
1982 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1983 return Err(format!(
1984 "another placement already covers those frames on {}",
1985 to.label()
1986 )
1987 .into());
1988 };
1989 let delta = want.clamp(lo, hi);
1990 self.snapshot();
1991 for &(l, i) in &members.clips {
1992 let c = &mut self.lanes[l].clips[i];
1993 c.start = (i64::from(c.start) + delta) as u32;
1994 }
1995 for &(l, i) in &members.subs {
1996 let s = &mut self.lanes[l].subs[i];
1997 s.start = (i64::from(s.start) + delta) as u32;
1998 }
1999 let moved = self.lanes[here].subs.remove(idx);
2000 let subs = &mut self.lanes[dest].subs;
2001 let at = subs.partition_point(|o| o.start < moved.start);
2002 subs.insert(at, moved);
2003 debug_assert!(subs_sorted_disjoint(subs));
2004 debug_assert!(members
2005 .clips
2006 .iter()
2007 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
2008 return Ok(());
2009 }
2010 let moved = SubClip { start, ..sub };
2011 if let Some(other) = self.lanes[dest]
2012 .subs
2013 .iter()
2014 .enumerate()
2015 .find(|&(j, o)| {
2016 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
2017 })
2018 .map(|(_, o)| *o)
2019 {
2020 return Err(format!(
2021 "the {} subtitle at frame {} already covers [{}, {})",
2022 to.label(),
2023 other.start,
2024 other.start,
2025 other.end()
2026 )
2027 .into());
2028 }
2029 self.snapshot();
2030 self.lanes[here].subs.remove(idx);
2031 let subs = &mut self.lanes[dest].subs;
2032 let at = subs.partition_point(|o| o.start < moved.start);
2033 subs.insert(at, moved);
2034 debug_assert!(subs_sorted_disjoint(subs));
2035 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
2036 Ok(())
2037 }
2038
2039 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
2040 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
2041 /// pulling an edge past what is legal means "as far as it goes".
2042 ///
2043 /// The window follows the edge, in the seconds the frames are worth at
2044 /// `fps`: a head pulled in starts the caption later *in its track* (the
2045 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
2046 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
2047 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
2048 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
2049 /// needed here and nowhere else in this file, because a trim is the only
2050 /// edit that changes a *duration*.
2051 ///
2052 /// The walls: one frame always survives, an edge never crosses the
2053 /// neighbouring subtitle on its own lane, a head never walks back past the
2054 /// track's own start (`in_us` of 0), and a tail never runs past the last
2055 /// cue the track has -- which is the source length a media trim needs a
2056 /// caller's table for, and which this one can simply read.
2057 ///
2058 /// `Err`, with nothing changed and no undo step, for an index that is not
2059 /// there and an unusable `fps`. An edge that ends up where it already was
2060 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2061 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2062 /// reason: a drag that stops at a wall is not a mistake to report.
2063 pub fn trim_sub(
2064 &mut self,
2065 lane: Lane,
2066 idx: usize,
2067 edge: Edge,
2068 to: u32,
2069 fps: f64,
2070 ) -> crate::Result<()> {
2071 if !(fps.is_finite() && fps > 0.0) {
2072 return Err(format!("{fps} is not a frame rate to trim against").into());
2073 }
2074 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2075 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2076 };
2077 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2078 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2079 };
2080 let to = to.clamp(lo, hi);
2081 let at = match edge {
2082 Edge::Start => sub.start,
2083 Edge::End => sub.end(),
2084 };
2085 if to == at {
2086 // The edge is where it was asked to go -- either the hand did not
2087 // move it, or the clamp above stopped it at a wall it was already
2088 // standing against. Both are a drag that changed nothing: `Ok`, no
2089 // undo step, and no toast for a box that simply stopped moving.
2090 return Ok(());
2091 }
2092 self.snapshot();
2093 let members = self.group_of(lane, idx).expect("the subtitle was found");
2094 let i = self.index(lane).expect("the subtitle was found on it");
2095 let s = &mut self.lanes[i].subs[idx];
2096 match edge {
2097 // The words that stay are the words that were there, so the window
2098 // moves with the head -- a trim, not a slip.
2099 Edge::Start => {
2100 // Clamped to a window that is still a window: the walls above
2101 // are frames and the rounding between the two clocks is not
2102 // exact, and neither is a caller's hand-built placement.
2103 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2104 .clamp(0, s.out_us - 1);
2105 s.frames = s.end() - to;
2106 s.start = to;
2107 }
2108 Edge::End => {
2109 s.out_us =
2110 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2111 s.frames = to - s.start;
2112 }
2113 }
2114 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2115 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2116 // A caption in a group drags its group's edge with it, exactly as a
2117 // clip's trim does: one delta, each member clamped to its own room.
2118 // No source table to grow by, which only tightens how far a member may
2119 // follow -- never whether it may.
2120 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
2121 Ok(())
2122 }
2123
2124 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2125 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2126 /// drawing the box during a drag asks. `None` for an index that is not
2127 /// there.
2128 pub fn trim_sub_room(
2129 &self,
2130 lane: Lane,
2131 idx: usize,
2132 edge: Edge,
2133 fps: f64,
2134 ) -> Option<(u32, u32)> {
2135 let subs = self.sub_lane(lane);
2136 let s = *subs.get(idx)?;
2137 // How many timeline frames a stretch of the track is worth, which is
2138 // what turns its two walls -- its own start, and its last cue -- into
2139 // frames. A rate that is not a rate leaves the window where it is.
2140 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2141 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
2142 false => 0,
2143 };
2144 Some(match edge {
2145 Edge::Start => (
2146 s.start
2147 .saturating_sub(frames_of(s.in_us))
2148 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2149 s.end() - 1,
2150 ),
2151 Edge::End => {
2152 // Out to the end of the track it reads, and never over the
2153 // subtitle behind it. A track the palette no longer has (or one
2154 // with no cues at all) may not grow, exactly as a source with no
2155 // entry in a media trim's table may not.
2156 let track_end = self
2157 .subtitles
2158 .get(s.track)
2159 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2160 .unwrap_or(s.out_us);
2161 (
2162 s.start + 1,
2163 s.start
2164 .saturating_add(frames_of(track_end - s.in_us).max(1))
2165 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2166 )
2167 }
2168 })
2169 }
2170
2171 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2172 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2173 /// `false` for an index that is not there (which a lane that is not a
2174 /// subtitle lane always is).
2175 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2176 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2177 return false;
2178 };
2179 self.snapshot();
2180 self.lanes[i].subs.remove(idx);
2181 true
2182 }
2183
2184 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2185 /// window of its track, clipped to that window and shifted to where the
2186 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2187 /// carried through the picture's spans -- this is its twin for a track that
2188 /// is placed on a lane of its own, and it is what a preview draws and what
2189 /// an export of the lane would write.
2190 ///
2191 /// Cut, not stretched: a cue half inside the window keeps the half that is
2192 /// inside, and a cue wholly outside it is gone -- the same rule the media
2193 /// spans follow. `fps` is the timeline's rate, needed here because a
2194 /// placement's *position* is in frames while its words are in microseconds.
2195 ///
2196 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2197 /// of their cues, no file opened), which is how a front-end asks it.
2198 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2199 if !(fps.is_finite() && fps > 0.0) {
2200 return Vec::new();
2201 }
2202 let mut out = Vec::new();
2203 for s in self.sub_lane(lane) {
2204 let Some(track) = self.subtitles.get(s.track) else {
2205 // A placement whose track was taken off the palette
2206 // ([`Project::remove_subtitles`]) shows nothing rather than
2207 // showing another track's words.
2208 continue;
2209 };
2210 // Where the placement's own first microsecond lands on the
2211 // timeline, and how many microseconds of timeline one microsecond
2212 // of the window is worth: the placement's own proportion, which a
2213 // group's re-rate changes (the frames compress, the window does
2214 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2215 // every cue lands where it always did; at 2x the words cross the
2216 // screen in half the time, cue for cue.
2217 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2218 let onto = |t: i64| {
2219 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2220 };
2221 for cue in &track.cues {
2222 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2223 if b <= a {
2224 continue; // wholly outside the window this placement keeps
2225 }
2226 out.push(SubtitleCue {
2227 start_us: onto(a),
2228 end_us: onto(b),
2229 text: cue.text.clone(),
2230 image: cue.image.clone(),
2231 });
2232 }
2233 }
2234 // The placements come in timeline order, but two lanes' worth (or a
2235 // track whose cues a window reordered) do not.
2236 out.sort_by_key(|cue| cue.start_us);
2237 out
2238 }
2239
2240 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2241 /// lanes is multiplied by on its way into the mix: the same lanes in the
2242 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2243 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2244 /// the bit-exact path.
2245 pub fn audio_gains(&self) -> Vec<f32> {
2246 self.audio_lanes()
2247 .into_iter()
2248 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2249 .collect()
2250 }
2251
2252 /// The master limiter the mix is summed through. A project setting, not a
2253 /// clip's and not a lane's: there is one mix.
2254 pub fn limiter(&self) -> Limiter {
2255 self.limiter
2256 }
2257
2258 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2259 /// for a setting already in force.
2260 ///
2261 /// corner-cut: not an undo step, for the reason the project resolution is not
2262 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2263 /// lane list the history snapshots. Upgrade path is a history entry that
2264 /// holds the mix settings beside the lanes.
2265 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2266 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2267 if self.limiter == limiter {
2268 return false;
2269 }
2270 self.limiter = limiter;
2271 true
2272 }
2273
2274 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2275 /// plays flat (and for an index that is not there) -- what a feeder and an
2276 /// export ask before they build an [`crate::eq::EqState`].
2277 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2278 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2279 }
2280
2281 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2282 /// take them off. One undo step, like every other edit. `false` -- and no
2283 /// history -- for an index that is not there and for params holding a value
2284 /// that is not finite, which is the one thing the file format could not
2285 /// write and read back.
2286 ///
2287 /// Settings equal to ones already in the table share their entry, so a
2288 /// project that puts the same curve on twenty clips writes it once.
2289 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2290 if idx >= self.lane(lane).len() {
2291 return false;
2292 }
2293 let slot = match params {
2294 None => None,
2295 Some(params) => {
2296 if !finite(&params) {
2297 return false;
2298 }
2299 Some(match self.eq.iter().position(|p| *p == params) {
2300 Some(at) => at as u16,
2301 // corner-cut: the table is append-only within a session (see
2302 // the module docs) and `Clip::eq` is a u16, so the 65535th
2303 // *distinct* setting of one session is refused rather than
2304 // silently aliased. Upgrade path if a UI ever drags a slider
2305 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2306 // snapshot the table into the history and compact it here.
2307 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2308 None => {
2309 self.eq.push(params);
2310 (self.eq.len() - 1) as u16
2311 }
2312 })
2313 }
2314 };
2315 self.snapshot();
2316 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2317 true
2318 }
2319
2320 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2321 /// ungraded (and for an index that is not there) -- what the renderer and
2322 /// the export ask before they call [`crate::color::apply_yuv`].
2323 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2324 self.color
2325 .get(usize::from(self.lane(lane).get(idx)?.color?))
2326 }
2327
2328 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2329 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2330 /// (and no history) for an index that is not there or a value that is not
2331 /// finite, and equal settings share a table entry.
2332 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2333 self.write_color(lane, idx, params, true)
2334 }
2335
2336 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2337 /// one pointer drag, whose first write (a plain `set_color`) already took the
2338 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2339 /// not one per pixel -- and undoing it lands where the hand picked it up.
2340 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2341 self.write_color(lane, idx, params, false)
2342 }
2343
2344 fn write_color(
2345 &mut self,
2346 lane: Lane,
2347 idx: usize,
2348 params: Option<ColorParams>,
2349 snapshot: bool,
2350 ) -> bool {
2351 if idx >= self.lane(lane).len() {
2352 return false;
2353 }
2354 let slot = match params {
2355 None => None,
2356 Some(params) => {
2357 if !color_finite(&params) {
2358 return false;
2359 }
2360 Some(match self.color.iter().position(|p| *p == params) {
2361 Some(at) => at as u16,
2362 // corner-cut: the 65535th *distinct* grade of one session is
2363 // refused rather than silently aliased, exactly as `set_eq`
2364 // refuses the 65535th curve; same upgrade path.
2365 None if self.color.len() >= usize::from(u16::MAX) => return false,
2366 None => {
2367 self.color.push(params);
2368 (self.color.len() - 1) as u16
2369 }
2370 })
2371 }
2372 };
2373 if snapshot {
2374 self.snapshot();
2375 }
2376 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2377 true
2378 }
2379
2380 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2381 /// policy's own placement (and for an index that is not there) -- what the
2382 /// renderer and the export ask before they place its picture.
2383 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2384 self.transform
2385 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2386 }
2387
2388 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2389 /// step, `false` (and no history) for an index that is not there or a
2390 /// value that is not finite, and equal settings share a table entry.
2391 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2392 self.write_transform(lane, idx, params, true)
2393 }
2394
2395 /// [`set_transform`](Self::set_transform) without the undo step, for
2396 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2397 /// one drag on a position/scale/rotate/crop control are one undo, not one
2398 /// per pixel.
2399 pub fn set_transform_live(
2400 &mut self,
2401 lane: Lane,
2402 idx: usize,
2403 params: Option<TransformParams>,
2404 ) -> bool {
2405 self.write_transform(lane, idx, params, false)
2406 }
2407
2408 fn write_transform(
2409 &mut self,
2410 lane: Lane,
2411 idx: usize,
2412 params: Option<TransformParams>,
2413 snapshot: bool,
2414 ) -> bool {
2415 if idx >= self.lane(lane).len() {
2416 return false;
2417 }
2418 let slot = match params {
2419 None => None,
2420 Some(params) => {
2421 if !transform_finite(&params) {
2422 return false;
2423 }
2424 Some(match self.transform.iter().position(|p| *p == params) {
2425 Some(at) => at as u16,
2426 // corner-cut: the 65535th *distinct* transform of one
2427 // session is refused rather than silently aliased,
2428 // exactly as `write_color` refuses the 65535th grade;
2429 // same upgrade path.
2430 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2431 None => {
2432 self.transform.push(params);
2433 (self.transform.len() - 1) as u16
2434 }
2435 })
2436 }
2437 };
2438 if snapshot {
2439 self.snapshot();
2440 }
2441 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2442 true
2443 }
2444
2445 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2446 /// index that is not there, which is what every clip starts at anyway.
2447 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2448 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2449 }
2450
2451 /// Sets it, for the clip **and its whole group**: a link is one span on
2452 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2453 /// from its sound would be a group no save could load. One snapshot, so the
2454 /// group's change is one [`Project::undo`].
2455 ///
2456 /// The source range is untouched -- a speed says how many timeline frames
2457 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2458 /// split still address the file afterwards.
2459 ///
2460 /// Refused, changing nothing and costing no undo step, when the clip would
2461 /// grow into the one after it on its own lane: slowing a clip down makes it
2462 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2463 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2464 /// something a user can go and fix. Also for an index that is not there.
2465 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2466 self.write_speed(lane, idx, speed, true)
2467 }
2468
2469 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2470 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2471 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2472 /// not one per rate it passed through -- exactly as
2473 /// [`set_color_live`](Self::set_color_live) is for a slider.
2474 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2475 self.write_speed(lane, idx, speed, false)
2476 }
2477
2478 fn write_speed(
2479 &mut self,
2480 lane: Lane,
2481 idx: usize,
2482 speed: Speed,
2483 snapshot: bool,
2484 ) -> crate::Result<()> {
2485 let Some(members) = self.group_of(lane, idx) else {
2486 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2487 };
2488 let labels = handles(&self.lanes);
2489 // The clip the hand is holding is the group's clock: everything else
2490 // in the group, caption members included, re-times by the ratio its new
2491 // rate gives its own frames. The clips take the rate itself; a caption
2492 // has none, so it takes the *ratio* -- its span on the timeline
2493 // compresses or stretches about the held clip's head, while the words
2494 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2495 // timeline moves, the track does not).
2496 let Some(held) = self.lane(lane).get(idx).copied() else {
2497 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2498 };
2499 // The same per-member piece `speeded_playhead` builds for this op,
2500 // asked here instead of read there -- a caption's length comes from
2501 // the map's own ends (`end - start`), never `round(len * ratio)`
2502 // separately, which is what let the two answers drift apart by a
2503 // frame.
2504 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2505 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2506 let retimed = |s: SubClip| {
2507 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2508 let start = map.apply(s.start);
2509 let end = map.apply(s.end()).max(start.saturating_add(1));
2510 SubClip { start, frames: end - start, ..s }
2511 };
2512 for &(l, i) in &members.clips {
2513 let clips = &self.lanes[l].clips;
2514 let mut moved = clips[i];
2515 moved.speed = speed;
2516 if let Some(next) = clips.get(i + 1)
2517 && moved.end() > next.start
2518 {
2519 let name = labels[l].label();
2520 return Err(format!(
2521 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2522 move it along, or trim this one first",
2523 moved.end(),
2524 next.start
2525 )
2526 .into());
2527 }
2528 }
2529 // ...and the captions, against their own lanes' captions: a stretch
2530 // that runs one into its neighbour is refused for the clip arm's
2531 // reason -- a lane may not overlap itself -- and by name like it.
2532 let subs: Vec<(usize, usize, SubClip)> = members
2533 .subs
2534 .iter()
2535 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2536 .collect();
2537 for &(l, i, moved) in &subs {
2538 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2539 if j != i && moved.start < other.end() && other.start < moved.end() {
2540 return Err(format!(
2541 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2542 starts at {}: move it along, or trim this one first",
2543 labels[l].label(),
2544 self.lanes[l].subs[i].start,
2545 moved.end(),
2546 other.start
2547 )
2548 .into());
2549 }
2550 }
2551 }
2552 if snapshot {
2553 self.snapshot();
2554 }
2555 for (l, i) in members.clips {
2556 self.lanes[l].clips[i].speed = speed;
2557 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2558 }
2559 for (l, i, moved) in subs {
2560 self.lanes[l].subs[i] = moved;
2561 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2562 }
2563 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2564 Ok(())
2565 }
2566
2567 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2568 /// playhead standing at `at` -- read off the geometry **before** the
2569 /// write, because the old ends are gone after it. The question a card
2570 /// asks as its bar moves: the picture under the cursor has to stay the
2571 /// picture under the cursor, or the scene changes with the rate.
2572 ///
2573 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2574 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2575 /// a clip member keeps its own start and re-fits its length at the new
2576 /// rate -- its **old** rate against the new one, which is what the bar's
2577 /// live samples ask about as much as a first press does; a caption
2578 /// member scales about the held clip's start by the held clip's own
2579 /// proportion; and a playhead outside every member's old extent stays
2580 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2581 /// (or the room a stretch takes) absorbs the difference, not the
2582 /// playhead. `None` for an index that is not there.
2583 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2584 let members = self.group_of(lane, idx)?;
2585 let held = self.lane(lane).get(idx).copied()?;
2586 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2587 for &(l, i) in members.clips.iter().chain(&members.subs) {
2588 let (span, map) = match self
2589 .lanes[l]
2590 .clips
2591 .get(i)
2592 .filter(|_| members.clips.contains(&(l, i)))
2593 {
2594 // The clip's own span, re-fitted at its own old rate: one
2595 // piece of the map, anchored where the clip itself is. The
2596 // new length is the same *source* frames at the new rate --
2597 // len divided by it, never multiplied.
2598 Some(c) => (
2599 (c.start, c.start + c.frames()),
2600 TimelineMap::piece(
2601 (c.start, c.start + c.frames()),
2602 (
2603 c.start,
2604 c.start + (c.len() as f64 / new).round() as u32,
2605 ),
2606 ),
2607 ),
2608 // The caption's span, scaled about the held clip's head by
2609 // the held clip's proportion -- the offset the group keeps.
2610 None => {
2611 let s = self.lanes[l].subs.get(i)?;
2612 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2613 (
2614 (s.start, s.end()),
2615 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2616 )
2617 }
2618 };
2619 // The piece owns only its own old span: outside it the playhead
2620 // is another member's question, or nobody's.
2621 if (span.0..span.1).contains(&at) {
2622 return Some(map.apply(at));
2623 }
2624 }
2625 Some(at)
2626 }
2627
2628 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2629 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2630 /// every clip starts at anyway.
2631 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2632 self.lane(lane)
2633 .get(idx)
2634 .map_or(FitPolicy::default(), |c| c.fit)
2635 }
2636
2637 /// Sets it. One undo step like every other edit, and `false` (with no
2638 /// history) for an index that is not there. Unlike an eq or a grade there is
2639 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2640 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2641 if idx >= self.lane(lane).len() {
2642 return false;
2643 }
2644 self.snapshot();
2645 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2646 true
2647 }
2648
2649 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
2650 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
2651 /// history) for an index that is not there.
2652 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
2653 if idx >= self.lane(lane).len() {
2654 return false;
2655 }
2656 self.snapshot();
2657 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
2658 true
2659 }
2660
2661 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
2662 /// `false` (with no history) for an index that is not there, the way every
2663 /// other setter refuses.
2664 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2665 self.write_viz_paint(lane, idx, paint, true)
2666 }
2667
2668 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
2669 /// samples *inside* one pointer drag across the colour wheel, whose first
2670 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
2671 /// rolls back to. One drag is one undo, not one per sample.
2672 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
2673 self.write_viz_paint(lane, idx, paint, false)
2674 }
2675
2676 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
2677 if idx >= self.lane(lane).len() {
2678 return false;
2679 }
2680 if snapshot {
2681 self.snapshot();
2682 }
2683 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
2684 true
2685 }
2686
2687 /// Timeline frames of ramp-up from silence at the start of the clip at
2688 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2689 /// that has none.
2690 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2691 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2692 }
2693
2694 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2695 /// can shrink a clip's audible middle to nothing but never ask for more
2696 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2697 /// and `false` (no history) for an index that is not there.
2698 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2699 if idx >= self.lane(lane).len() {
2700 return false;
2701 }
2702 self.snapshot();
2703 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2704 clip.fade_in = frames.min(clip.frames());
2705 true
2706 }
2707
2708 /// Timeline frames of ramp-down to silence at the end of the clip at
2709 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2710 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2711 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2712 }
2713
2714 /// Sets it. Same promises as [`Project::set_fade_in`].
2715 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2716 if idx >= self.lane(lane).len() {
2717 return false;
2718 }
2719 self.snapshot();
2720 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2721 clip.fade_out = frames.min(clip.frames());
2722 true
2723 }
2724
2725 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2726 /// into its successor, at its own end. `0` for an index that is not
2727 /// there, same as a clip that has none.
2728 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2729 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2730 }
2731
2732 /// Sets it, clamped to the clip's own length and to how many frames its
2733 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2734 /// visible middle to nothing but never ask for more than the two clips
2735 /// between them have. `false` -- no history -- unless `lane` is video,
2736 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2737 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2738 /// them. One undo step like [`Project::set_fade_out`].
2739 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2740 if lane.kind != LaneKind::Video {
2741 return false;
2742 }
2743 let clips = self.lane(lane);
2744 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2745 return false;
2746 };
2747 if a.end() != b.start {
2748 return false;
2749 }
2750 let cap = a.frames().min(b.frames());
2751 self.snapshot();
2752 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2753 true
2754 }
2755
2756 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2757 /// after it, over `frames` timeline frames: sets `idx`'s
2758 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2759 /// each clamped to its own clip's length. `false` -- no history -- unless
2760 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2761 /// adjacent: the second's [`Clip::start`] is exactly the first's
2762 /// [`Clip::end`], no gap between them.
2763 ///
2764 /// This is the whole mechanism, not a stand-in for one: a *real*
2765 /// cross-fade -- both takes heard at once, blending -- is what two clips
2766 /// **overlapping** on separate lanes already get for free from the
2767 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2768 /// This call only shapes the edges of two clips already sitting
2769 /// end-to-end on *one* lane, so the join between them fades like one did.
2770 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2771 if lane.kind != LaneKind::Audio {
2772 return false;
2773 }
2774 let clips = self.lane(lane);
2775 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2776 return false;
2777 };
2778 if a.end() != b.start {
2779 return false;
2780 }
2781 self.snapshot();
2782 let clips = self.lane_mut(lane).expect("checked above");
2783 clips[idx].fade_out = frames.min(clips[idx].frames());
2784 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2785 true
2786 }
2787
2788 /// Every frame number on every lane rewritten onto a timeline counted at
2789 /// another rate: `k` is old timeline frames per new one, `counts` is how
2790 /// long each source is on the *new* timeline (indexed as
2791 /// [`Project::sources`] is), and the edit survives as the same seconds of
2792 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2793 /// the edit list, and the only thing that touches the frame numbers without
2794 /// being an edit anyone made.
2795 ///
2796 /// Every position -- a clip's start and its end alike -- goes through the
2797 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2798 /// stays a gap, and a take's picture and its sound land on the same frame on
2799 /// their two lanes: no lane can drift against another. A clip is then only
2800 /// ever made to *fit* the room its own start and end mapped to, never to
2801 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2802 /// below is the backstop for the one case that could: a slow clip so short
2803 /// that no source range fits its new room at all).
2804 ///
2805 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2806 /// onto the new grid, so a rate picked, unpicked and picked again is within
2807 /// a frame of where it started rather than back at it. Upgrade path is
2808 /// keeping the edit list at one reference rate and conforming on the way
2809 /// out, which every frame number in this module would then be measured in.
2810 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2811 for lane in &mut self.lanes {
2812 let mut cursor = 0;
2813 for clip in &mut lane.clips {
2814 let start = k.timeline_at(clip.start).max(cursor);
2815 // The room its own end mapped to -- never zero, since a clip is
2816 // never empty even on a grid too coarse to hold it.
2817 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2818 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2819 // Its footage, held inside the file's new length: a clip whose
2820 // out-point was the last frame of its source must not come out
2821 // of this naming a frame past the end -- that is a project that
2822 // would not open again ([`crate::PlaybackSession::open_project`]
2823 // refuses one by name).
2824 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2825 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2826 clip.start = start;
2827 clip.in_frame = in_frame;
2828 clip.out_frame = in_frame + len;
2829 cursor = clip.end();
2830 }
2831 // A subtitle's *window* is in microseconds and a rate change moves
2832 // no seconds, so only where it sits is remapped -- through the same
2833 // [`Rate::timeline_at`] every clip boundary goes through, so a
2834 // caption still starts on the frame its picture does.
2835 let mut cursor = 0;
2836 for sub in &mut lane.subs {
2837 let start = k.timeline_at(sub.start).max(cursor);
2838 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2839 sub.start = start;
2840 cursor = sub.end();
2841 }
2842 }
2843 }
2844
2845 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2846 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2847 ///
2848 /// A subtitle lane counts like any other: a caption placed past the last
2849 /// picture holds the timeline open under it, exactly as an `A2` running
2850 /// past `V1` does, rather than being silently clipped away by the length
2851 /// ([`crate::export::timeline_cues`] clips cues to this).
2852 pub fn timeline_frames(&self) -> u32 {
2853 self.lanes
2854 .iter()
2855 .filter_map(|l| match l.kind {
2856 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2857 _ => l.clips.last().map(Clip::end),
2858 })
2859 .max()
2860 .unwrap_or(0)
2861 }
2862
2863 /// The same, counting the *media* alone: where the last picture or sound
2864 /// runs out, with the captions over them ignored.
2865 ///
2866 /// What an export actually writes ends here -- the picture loop walks the
2867 /// composite spans and the file stops with them -- so this is the length a
2868 /// cue has to be inside of to be written at all (what
2869 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2870 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2871 /// thing is a picture or a sound, which is every timeline that has no
2872 /// caption hanging past the end of both.
2873 pub fn media_frames(&self) -> u32 {
2874 self.lanes
2875 .iter()
2876 .filter(|l| l.kind != LaneKind::Subtitle)
2877 .filter_map(|l| l.clips.last().map(Clip::end))
2878 .max()
2879 .unwrap_or(0)
2880 }
2881
2882 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2883 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2884 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2885 self.lane_spans(Lane::V1)
2886 }
2887
2888 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2889 // Timeline frames, not source ones: a box on a lane is as wide as the
2890 // clip is long *there*, which a speed halves or quadruples.
2891 self.lane(lane)
2892 .iter()
2893 .map(|c| (c.start, c.frames()))
2894 .collect()
2895 }
2896
2897 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2898 /// and past the end -- [`Project::span_at`] is the version that tells those
2899 /// two apart.
2900 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2901 let clips = self.lane(lane);
2902 let idx = at(clips, timeline_frame)?;
2903 Some((idx, source_frame(&clips[idx], timeline_frame)))
2904 }
2905
2906 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2907 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2908 self.map(Lane::V1, timeline_frame)
2909 }
2910
2911 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2912 /// it, or the gap running to the next clip (or to the end of the timeline,
2913 /// which is where a lane shorter than its neighbour keeps showing black).
2914 /// `None` at or past the end of the timeline, which is the only "nothing
2915 /// left" there is.
2916 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2917 let total = self.timeline_frames();
2918 if timeline_frame >= total {
2919 return None;
2920 }
2921 let clips = self.lane(lane);
2922 Some(match at(clips, timeline_frame) {
2923 Some(idx) => Span {
2924 start: timeline_frame,
2925 len: clips[idx].end() - timeline_frame,
2926 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2927 speed: clips[idx].speed,
2928 },
2929 None => Span {
2930 start: timeline_frame,
2931 speed: Speed::NORMAL,
2932 // The next placement, or the end of the timeline: a gap is
2933 // bounded by what comes after it, never by its own bookkeeping.
2934 len: clips
2935 .iter()
2936 .find(|c| c.start > timeline_frame)
2937 .map_or(total, |c| c.start)
2938 - timeline_frame,
2939 from: None,
2940 },
2941 })
2942 }
2943
2944 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2945 /// gaps included -- the whole play list, which is what an export walks.
2946 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2947 let mut out = Vec::new();
2948 let mut t = timeline_frame;
2949 while let Some(span) = self.span_at(lane, t) {
2950 t = span.end();
2951 out.push(span);
2952 }
2953 out
2954 }
2955
2956 /// What the *composite* shows from `timeline_frame` on -- the answer
2957 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2958 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2959 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2960 /// (the usual overlay convention). A frame no video lane covers is a gap,
2961 /// which is black however many lanes are above or below it.
2962 ///
2963 /// No blending, so exactly one lane is visible at a time and the composite
2964 /// is itself a span list -- which is why one decoder plays it, the same one
2965 /// a single-lane timeline uses, rather than N running at once.
2966 ///
2967 /// The span is cut short wherever a *higher* lane's clip starts, because
2968 /// from that frame on a different lane wins; that is what makes walking
2969 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2970 ///
2971 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2972 /// lanes would then be visible in one frame and the caller needs a decoder
2973 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2974 /// (this same walk, per lane) feeding N decoders.
2975 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2976 let total = self.timeline_frames();
2977 if timeline_frame >= total {
2978 return None;
2979 }
2980 let video = self.video_lanes();
2981 // The last covering lane is the winner; only the lanes above it can
2982 // interrupt what it shows.
2983 let winner = video
2984 .iter()
2985 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2986 let (from, speed, until) = match winner {
2987 Some(i) => {
2988 let clips = self.lane(video[i]);
2989 let idx = at(clips, timeline_frame).expect("just found above");
2990 (
2991 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2992 clips[idx].speed,
2993 clips[idx].end(),
2994 )
2995 }
2996 // Nothing covers it: black until something above the floor starts.
2997 None => (None, Speed::NORMAL, total),
2998 };
2999 let takeover = video[winner.map_or(0, |i| i + 1)..]
3000 .iter()
3001 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
3002 .map(|c| c.start)
3003 .min();
3004 Some(Span {
3005 start: timeline_frame,
3006 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
3007 from,
3008 speed,
3009 })
3010 }
3011
3012 /// The video lanes in display order, topmost last -- the order the composite
3013 /// rule counts in.
3014 fn video_lanes(&self) -> Vec<Lane> {
3015 self.lanes()
3016 .into_iter()
3017 .filter(|l| l.kind == LaneKind::Video)
3018 .collect()
3019 }
3020
3021 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
3022 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
3023 /// index on that lane. `None` over a gap and past the end. What a front-end
3024 /// asks to act on "the clip on screen" without re-deriving the rule.
3025 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
3026 let video = self.video_lanes();
3027 let winner = video
3028 .iter()
3029 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
3030 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
3031 }
3032
3033 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
3034 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
3035 /// answers "the clip on screen"; this answers it per lane, which is what
3036 /// walking the lanes for something to select needs.
3037 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
3038 at(self.lane(lane), timeline_frame)
3039 }
3040
3041 /// How the composite is graded at `timeline_frame`, so the picture playback
3042 /// converts and the one an export encodes are graded from one answer.
3043 /// `None` over a gap (black is black) and for a clip nobody has graded,
3044 /// which is the byte-identical path everywhere.
3045 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
3046 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3047 self.color_of(lane, idx)
3048 }
3049
3050 /// [`composite_color_at`](Self::composite_color_at)'s twin for
3051 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
3052 /// policy's own placement.
3053 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
3054 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
3055 self.transform_of(lane, idx)
3056 }
3057
3058 /// How the composite meets the project canvas at `timeline_frame`, so the
3059 /// picture playback composes and the one an export encodes are placed from
3060 /// one answer. `Fit` over a gap, where black is already the canvas.
3061 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
3062 self.composite_clip_at(timeline_frame)
3063 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
3064 }
3065
3066 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
3067 /// over a gap / a picture that is not a visualizer.
3068 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
3069 self.composite_clip_at(timeline_frame)
3070 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
3071 .unwrap_or(0)
3072 }
3073
3074 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
3075 /// `timeline_frame`, or zero over a gap / a picture that is not a
3076 /// visualizer.
3077 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
3078 self.composite_clip_at(timeline_frame)
3079 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
3080 .unwrap_or(0)
3081 }
3082
3083 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
3084 /// viewer sees from `timeline_frame` to the end, in order. What an export
3085 /// encodes and what playback walks at a clip boundary.
3086 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
3087 let mut out = Vec::new();
3088 let mut t = timeline_frame;
3089 while let Some(span) = self.composite_span_at(t) {
3090 t = span.end();
3091 out.push(span);
3092 }
3093 out
3094 }
3095
3096 /// Split every lane at `timeline_frame`, so that frame becomes the first
3097 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
3098 /// (`false`, no change) when no lane has a clip to split there -- at a
3099 /// placement's own start, in a gap, and past the end -- all of which would
3100 /// produce an empty clip or nothing at all.
3101 ///
3102 /// Lanes' halves share an id only where they are the *same* span: the lanes
3103 /// are edited apart, so the clip being cut here may start (or end)
3104 /// somewhere else on another lane, and a group id whose clips disagree
3105 /// about their span is not one take (see [`links_are_consistent`], which
3106 /// refuses to load one).
3107 ///
3108 /// Metadata only: no mapping changes, in any lane.
3109 pub fn split(&mut self, timeline_frame: u32) -> bool {
3110 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
3111 }
3112
3113 /// [`split`](Project::split), with the snapshot optional and the lanes
3114 /// named: a batch that has already taken a snapshot
3115 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3116 /// region and must still be one undo press, and a *scoped* batch must not
3117 /// cut a lane it was told to leave alone.
3118 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3119 let cut: Vec<Option<Clip>> = self
3120 .lanes
3121 .iter()
3122 .enumerate()
3123 .map(|(i, l)| {
3124 on.contains(&i)
3125 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3126 .flatten()
3127 })
3128 .collect();
3129 // The same question on the subtitle lanes, in their own arithmetic: a
3130 // razor cuts the captions with the picture, and a frame where only a
3131 // caption can be cut is still a cut.
3132 let cut_subs: Vec<bool> = self
3133 .lanes
3134 .iter()
3135 .enumerate()
3136 .map(|(i, l)| {
3137 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
3138 })
3139 .collect();
3140 // The links the captions carry, read before the room is opened below
3141 // -- `sub_open_room` takes the id off both halves, exactly as
3142 // `open_room` does for a clip, and the split hands the halves theirs
3143 // back afterwards.
3144 let sub_orig: Vec<Option<u32>> = self
3145 .lanes
3146 .iter()
3147 .zip(&cut_subs)
3148 .map(|(l, &cut)| {
3149 cut.then(|| {
3150 l.subs
3151 .iter()
3152 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3153 .and_then(|s| s.link)
3154 })
3155 .flatten()
3156 })
3157 .collect();
3158 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3159 return false;
3160 }
3161 if snapshot {
3162 self.snapshot();
3163 }
3164 for (data, _) in self
3165 .lanes
3166 .iter_mut()
3167 .zip(&cut_subs)
3168 .filter(|&(_, &cut)| cut)
3169 {
3170 // A split is room of no width: the halves keep their windows by
3171 // proportion and nothing moves.
3172 sub_open_room(&mut data.subs, timeline_frame, 0);
3173 debug_assert!(subs_sorted_disjoint(&data.subs));
3174 }
3175 // Each side is its own question, and the answer is the group the clip
3176 // already carried: the left half *keeps* its take's id -- the take the
3177 // frames before the cut still are -- and the right halves of one take
3178 // share one fresh id of their own, clips and captions alike. A lane
3179 // holding no group (a `place`ment, a caption nobody grouped) comes out
3180 // of the cut holding none, which is what it went in with. The captions'
3181 // own links were drawn above, before the room opened.
3182 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3183 let mut distinct: Vec<u32> = Vec::new();
3184 for id in orig.iter().chain(&sub_orig).flatten() {
3185 if !distinct.contains(id) {
3186 distinct.push(*id);
3187 }
3188 }
3189 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3190 let right_of =
3191 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
3192 for (l, data) in self.lanes.iter_mut().enumerate() {
3193 if !cut_subs[l] {
3194 continue;
3195 }
3196 // The pair the razor just made: they touch at the frame it cut.
3197 if let Some(idx) = data
3198 .subs
3199 .iter()
3200 .position(|s| s.end() == timeline_frame)
3201 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
3202 {
3203 data.subs[idx].link = sub_orig[l];
3204 data.subs[idx + 1].link = right_of(sub_orig[l]);
3205 }
3206 }
3207 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3208 // The lanes this call was not scoped to are not cut, whatever their
3209 // own clips would allow.
3210 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
3211 continue;
3212 };
3213 let mut tail = data.clips[idx];
3214 // Where the cut lands *in the file*, which is the clip's own rate
3215 // away from where it lands on the timeline. Both halves keep the
3216 // speed, and `splittable` has already refused any frame at which
3217 // the two would not add up to the one being cut.
3218 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3219 tail.start = timeline_frame;
3220 tail.link = right_of(orig[data_i]);
3221 // A split makes a new edge for each half, and a fade is a promise
3222 // about an edge: only the half that *kept* the original edge
3223 // keeps that fade, re-clamped to its own now-shorter length (a
3224 // cut inside the ramp shortens it, never leaves it pointing past
3225 // the clip it is on); the edge the cut itself made starts, or
3226 // ends, flat -- there was no silence there to ramp out of.
3227 tail.fade_in = 0;
3228 tail.fade_out = tail.fade_out.min(tail.frames());
3229 // A dissolve is a promise about the *end* edge, same as
3230 // `fade_out`: only the half that kept the clip's original end
3231 // (the tail) keeps it, re-clamped to its own now-shorter length;
3232 // the head's new end is the cut the razor just made, which starts
3233 // flat -- there was no successor to dissolve into there.
3234 tail.transition_out = tail.transition_out.min(tail.frames());
3235 data.clips[idx].out_frame = tail.in_frame;
3236 data.clips[idx].link = orig[data_i];
3237 data.clips[idx].fade_out = 0;
3238 data.clips[idx].transition_out = 0;
3239 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3240 data.clips.insert(idx + 1, tail);
3241 }
3242 true
3243 }
3244
3245 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3246 /// at `timeline_frame` in every lane and put the result back in one group.
3247 /// Only what a split could have produced is rejoined -- the two sides must
3248 /// touch on the timeline *and* be consecutive frames of the same source --
3249 /// so the clip list comes back exactly as it was and traversal with it.
3250 /// `false` when no lane has such a pair. The rejoined placement keeps the
3251 /// **left** half's id, which is the take the split left on it: rejoining a
3252 /// cut take puts the take back, id and all.
3253 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3254 // What each lane would end up covering, if it joins here at all.
3255 let joined: Vec<Option<(u32, u32)>> = self
3256 .lanes
3257 .iter()
3258 .map(|l| {
3259 joinable(&l.clips, timeline_frame)
3260 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3261 })
3262 .collect();
3263 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3264 let join_subs: Vec<Option<usize>> = self
3265 .lanes
3266 .iter()
3267 .map(|l| sub_joinable(&l.subs, timeline_frame))
3268 .collect();
3269 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3270 return false;
3271 }
3272 self.snapshot();
3273 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3274 if let Some(idx) = sub {
3275 data.subs[idx].frames += data.subs[idx + 1].frames;
3276 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3277 data.subs.remove(idx + 1);
3278 debug_assert!(subs_sorted_disjoint(&data.subs));
3279 }
3280 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3281 continue;
3282 };
3283 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3284 data.clips.remove(idx + 1);
3285 }
3286 true
3287 }
3288
3289 /// Take the placement at `idx` of `lane` out of its group: every clip and
3290 /// every caption carrying its id -- on however many lanes -- is handed an
3291 /// id of its own, so from here on each half moves, trims and is deleted
3292 /// alone. The music video whose sound is to be cut against its picture
3293 /// starts here, and so does the caption that has to come off the picture it
3294 /// was pinned to.
3295 ///
3296 /// An id of its own rather than none at all: a half no other lane is grouped
3297 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3298 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3299 /// as detached. `None` would instead say "was never part of a take", which
3300 /// is what a one-lane [`place`](Project::place) means.
3301 ///
3302 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3303 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3304 /// the group back. Refused (`false`, nothing changed) for an index that is
3305 /// not there, a placement in no group at all, and one whose group has no
3306 /// other half -- that one is already detached, and a refusal must not cost
3307 /// an undo step.
3308 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3309 let Some(members) = self.group_of(lane, idx) else {
3310 return false;
3311 };
3312 if members.alone() {
3313 return false;
3314 }
3315 let Some(id) = self
3316 .lane(lane)
3317 .get(idx)
3318 .and_then(|c| c.link)
3319 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3320 else {
3321 return false;
3322 };
3323 self.snapshot();
3324 // Drawn before the walk: `new_link` takes the whole project, and the
3325 // walk holds the lanes.
3326 let count = members.clips.len() + members.subs.len();
3327 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3328 for data in &mut self.lanes {
3329 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3330 c.link = fresh.pop();
3331 }
3332 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3333 s.link = fresh.pop();
3334 }
3335 }
3336 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3337 true
3338 }
3339
3340 /// Put two clips on two lanes into one group, so what moves one moves the
3341 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3342 /// how a picture is regrouped with sound it was never opened with. Whatever
3343 /// either of them was grouped with comes along: those clips cover this same
3344 /// span already, so the result is one group and not two overlapping ones.
3345 ///
3346 /// Same frames or nothing: a group id names **one span** on however many
3347 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3348 /// clips that do not cover the same frames cannot be one take, and the
3349 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3350 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3351 /// mean, not the rule.
3352 ///
3353 /// Metadata only, one snapshot. The error says what is wrong, because
3354 /// `false` would not: a bad index, one lane twice (a group is at most one
3355 /// clip per lane), spans that disagree, and a pair that is already one take
3356 /// -- nothing changes, and none of them costs an undo step.
3357 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3358 if a == b {
3359 return Err(format!(
3360 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3361 a.label()
3362 )
3363 .into());
3364 }
3365 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3366 p.lane(lane)
3367 .get(idx)
3368 .copied()
3369 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3370 };
3371 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3372 if (x.start, x.end()) != (y.start, y.end()) {
3373 return Err(format!(
3374 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3375 a.label(),
3376 x.start,
3377 x.end(),
3378 b.label(),
3379 y.start,
3380 y.end()
3381 )
3382 .into());
3383 }
3384 if x.link.is_some() && x.link == y.link {
3385 return Err("those two are one take already".into());
3386 }
3387 self.snapshot();
3388 let id = self.new_link();
3389 // Every clip either of them was grouped with, by the same rule: all of
3390 // them cover this span, so one id over the lot stays consistent.
3391 let old = [x.link, y.link];
3392 for data in &mut self.lanes {
3393 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3394 if old.contains(&c.link) {
3395 c.link = Some(id);
3396 }
3397 }
3398 }
3399 // And the two themselves, which a `place` may have left in no group.
3400 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3401 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3402 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3403 Ok(())
3404 }
3405
3406 /// Put every placement the picks name into one group -- the group a hand
3407 /// builds with ctrl-click and a menu: the picture, its sound and the
3408 /// caption over it, on as many lanes as the picks name. What any of them
3409 /// was already grouped with rides along (one group, not two sharing a
3410 /// member), and the members keep their own spans: a group is one id over
3411 /// one placement per lane, and the offsets between them are what the group
3412 /// preserves -- a drag, a trim and a delete all move the members *by the
3413 /// same distance*, not to the same frames.
3414 ///
3415 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3416 /// and the refusal says which lane -- and a pick that names nothing is
3417 /// refused with its own words. At least two picks, or there is nothing to
3418 /// group.
3419 ///
3420 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3421 /// apart again. None of the refusals changes anything or costs an undo
3422 /// step.
3423 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3424 if picks.len() < 2 {
3425 return Err("a group is two placements or more: pick another one first".into());
3426 }
3427 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3428 for &(lane, idx) in picks {
3429 if seen.contains(&lane) {
3430 return Err(format!(
3431 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3432 track",
3433 lane.label()
3434 )
3435 .into());
3436 }
3437 seen.push(lane);
3438 let there = if lane.kind == LaneKind::Subtitle {
3439 idx < self.sub_lane(lane).len()
3440 } else {
3441 idx < self.lane(lane).len()
3442 };
3443 if !there {
3444 let what = if lane.kind == LaneKind::Subtitle {
3445 "subtitle"
3446 } else {
3447 "clip"
3448 };
3449 return Err(
3450 format!("there is no {what} {idx} on {}", lane.label()).into()
3451 );
3452 }
3453 }
3454 let links: Vec<Option<u32>> = picks
3455 .iter()
3456 .map(|&(lane, idx)| {
3457 if lane.kind == LaneKind::Subtitle {
3458 self.sub_lane(lane)[idx].link
3459 } else {
3460 self.lane(lane)[idx].link
3461 }
3462 })
3463 .collect();
3464 // The picks are already one per lane (`seen`, above), but a pick's
3465 // *existing* group can carry a second member onto a lane another
3466 // pick (or another existing group in the merge) already occupies --
3467 // two captions on one sub lane, say, each grouped with a different
3468 // clip before this call. Merging both in would leave that lane with
3469 // two members of one id, which `links_are_consistent` may never see:
3470 // refused by name, before anything moves, rather than a group closed
3471 // broken.
3472 let labels = handles(&self.lanes);
3473 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3474 for (li, data) in self.lanes.iter().enumerate() {
3475 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3476 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3477 if n > 0 {
3478 per_lane.insert(li, n as u32);
3479 }
3480 }
3481 // A pick that carries no link of its own is invisible to the scan
3482 // above (there is no `Some` to match): it still claims its lane.
3483 for &(lane, _) in picks {
3484 let li = self.index(lane).expect("checked above");
3485 per_lane.entry(li).or_insert(0);
3486 if !self.lanes[li]
3487 .clips
3488 .iter()
3489 .any(|c| c.link.is_some() && links.contains(&c.link))
3490 && !self.lanes[li]
3491 .subs
3492 .iter()
3493 .any(|s| s.link.is_some() && links.contains(&s.link))
3494 {
3495 *per_lane.get_mut(&li).expect("just inserted") += 1;
3496 }
3497 }
3498 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3499 return Err(format!(
3500 "a group is one placement per lane: merging these groups would put two on {}",
3501 labels[li].label()
3502 )
3503 .into());
3504 }
3505 self.snapshot();
3506 let id = self.new_link();
3507 // Whatever any pick was grouped with comes along, for [`group`]'s
3508 // reason -- one id over the lot, not two groups sharing a member.
3509 for data in &mut self.lanes {
3510 for c in data.clips.iter_mut() {
3511 if c.link.is_some() && links.contains(&c.link) {
3512 c.link = Some(id);
3513 }
3514 }
3515 for s in data.subs.iter_mut() {
3516 if s.link.is_some() && links.contains(&s.link) {
3517 s.link = Some(id);
3518 }
3519 }
3520 }
3521 // And the picks themselves, which a `place` may have left in no group.
3522 // The lane seats are read before the walk, which holds the lanes.
3523 let seats: Vec<(usize, bool)> = picks
3524 .iter()
3525 .map(|&(lane, _)| {
3526 (
3527 self.index(lane).expect("checked above"),
3528 lane.kind == LaneKind::Subtitle,
3529 )
3530 })
3531 .collect();
3532 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3533 let _ = lane;
3534 if sub {
3535 self.lanes[at].subs[idx].link = Some(id);
3536 } else {
3537 self.lanes[at].clips[idx].link = Some(id);
3538 }
3539 }
3540 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3541 Ok(())
3542 }
3543
3544 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3545 /// lands on and leaving every other clip exactly where it is -- the
3546 /// per-lane paste. Anything already there is trimmed away (and split in two
3547 /// if `clip` lands inside it), which is what keeps the lane sorted and
3548 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3549 /// gap. Refused only for an empty `clip`.
3550 ///
3551 /// The placement belongs to no group: a clipboard clip carries the link id
3552 /// of the take it was copied from, and placing it twice -- or placing a copy
3553 /// back over the clip it came from -- would put that id on two clips of one
3554 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3555 /// `None` rather than a fresh id because a one-lane placement has nothing on
3556 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3557 /// become a group again.
3558 ///
3559 /// Refused for an empty `clip`, for a lane that is not there, and for a
3560 /// subtitle lane, which carries no picture and no sound
3561 /// ([`Project::place_sub`] is its door).
3562 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3563 if clip.out_frame <= clip.in_frame
3564 || lane.kind == LaneKind::Subtitle
3565 || self.index(lane).is_none()
3566 {
3567 return false;
3568 }
3569 self.snapshot();
3570 let clip = Clip {
3571 fade_in: 0,
3572 fade_out: 0,
3573 transition_out: 0,
3574 start: timeline_frame,
3575 link: None,
3576 ..clip
3577 };
3578 self.insert_over(lane, clip);
3579 true
3580 }
3581
3582 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3583 /// one grouped take -- what a picture let go over a further video track
3584 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3585 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3586 /// this half a file with sound landed on a layer silent, and the only way to
3587 /// hear it was to drop it a second time on an audio lane.
3588 ///
3589 /// Both halves overwrite what they land on and neither ripples, exactly as
3590 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3591 /// nothing under it moves. One history snapshot for the pair, the added lane
3592 /// included, so one [`Project::undo`] takes the whole placement back. The two
3593 /// carry one link, which is what makes them one take to a drag, a trim and a
3594 /// save.
3595 ///
3596 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3597 /// there or is not a video lane: sound placed alone is
3598 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3599 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3600 if clip.out_frame <= clip.in_frame
3601 || lane.kind != LaneKind::Video
3602 || self.index(lane).is_none()
3603 {
3604 return false;
3605 }
3606 self.snapshot();
3607 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3608 // an ord names a lane only while every ord below it does.
3609 while self.lane_count(LaneKind::Audio) <= lane.ord {
3610 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3611 }
3612 let clip = Clip {
3613 fade_in: 0,
3614 fade_out: 0,
3615 transition_out: 0,
3616 start: timeline_frame,
3617 link: Some(self.new_link()),
3618 ..clip
3619 };
3620 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3621 self.insert_over(half, clip);
3622 }
3623 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3624 true
3625 }
3626
3627 /// `clip` into `lane` at its own start, over whatever it lands on: the
3628 /// insert both placement doors make, which is what keeps a lane sorted and
3629 /// disjoint. The caller has checked that the lane is there.
3630 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3631 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3632 clear(clips, clip.start, clip.end());
3633 let idx = clips.partition_point(|c| c.start < clip.start);
3634 clips.insert(idx, clip);
3635 debug_assert!(sorted_disjoint(clips));
3636 }
3637
3638 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3639 /// frame `start`: the drag that rearranges takes, along a track and across
3640 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3641 /// was. `start` at the clip's own is the pure lane change.
3642 ///
3643 /// The whole group travels the same distance, each half on the lane it
3644 /// already sits on -- a link means "these cover one span on however many
3645 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3646 /// sound would be a group no save could load. Only the dragged half changes
3647 /// lane, and that is not a desync: a link names no lane at all.
3648 ///
3649 /// `start` is **clamped**, never refused, to the room the group has: no
3650 /// member crosses a neighbour on the lane it lands on, exactly as
3651 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3652 /// dragging past a neighbour means "as far as it goes", and butting up
3653 /// against the take next door is how clips are laid end to end. The
3654 /// tightest member's wall wins, so a sound half boxed in between two others
3655 /// holds its picture still.
3656 ///
3657 /// Refused, changing nothing and costing no undo step, for a lane that is
3658 /// not there, an index that is not there, a move across *kinds* (a picture
3659 /// cannot play on an audio lane, and the save it wrote would not open
3660 /// again), a head let go *inside* another clip or into a gap too narrow to
3661 /// hold this one -- a move that overwrote what it landed on would destroy a
3662 /// take the pointer never named, which is what [`place`](Project::place)
3663 /// may do and a drag may not -- a half let go onto the lane its own partner
3664 /// is on, and a drop that changes neither lane nor frame, which is a clip
3665 /// picked up and put back down, i.e. a click.
3666 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3667 self.move_selection(&[(from, idx)], from, idx, to, start)
3668 }
3669
3670 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
3671 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
3672 /// reads it) travels the same distance as the clip at `idx` of `from`,
3673 /// which alone changes lane, onto `to`. One clamp across the whole set
3674 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
3675 /// neighbour that boxes in *any* member narrows the delta every member
3676 /// moves by, and a member with no room at all (`lo > hi`) refuses the
3677 /// whole set rather than moving the rest and leaving that one behind.
3678 /// `move_clip` is this with a selection of one -- the dragged clip's own
3679 /// group and nothing else -- so a drag on a clip outside the selection is
3680 /// byte-identical to before this existed.
3681 pub fn move_selection(
3682 &mut self,
3683 picks: &[(Lane, usize)],
3684 from: Lane,
3685 idx: usize,
3686 to: Lane,
3687 start: u32,
3688 ) -> bool {
3689 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3690 return false;
3691 };
3692 if from.kind != to.kind {
3693 return false;
3694 }
3695 let held = self.index(from).expect("the clip was found on it");
3696 // Every pick's own group, unioned: the whole selection moves as one,
3697 // and a pick's link partners (not themselves picked) come along with
3698 // it exactly as a lone drag's do.
3699 let mut members = Members::default();
3700 for &(lane, i) in picks {
3701 let Some(group) = self.group_of(lane, i) else {
3702 continue;
3703 };
3704 for m in group.clips {
3705 if !members.clips.contains(&m) {
3706 members.clips.push(m);
3707 }
3708 }
3709 for m in group.subs {
3710 if !members.subs.contains(&m) {
3711 members.subs.push(m);
3712 }
3713 }
3714 }
3715 if !members.clips.contains(&(held, idx)) {
3716 members.clips.push((held, idx));
3717 }
3718 // The two halves of *the dragged clip's own* group would land on one
3719 // span of one lane, which is the one thing a link may never mean --
3720 // checked against that group alone, not the whole moving set: an
3721 // unlinked fellow pick already sitting on `dest` is no conflict at
3722 // all, since it travels by the same delta and `move_room` below
3723 // leaves it the room to. Refused rather than clamped: the partner
3724 // moves the same distance, so there is no room for it anywhere on
3725 // that lane.
3726 let own_group = self.group_of(from, idx).expect("the clip was found");
3727 if dest != held
3728 && own_group
3729 .clips
3730 .iter()
3731 .chain(&own_group.subs)
3732 .any(|&(l, _)| l == dest)
3733 {
3734 return false;
3735 }
3736 let want = i64::from(start) - i64::from(clip.start);
3737 // How far the group may travel, in timeline frames and signed: every
3738 // member -- the clips and any caption grouped with them -- narrows it
3739 // to the gap it is landing in, and what is left is what the pointer is
3740 // clamped to.
3741 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3742 return false;
3743 };
3744 if lo > hi {
3745 return false;
3746 }
3747 let delta = want.clamp(lo, hi);
3748 if delta == 0 && dest == held {
3749 return false;
3750 }
3751 self.snapshot();
3752 for &(l, i) in &members.clips {
3753 let c = &mut self.lanes[l].clips[i];
3754 // In range by the walls above, which are `u32` frames throughout.
3755 c.start = (i64::from(c.start) + delta) as u32;
3756 }
3757 for &(l, i) in &members.subs {
3758 let s = &mut self.lanes[l].subs[i];
3759 s.start = (i64::from(s.start) + delta) as u32;
3760 }
3761 if dest != held {
3762 let clip = self.lanes[held].clips.remove(idx);
3763 let clips = &mut self.lanes[dest].clips;
3764 let at = clips.partition_point(|c| c.start < clip.start);
3765 clips.insert(at, clip);
3766 }
3767 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3768 debug_assert!(members
3769 .clips
3770 .iter()
3771 .chain(&members.subs)
3772 .all(|&(l, _)| {
3773 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3774 }));
3775 true
3776 }
3777
3778 /// How far a group drag may travel, `(least, most)` in timeline frames and
3779 /// signed: every member narrows the range to the gap it is landing in --
3780 /// the clips against their lanes' clips and the captions against their
3781 /// lanes' captions -- and what is left is what the pointer is clamped to.
3782 /// `travelling` names the one member that changes lane, if any: the clip a
3783 /// hand is carrying onto another track, whose walls are read on the lane it
3784 /// is let go over at the frame the pointer named. `None` when a member has
3785 /// no gap to land in at all.
3786 fn move_room(
3787 &self,
3788 members: &Members,
3789 travelling: Option<(usize, usize, usize, u32)>,
3790 ) -> Option<(i64, i64)> {
3791 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3792 for &(l, i) in members.clips.iter().chain(&members.subs) {
3793 let sub = members.subs.contains(&(l, i));
3794 let (start, frames) = match self.lanes[l]
3795 .clips
3796 .get(i)
3797 .filter(|_| !sub)
3798 .map(|c| (c.start, c.frames()))
3799 {
3800 Some(pair) => pair,
3801 None => {
3802 let s = self.lanes[l].subs.get(i)?;
3803 (s.start, s.frames)
3804 }
3805 };
3806 let land = travelling
3807 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3808 .map_or(l, |(_, _, dest, _)| dest);
3809 // Which gap this member's walls are read off: its own place on the
3810 // lane it stays on, and the frame the pointer named on the lane it
3811 // is let go over. A clip's neighbours are the clips of the lane it
3812 // lands on and a caption's are its captions -- the two lists of one
3813 // lane never meet.
3814 let at = match travelling {
3815 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3816 _ => start,
3817 };
3818 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3819 let neighbours: Vec<(u32, u32)> = if sub {
3820 self.lanes[land]
3821 .subs
3822 .iter()
3823 .map(|s| (s.start, s.end()))
3824 .collect()
3825 } else {
3826 self.lanes[land]
3827 .clips
3828 .iter()
3829 .map(|c| (c.start, c.end()))
3830 .collect()
3831 };
3832 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3833 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3834 continue;
3835 }
3836 if *other_start <= at && at < *other_end {
3837 // A head let go inside another placement, which a clamp
3838 // has no answer for: the drop is refused.
3839 return None;
3840 }
3841 match other_end <= &at {
3842 true => wall_lo = wall_lo.max(*other_end),
3843 false => wall_hi = wall_hi.min(*other_start),
3844 }
3845 }
3846 if wall_hi - wall_lo < frames {
3847 return None;
3848 }
3849 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3850 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3851 }
3852 Some((lo, hi))
3853 }
3854
3855 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3856 /// the drag on a clip's end that makes it play more or less of its source.
3857 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3858 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3859 /// is room that was already empty. One snapshot, so a whole drag is one
3860 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3861 /// sample. Changes the timeline->source mapping: the caller must reseek.
3862 ///
3863 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3864 /// exactly what they played before, which is what makes this a trim and not
3865 /// a slip.
3866 ///
3867 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3868 /// legal means "as far as it goes", and stopping the box there is the
3869 /// affordance. The walls are: one frame of clip always survives, an edge
3870 /// never crosses the neighbouring clip on its own lane, an in-point never
3871 /// walks back past the source's first frame, and an out-point never runs
3872 /// past `source_frames[clip.source]` -- the caller's table of how long each
3873 /// source actually is ([`Project`] does not know, and a clip ending past its
3874 /// file's last frame is a save that will not open again; see
3875 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3876 /// there may not grow at all.
3877 ///
3878 /// Linked placements trim *together*, by one delta: every member's same
3879 /// edge moves the distance the dragged one did, clamped to the room its
3880 /// own walls leave -- offsets between the members of a hand-built group
3881 /// survive the trim, exactly as they survive a drag.
3882 ///
3883 /// `false`, changing nothing and costing no undo step, for an index that is
3884 /// not there and for an edge that is already where it was asked to go.
3885 pub fn trim(
3886 &mut self,
3887 lane: Lane,
3888 idx: usize,
3889 edge: Edge,
3890 to: u32,
3891 source_frames: &[u32],
3892 ) -> bool {
3893 let (Some((lo, hi)), Some(clip)) = (
3894 self.trim_room(lane, idx, edge, source_frames),
3895 self.lane(lane).get(idx).copied(),
3896 ) else {
3897 return false;
3898 };
3899 let to = to.clamp(lo, hi);
3900 let at = match edge {
3901 Edge::Start => clip.start,
3902 Edge::End => clip.end(),
3903 };
3904 if to == at {
3905 return false;
3906 }
3907 // Worked out before anything moves: at a slow rate a room can be too
3908 // narrow to hold even one source frame ([`Speed::fit`]), and the
3909 // dragged clip refusing to fit must refuse the whole gesture rather
3910 // than be given a range wider than its room -- which is the overlap
3911 // the lane invariant exists to forbid. The walls below leave that room,
3912 // so this is the backstop for a project that came in through another
3913 // door.
3914 let room = match edge {
3915 // The frames that stay play what they played, so what survives is
3916 // measured from the *end*.
3917 Edge::Start => clip.end() - to,
3918 Edge::End => to - clip.start,
3919 };
3920 let Some(keep) = clip.speed.fit(room) else {
3921 return false;
3922 };
3923 let members = self.group_of(lane, idx).expect("checked above");
3924 self.snapshot();
3925 let still = self.is_still(&clip);
3926 let held = self.index(lane).expect("checked above");
3927 let c = &mut self.lanes[held].clips[idx];
3928 match edge {
3929 // A still has no earlier frame to walk an in-point back to --
3930 // every frame of it is the same picture -- so its head grows
3931 // *forward*: the range it plays is however long the new room is,
3932 // anchored at the source's frame 0. Bounded by `lo`, which is where
3933 // the cap in `source_frames` is applied.
3934 Edge::Start if still => {
3935 c.in_frame = 0;
3936 c.out_frame = keep;
3937 c.start = to;
3938 }
3939 Edge::Start => {
3940 // Non-negative by `lo`, which is what keeps the in-point on the
3941 // source.
3942 c.in_frame = c.out_frame - keep.min(c.out_frame);
3943 c.start = to;
3944 }
3945 // Never wider than the room the edge was clamped to: see
3946 // [`Speed::fit`].
3947 Edge::End => c.out_frame = c.in_frame + keep,
3948 }
3949 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3950 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3951 true
3952 }
3953
3954 /// The rest of a group after one member's `edge` has moved by `delta`:
3955 /// every other member's same edge moves the same distance, clamped to the
3956 /// room its own walls leave -- a clip's against its lane and its source,
3957 /// a caption's against its own lane, its window following by the
3958 /// placement's own proportion. The undo step is the caller's: this is the
3959 // second half of one edit, not an edit of its own.
3960 fn follow_group(
3961 &mut self,
3962 members: &Members,
3963 dragged: &(usize, usize),
3964 edge: Edge,
3965 delta: i64,
3966 source_frames: &[u32],
3967 ) {
3968 for &(l, i) in &members.clips {
3969 if (l, i) == *dragged {
3970 continue;
3971 }
3972 let c = self.lanes[l].clips[i];
3973 let at = match edge {
3974 Edge::Start => c.start,
3975 Edge::End => c.end(),
3976 };
3977 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3978 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3979 if to == at {
3980 continue;
3981 }
3982 let room = match edge {
3983 Edge::Start => c.end() - to,
3984 Edge::End => to - c.start,
3985 };
3986 let Some(keep) = c.speed.fit(room) else {
3987 continue;
3988 };
3989 let still = self.is_still(&self.lanes[l].clips[i]);
3990 let c = &mut self.lanes[l].clips[i];
3991 match edge {
3992 Edge::Start if still => {
3993 c.in_frame = 0;
3994 c.out_frame = keep;
3995 c.start = to;
3996 }
3997 Edge::Start => {
3998 c.in_frame = c.out_frame - keep.min(c.out_frame);
3999 c.start = to;
4000 }
4001 Edge::End => c.out_frame = c.in_frame + keep,
4002 }
4003 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4004 }
4005 for &(l, i) in &members.subs {
4006 if (l, i) == *dragged {
4007 continue;
4008 }
4009 let s = self.lanes[l].subs[i];
4010 let at = match edge {
4011 Edge::Start => s.start,
4012 Edge::End => s.end(),
4013 };
4014 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
4015 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
4016 if to == at {
4017 continue;
4018 }
4019 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
4020 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4021 }
4022 }
4023
4024 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
4025 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
4026 /// What a front-end drawing the box *during* a drag asks, so the live width
4027 /// is the width the release will commit and an edge stops under the pointer
4028 /// rather than snapping back. The **clip's own** walls: the rest of its
4029 /// group follows by the same delta within their own ([`follow_group`]), so
4030 /// what is drawn for the dragged edge is what its own clip will commit.
4031 /// `None` for an index that is not there.
4032 pub fn trim_room(
4033 &self,
4034 lane: Lane,
4035 idx: usize,
4036 edge: Edge,
4037 source_frames: &[u32],
4038 ) -> Option<(u32, u32)> {
4039 let l = self.index(lane)?;
4040 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
4041 }
4042
4043 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
4044 /// its lane's storage index: the one wall computation, asked for the clip
4045 /// itself and for each member a group trim carries.
4046 fn clip_room(
4047 &self,
4048 l: usize,
4049 i: usize,
4050 edge: Edge,
4051 source_frames: &[u32],
4052 ) -> (u32, u32) {
4053 let clips = &self.lanes[l].clips;
4054 let c = clips[i];
4055 let (lo, hi) = match edge {
4056 Edge::Start => (
4057 // Back to the source's own first frame -- as many *timeline*
4058 // frames as that head is worth at the clip's rate, which at
4059 // real time is the head itself -- and never over the clip in
4060 // front of it. Saturating because a clip may hold *more*
4061 // head than the timeline has room for -- a ripple delete
4062 // slides a clip back to frame 0 with its in-point wherever
4063 // the cut left it -- and frame 0 is the other wall.
4064 //
4065 // A still is measured from its *tail* instead: it has no
4066 // in-point worth the name (every frame the same picture), so
4067 // its head reaches exactly as far as its tail does -- out to
4068 // the length the caller's table gives it, whole. Measured
4069 // from the in-point it would have no head room at all, which
4070 // is a placed picture whose left edge cannot be dragged out.
4071 // No entry in the table means no growth, as it does at the
4072 // other end.
4073 if self.is_still(&c) {
4074 c.end().saturating_sub(
4075 c.speed
4076 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
4077 )
4078 } else {
4079 c.start.saturating_sub(c.speed.room(c.in_frame))
4080 }
4081 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
4082 // One *frame of clip* always survives, and at a rate below
4083 // real time one frame of clip is several frames of timeline
4084 // ([`Speed::room`]): an edge dragged closer than that would
4085 // ask for a range no source frame fits in. At real time this
4086 // is `end - 1`, unchanged.
4087 c.end() - c.speed.room(1),
4088 ),
4089 Edge::End => (
4090 // ...and the same wall from the other end: the shortest this
4091 // clip can be is the room one source frame of it takes.
4092 c.start + c.speed.room(1),
4093 // Out to whatever is left of the source -- again in timeline
4094 // frames, at this clip's rate -- and never over the clip
4095 // behind it.
4096 c.start
4097 .saturating_add(
4098 c.speed.room(
4099 source_frames
4100 .get(c.source)
4101 .copied()
4102 .unwrap_or(c.out_frame)
4103 .saturating_sub(c.in_frame),
4104 ),
4105 )
4106 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
4107 ),
4108 };
4109 // `hi.max(lo)`: for a clip the invariants hold for, the range always
4110 // contains the edge's own place, and a caller's wrong `source_frames`
4111 // must not become an empty range (or a panicking `clamp`) here.
4112 (lo, hi.max(lo))
4113 }
4114
4115 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
4116 /// every frame is the same picture, so which frame of it a clip's in-point
4117 /// names is not a question -- what [`Project::trim`] lets grow at either
4118 /// end. `false` for a source that is not there.
4119 fn is_still(&self, clip: &Clip) -> bool {
4120 self.sources
4121 .get(clip.source)
4122 .is_some_and(|s| crate::is_image(&s.path))
4123 }
4124
4125 /// The placements that move as one with the one at `idx` of `lane` --
4126 /// itself and whatever carries its link, on the media lanes and the
4127 /// subtitle ones alike. `None` for an index that is not there.
4128 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
4129 let sub = lane.kind == LaneKind::Subtitle;
4130 let link = if sub {
4131 self.sub_lane(lane).get(idx)?.link
4132 } else {
4133 self.lane(lane).get(idx)?.link
4134 };
4135 let mut members = Members::default();
4136 match link {
4137 Some(link) => {
4138 for (l, data) in self.lanes.iter().enumerate() {
4139 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
4140 members.clips.push((l, i));
4141 }
4142 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
4143 members.subs.push((l, i));
4144 }
4145 }
4146 }
4147 None => {
4148 let l = self.index(lane).expect("the placement was found on it");
4149 if sub {
4150 members.subs.push((l, idx));
4151 } else {
4152 members.clips.push((l, idx));
4153 }
4154 }
4155 }
4156 Some(members)
4157 }
4158
4159 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4160 /// new group, pushing everything from there on later by its length in
4161 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4162 /// the clip it lands in is split around it; past the end of the timeline it
4163 /// goes down where it was asked for, with black in front of it -- which is
4164 /// what a library row let go on the open bed means, and what the ghost under
4165 /// the pointer promised. A clipboard means "put it here", not "here and
4166 /// black in front", and clamps to the end at its own door
4167 /// ([`crate::PlaybackSession::paste_at`]).
4168 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4169 ///
4170 /// `V1` and `A1` and no other lane, because a take is one picture and one
4171 /// sound: copying it onto every lane there is would play the same audio
4172 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4173 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4174 /// video lane it is a clip that decodes to nothing, and a save carrying one
4175 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4176 /// `V1` only, for the mirror of that reason. The room is still opened on
4177 /// every media lane, or the lanes it was not inserted into would slide out
4178 /// of step with the ones it was -- and the subtitle lanes are left alone:
4179 /// the words keep their own clock, and a caption that should travel with a
4180 /// clip is what a group is for.
4181 ///
4182 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4183 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4184 /// an empty `clip` and for one naming a source that is not there (both of
4185 /// which the public fields let a caller build), and for a paste whose ripple
4186 /// would push a clip past the last frame there is -- nothing is changed by
4187 /// any of them.
4188 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4189 let Some(source) = self.sources.get(clip.source) else {
4190 return false;
4191 };
4192 if clip.out_frame <= clip.in_frame {
4193 return false;
4194 }
4195 let audio_only = crate::is_audio(&source.path);
4196 // ...and its mirror: a still is a picture and no sound, so a copy of one
4197 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4198 // worker tries to demux -- which silences the *whole session*, not just
4199 // that clip -- and a save the engine's own `open_project` then refuses.
4200 let picture_only = crate::is_image(&source.path);
4201 // The frame it was asked for and no other: a row let go on the empty
4202 // bed past the last clip lands *there*, under the ghost that promised
4203 // it, with black in front. Clamping to the end here made every drop on
4204 // open bed an append -- the clipboard's rule, applied to a hand that
4205 // had named a place.
4206 let at = timeline_frame;
4207 // The room it takes on the timeline, which its speed decides -- not the
4208 // source range it reads.
4209 let len = clip.frames();
4210 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4211 // hand-written file may hold a clip that ends at the very last frame
4212 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4213 // rather than wrapped there -- a wrapped start lands *behind* the clip
4214 // it belongs after, which is an overlap no save will read back.
4215 if at.checked_add(len).is_none()
4216 || self
4217 .lanes
4218 .iter()
4219 .flat_map(|l| &l.clips)
4220 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4221 {
4222 return false;
4223 }
4224 // ...and room *to open*: the paste splits whatever it lands inside of,
4225 // and a speeded clip can only be cut where its own rate has a source
4226 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4227 // of one, which is the overlap a lane may never hold. At real time every
4228 // frame answers, so this cannot refuse an unspeeded paste.
4229 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4230 if self
4231 .lanes
4232 .iter()
4233 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4234 {
4235 return false;
4236 }
4237 self.snapshot();
4238 let clip = Clip {
4239 fade_in: 0,
4240 fade_out: 0,
4241 transition_out: 0,
4242 start: at,
4243 link: Some(self.new_link()),
4244 ..clip
4245 };
4246 // Only lanes that can play the source: a file with no picture belongs on
4247 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4248 // it for an import. On a video lane it would decode to nothing, and the
4249 // save it wrote would not open again.
4250 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4251 (true, _) => &[LaneKind::Audio],
4252 (_, true) => &[LaneKind::Video],
4253 _ => &[LaneKind::Video, LaneKind::Audio],
4254 };
4255 let takes: Vec<usize> = kinds
4256 .iter()
4257 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4258 .collect();
4259 for (i, data) in self.lanes.iter_mut().enumerate() {
4260 open_room(&mut data.clips, at, len);
4261 // The subtitle lanes are NOT touched: a paste inserts media, and
4262 // the words keep their own clock. Opening room here used to split
4263 // a caption the paste landed inside and slide the rest behind it
4264 // -- "a caption that stayed put while the picture moved on no
4265 // longer says the same thing" -- but a caption pinned to nothing
4266 // (and a video arriving on a timeline of words alone) has no
4267 // picture to follow, and the split did to the words what no hand
4268 // asked for. A caption that should travel with a clip is what a
4269 // group is for, and a group moves as one.
4270 if takes.contains(&i) {
4271 let idx = data.clips.partition_point(|c| c.start < at);
4272 data.clips.insert(idx, clip);
4273 }
4274 debug_assert!(sorted_disjoint(&data.clips));
4275 debug_assert!(subs_sorted_disjoint(&data.subs));
4276 }
4277 true
4278 }
4279
4280 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
4281 /// `items` lands on the lane it names, its head moved by the offset every
4282 /// other item moves by too -- `at` less the earliest `start` among them,
4283 /// so the set's own gaps and lane assignment survive the trip from
4284 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
4285 /// way a lone clip's copy does.
4286 ///
4287 /// All-or-nothing, and **refused** rather than opening room or splitting
4288 /// a neighbour the way [`paste`](Project::paste) does for one clip:
4289 /// a set-paste never ripples the bed, so a landing that overlaps so much
4290 /// as one existing clip on its own lane refuses the whole set, changing
4291 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
4292 /// clamps instead of refusing, but a paste has no drag to clamp against,
4293 /// and a landing moved off the frame asked for is not what a paste means.
4294 /// `items` empty, naming a lane or a source that is not there, or a clip
4295 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
4296 ///
4297 /// Exactly one history snapshot for the whole set, so one
4298 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
4299 /// on every lane an item lands on: the caller must reseek.
4300 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
4301 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
4302 return false;
4303 };
4304 // Resolved once, up front, off the lanes as they stand now: a lane or
4305 // source that is not there, or a landing that would overlap a
4306 // neighbour, refuses the whole set before any of it is written.
4307 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
4308 for &(lane, clip) in items {
4309 let Some(li) = self.index(lane) else {
4310 return false;
4311 };
4312 if self.sources.get(clip.source).is_none() || clip.out_frame <= clip.in_frame {
4313 return false;
4314 }
4315 let delta = i64::from(clip.start) - i64::from(anchor);
4316 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
4317 return false;
4318 };
4319 let Some(end) = start.checked_add(clip.frames()) else {
4320 return false;
4321 };
4322 if self.lanes[li]
4323 .clips
4324 .iter()
4325 .any(|c| c.start < end && start < c.end())
4326 {
4327 return false;
4328 }
4329 landings.push((li, Clip { start, ..clip }));
4330 }
4331 self.snapshot();
4332 for (li, mut clip) in landings {
4333 clip.link = Some(self.new_link());
4334 clip.fade_in = 0;
4335 clip.fade_out = 0;
4336 clip.transition_out = 0;
4337 let clips = &mut self.lanes[li].clips;
4338 let idx = clips.partition_point(|c| c.start < clip.start);
4339 clips.insert(idx, clip);
4340 }
4341 true
4342 }
4343
4344 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4345 /// silence, and nothing else moves. Refused only for an out-of-range index
4346 /// (which a lane that is not there always is) -- lifting the last placement
4347 /// there is leaves an *empty* timeline, which is a state the project holds
4348 /// like any other and an undo brings back.
4349 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4350 if idx >= self.lane(lane).len() {
4351 return false;
4352 }
4353 self.snapshot();
4354 self.lane_mut(lane).expect("checked above").remove(idx);
4355 true
4356 }
4357
4358 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4359 /// the hole: everything after slides back by `len`. The rippling delete --
4360 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4361 /// empty range; a delete that leaves nothing behind empties the timeline,
4362 /// which is a state like any other and one undo away.
4363 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4364 if len == 0 {
4365 return false;
4366 }
4367 // Nothing reaches past `at`: there is nothing to cut and nothing to
4368 // slide back, and a delete that changes nothing must not cost an undo
4369 // step (see [`snapshot`](Project::snapshot)).
4370 if !self
4371 .lanes
4372 .iter()
4373 .flat_map(|l| &l.clips)
4374 .any(|c| c.end() > at)
4375 {
4376 return false;
4377 }
4378 self.snapshot();
4379 let on = all_lanes(&self.lanes);
4380 ripple(&mut self.lanes, &on, at, len);
4381 true
4382 }
4383
4384 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
4385 /// a right-click on empty bench space names before offering to close it.
4386 /// `None` when `frame` sits inside a placement, or past the last one: the
4387 /// open end of a lane is not a gap, since there is nothing after it to slide
4388 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
4389 /// the media [`Clip`] list they deliberately never hold.
4390 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
4391 let data = self.index(lane).map(|i| &self.lanes[i])?;
4392 match data.kind {
4393 LaneKind::Subtitle => gap(&data.subs, frame),
4394 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
4395 }
4396 }
4397
4398 /// How many bounded holes `lane` holds. The open end after the last
4399 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
4400 /// it would move nothing.
4401 pub fn gap_count(&self, lane: Lane) -> usize {
4402 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
4403 return 0;
4404 };
4405 match data.kind {
4406 LaneKind::Subtitle => gaps(&data.subs).len(),
4407 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
4408 }
4409 }
4410
4411 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4412 /// together to keep sync -- what a right-click on empty bench space asks
4413 /// before the menu offers to close it, and what widens
4414 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
4415 /// named to the whole take the gap might be half of.
4416 ///
4417 /// A clip bordering the gap on `lane` -- the one ending where it starts,
4418 /// the one starting where it ends -- carries a link when it is one take
4419 /// with a clip on another lane. That lane joins the scope only when the
4420 /// *exact same* stretch is empty there too (same start, same length): the
4421 /// ripple then removes nothing but silence, on every lane it touches, and
4422 /// both halves stay the length they always were. A link whose partner
4423 /// lane is not empty there -- a gap of a different length, or none at all
4424 /// -- is named back to the caller rather than silently widened past
4425 /// (which would cut real media out of a lane nothing asked to touch) or
4426 /// silently left out (which is the defect this closes: a per-lane ripple
4427 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
4428 /// to refuse it after the fact, on the very half this could have carried
4429 /// along).
4430 ///
4431 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
4432 /// partner clip sits on another lane -- the unlinked case, untouched.
4433 ///
4434 /// Subtitle lanes have no media take halves to inspect. A caption can be
4435 /// hand-grouped with clips, but it is not the imported A/V take this method
4436 /// widens for, so a subtitle gap stays scoped to its own lane; the later
4437 /// scoped cut still refuses an explicit group split.
4438 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4439 let Some(li) = self.index(lane) else {
4440 return Err("no track to work on".into());
4441 };
4442 let labels = handles(&self.lanes);
4443 let end = start + frames;
4444 let mut scope = vec![lane];
4445 for c in self.lanes[li]
4446 .clips
4447 .iter()
4448 .filter(|c| c.end() == start || c.start == end)
4449 {
4450 let Some(id) = c.link else { continue };
4451 for (j, data) in self.lanes.iter().enumerate() {
4452 if j == li {
4453 continue;
4454 }
4455 let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else {
4456 continue;
4457 };
4458 match gap(&data.clips, start) {
4459 Some((s, f)) if s == start && f == frames => {
4460 let other = labels[j];
4461 if !scope.contains(&other) {
4462 scope.push(other);
4463 }
4464 }
4465 _ => {
4466 return Err(format!(
4467 "the {} clip at frame {} is one take with the {} clip at frame {}: \
4468 closing this gap alone would pull the take out of sync -- close {}'s \
4469 gap there too, or detach them first",
4470 labels[li].label(),
4471 c.start,
4472 labels[j].label(),
4473 half.start,
4474 labels[j].label()
4475 )
4476 .into());
4477 }
4478 }
4479 }
4480 }
4481 Ok(scope)
4482 }
4483
4484 /// Close every bounded gap on `lane`, as one undo step, without making the
4485 /// lane's scope global. Media lanes use the same take-safety widening
4486 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
4487 /// halves ride along only when their matching lane is empty over that exact
4488 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
4489 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
4490 /// halves of an imported A/V take, so the media take-widening rule has
4491 /// nothing to add there.
4492 ///
4493 /// The walk is back-to-front. Closing a gap shifts everything after it, so
4494 /// later holes must be consumed while their measured starts are still true;
4495 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
4496 /// only before the first successful close, so an all-skipped sweep is not an
4497 /// undo step.
4498 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4499 let Some(i) = self.index(lane) else {
4500 return Err("no track to work on".into());
4501 };
4502 if self.lanes[i].kind == LaneKind::Subtitle {
4503 return Ok(self.close_all_subtitle_gaps_on_lane(i));
4504 }
4505 let mut report = GapSweep::default();
4506 let mut snapshot = false;
4507 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
4508 match self
4509 .gap_take_scope(lane, start, frames)
4510 .and_then(|scope| {
4511 let on = self.scoped(&scope)?;
4512 self.scope_holds_takes_whole(&on, start)?;
4513 Ok(on)
4514 }) {
4515 Ok(on) => {
4516 if !snapshot {
4517 self.snapshot();
4518 snapshot = true;
4519 }
4520 ripple(&mut self.lanes, &on, start, frames);
4521 report.closed += 1;
4522 }
4523 Err(e) => report.skipped.push(GapSkip {
4524 start,
4525 reason: e.to_string(),
4526 }),
4527 }
4528 }
4529 report.skipped.reverse();
4530 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4531 Ok(report)
4532 }
4533
4534 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
4535 /// take-scope widening: a caption is not one half of an A/V take. Explicit
4536 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
4537 /// so a grouped caption is refused rather than pulled away from its group.
4538 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
4539 let mut report = GapSweep::default();
4540 let mut snapshot = false;
4541 let on = [i];
4542 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
4543 match self.scope_holds_takes_whole(&on, start) {
4544 Ok(()) => {
4545 if !snapshot {
4546 self.snapshot();
4547 snapshot = true;
4548 }
4549 ripple(&mut self.lanes, &on, start, frames);
4550 report.closed += 1;
4551 }
4552 Err(e) => report.skipped.push(GapSkip {
4553 start,
4554 reason: e.to_string(),
4555 }),
4556 }
4557 }
4558 report.skipped.reverse();
4559 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4560 report
4561 }
4562
4563 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4564 /// out of the lanes in `scope` and close each hole, as one edit: the
4565 /// jumpcut a silence scan asks for ([`crate::silence`]).
4566 ///
4567 /// A lane that is not in `scope` **does not move**, which is the whole
4568 /// point of the parameter: the silences of a podcast track come out
4569 /// without the music track under it sliding. `scope` is an arbitrary set of
4570 /// lanes and not a kind or a range, so a caller with its own idea of what
4571 /// is selected (a take, a track, everything) says it in lanes and nothing
4572 /// here has to learn about selection.
4573 ///
4574 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4575 /// reason this exists rather than a caller's loop over
4576 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4577 /// undo press, not forty. Cut back to front, so a region's frames still
4578 /// mean what the caller measured while the ones before it are cut.
4579 ///
4580 /// The list is sorted and overlapping entries are merged before anything is
4581 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4582 /// other's frames. Refused, with no undo step, for an empty list, for a
4583 /// scope naming no lane that is there, and -- by name -- when the scope
4584 /// would take one half of a take with it
4585 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4586 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4587 let regions = tidy(regions);
4588 let on = self.scoped(scope)?;
4589 let Some(&(first, _)) = regions.first() else {
4590 return Err("nothing to cut".into());
4591 };
4592 self.scope_holds_takes_whole(&on, first)?;
4593 self.snapshot();
4594 for &(at, len) in regions.iter().rev() {
4595 ripple(&mut self.lanes, &on, at, len);
4596 }
4597 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4598 Ok(())
4599 }
4600
4601 /// The storage indices of `scope`, which is what every batch below walks.
4602 /// `Err` for a scope that names nothing there rather than a silent no-op:
4603 /// an edit asked for on a lane that is not there did not happen, and the
4604 /// caller has to hear so.
4605 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4606 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4607 match on.is_empty() {
4608 true => Err("no track to work on".into()),
4609 false => Ok(on),
4610 }
4611 }
4612
4613 /// The law a scoped ripple lives under: **a group travels as one**, so a
4614 /// batch that moves one half of a take and not the other would leave the
4615 /// halves disagreeing about where they stand -- an offset no hand asked
4616 /// for, and the reason the take's lanes have to be scoped together.
4617 ///
4618 /// Refused by name rather than widened silently. Widening would edit a
4619 /// track the user did not scope, which is exactly the surprise scoping
4620 /// exists to end; a front-end that wants the take is free to *say* the
4621 /// take's lanes, and to name them in what it tells the user afterwards.
4622 ///
4623 /// Only from `from` on: a take sitting entirely before the first cut does
4624 /// not move, so it is not this rule's business.
4625 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4626 let labels = handles(&self.lanes);
4627 // The halves of a group are on either of a lane's lists, and the
4628 // refusal names whichever sits outside the scope -- a clip like it
4629 // always has, and a caption now that a group may hold one.
4630 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4631 let Some(id) = link else {
4632 return Ok(());
4633 };
4634 for (j, data) in self.lanes.iter().enumerate() {
4635 if on.contains(&j) {
4636 continue;
4637 }
4638 let clip = data.clips.iter().find(|o| o.link == Some(id));
4639 let sub = data.subs.iter().find(|s| s.link == Some(id));
4640 if let Some(half) = clip {
4641 return Err(format!(
4642 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4643 moving one track of a take would pull it apart -- take the whole take, \
4644 or detach them first",
4645 labels[j].label(),
4646 half.start
4647 )
4648 .into());
4649 }
4650 if let Some(half) = sub {
4651 return Err(format!(
4652 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4653 moving one track of a take would pull it apart -- take the whole take, \
4654 or detach them first",
4655 labels[j].label(),
4656 half.start
4657 )
4658 .into());
4659 }
4660 }
4661 Ok(())
4662 };
4663 for &i in on {
4664 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4665 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4666 }
4667 // A caption before the first cut does not move, so it is not this
4668 // rule's business -- exactly the clip test's own line.
4669 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4670 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4671 }
4672 }
4673 Ok(())
4674 }
4675
4676 /// Play every one of `regions` at `speed` instead of cutting it: each is
4677 /// split out of whatever covers it, re-rated, and the room it no longer
4678 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4679 /// does not ripple, and a hole where a silence shrank is the one thing this
4680 /// must not leave. One snapshot for the lot, like
4681 /// [`cut_regions`](Project::cut_regions).
4682 ///
4683 /// The rate is **absolute**, not a multiplier on what is there: running it
4684 /// twice over the same stretch leaves it at `speed`, not at `speed`
4685 /// squared, so a second pass over an already-cut timeline changes nothing.
4686 ///
4687 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4688 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4689 ///
4690 /// Refused by name, with nothing changed and no undo step, when:
4691 ///
4692 /// * the scope would take one half of a take with it
4693 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4694 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4695 /// shrink by different amounts and the ripple would pull them apart,
4696 /// which is what cutting does not suffer and why delete mode has no such
4697 /// refusal;
4698 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4699 /// piece could not be split out exactly;
4700 /// * two lanes' pieces would end up different lengths, which is a group
4701 /// whose halves disagree about their span (the refusal
4702 /// [`write_speed`](Project::write_speed) already makes, in its words);
4703 /// * the region would grow rather than shrink, i.e. it already plays faster
4704 /// than `speed`.
4705 pub fn speed_regions(
4706 &mut self,
4707 regions: &[(u32, u32)],
4708 speed: Speed,
4709 scope: &[Lane],
4710 ) -> crate::Result<()> {
4711 let regions = tidy(regions);
4712 let on = self.scoped(scope)?;
4713 let Some(&(first, _)) = regions.first() else {
4714 return Err("nothing to speed up".into());
4715 };
4716 self.scope_holds_takes_whole(&on, first)?;
4717 let labels = handles(&self.lanes);
4718 // Before anything is touched, because this is the refusal a person can
4719 // act on: a clip that laps over the edge of a silence has to be trimmed
4720 // (or the silences cut instead), and saying so after a rollback would
4721 // be saying it about a timeline that already looks different.
4722 for &(at, len) in &regions {
4723 for &l in &on {
4724 for c in &self.lanes[l].clips {
4725 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4726 {
4727 return Err(format!(
4728 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4729 speeding it up would pull the lanes apart -- trim it first, or cut the \
4730 silences out instead",
4731 labels[l].label(),
4732 c.start,
4733 at + len
4734 )
4735 .into());
4736 }
4737 }
4738 }
4739 }
4740 // The rest is checked as it is built: a split's own arithmetic is what
4741 // says whether a rate can address an edge. So the snapshot is taken
4742 // first and *rolled back* on a refusal -- one undo either way, and a
4743 // refusal still costs no step (`undo` pops the one just pushed).
4744 self.snapshot();
4745 for &(at, len) in regions.iter().rev() {
4746 self.write_split(at, false, &on);
4747 self.write_split(at + len, false, &on);
4748 let mut room: Option<(Lane, u32)> = None;
4749 let mut refused = None;
4750 for &l in &on {
4751 let clips = &self.lanes[l].clips;
4752 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4753 if (c.start, c.end()) != (at, at + len) {
4754 // *Which* edge did not come off: a rate that cannot
4755 // address the end of the silence is not a rate that
4756 // cannot address its start, and naming the wrong frame
4757 // sends the user looking in the wrong place.
4758 let edge = match c.start == at {
4759 true => at + len,
4760 false => at,
4761 };
4762 refused = Some(format!(
4763 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4764 detach it, or put it back to 1.00x first",
4765 labels[l].label(),
4766 c.start,
4767 c.speed
4768 ));
4769 continue;
4770 }
4771 let after = speed.frames(c.len());
4772 match room {
4773 None => room = Some((labels[l], after)),
4774 Some((first, n)) if n != after => {
4775 refused = Some(format!(
4776 "at {speed} the {} half of the silence at frame {at} would cover \
4777 {after} frames and the {} half {n}: they are one take and a take \
4778 is one span -- detach them first",
4779 labels[l].label(),
4780 first.label()
4781 ));
4782 }
4783 Some(_) => {}
4784 }
4785 }
4786 }
4787 let shrunk = match (refused, room) {
4788 (Some(e), _) => {
4789 self.undo();
4790 return Err(e.into());
4791 }
4792 // A gap on every lane: nothing to re-rate, and nothing to close.
4793 (None, None) => continue,
4794 (None, Some((_, after))) => after,
4795 };
4796 // The region's new length, on every scoped lane alike.
4797 let after = shrunk;
4798 let Some(delta) = len.checked_sub(shrunk) else {
4799 self.undo();
4800 return Err(format!(
4801 "the silence at frame {at} already plays faster than {speed}: \
4802 at that rate it would be {shrunk} frames instead of {len}"
4803 )
4804 .into());
4805 };
4806 for &l in &on {
4807 for c in &mut self.lanes[l].clips {
4808 if c.start == at && c.end() == at + len {
4809 c.speed = speed;
4810 } else if c.start >= at + len {
4811 c.start -= delta;
4812 }
4813 }
4814 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4815 // The captions on a scoped lane travel with the region's time:
4816 // a piece inside it plays in `after` frames instead of `len`
4817 // -- same words on less timeline, its window untouched, for
4818 // [`write_speed`]'s reason -- and everything behind the region
4819 // slides up by what the region gave back.
4820 //
4821 // The pieces inside re-time by their *boundaries*, not each
4822 // on its own: rounding one piece's start and its neighbour's
4823 // start apart can land both on the same frame (two one-frame
4824 // cues of a thirty-frame region at 2x both want frame 15), so
4825 // the mapped boundaries are walked in order and forced apart
4826 // -- each piece at least one frame, none past the region's own
4827 // new end, where the first follower lands exactly. A rounding
4828 // artifact is clamped, not refused: nothing about the words
4829 // asked for an overlap.
4830 let share = f64::from(after) / f64::from(len).max(1.);
4831 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4832 let mut prev = at;
4833 let subs = &mut self.lanes[l].subs;
4834 for i in 0..subs.len() {
4835 let s = subs[i];
4836 if s.start >= at + len {
4837 subs[i].start = s.start - delta;
4838 } else if s.start >= at && s.end() <= at + len {
4839 let mut start = map(s.start).max(prev);
4840 let end = map(s.end()).max(start + 1).min(at + after);
4841 start = start.min(end - 1);
4842 subs[i].start = start;
4843 subs[i].frames = end - start;
4844 prev = end;
4845 }
4846 }
4847 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4848 }
4849 }
4850 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4851 Ok(())
4852 }
4853
4854 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4855 /// -- the whole-group delete a single-lane front-end means. `false` for a
4856 /// bad index. Changes the mapping: the caller must reseek.
4857 pub fn delete(&mut self, idx: usize) -> bool {
4858 self.delete_in(Lane::V1, idx)
4859 }
4860
4861 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4862 /// in no group (or a group of one, which is the same thing to a delete) is
4863 /// what it always was: its own span cut out of *every* lane, so the
4864 /// timeline closes up under it. A clip in a group takes the group with it,
4865 /// each member by its **own** span and on its **own** lane -- the members
4866 /// keep their offsets, so their spans may disagree, and the lanes may end
4867 /// up out of step with each other, which is inherent to a hand-built group
4868 /// and one undo away. Every member -- clips and captions alike -- goes by
4869 /// the same law: its own span out of its own lane, hole closed; a caption
4870 /// in no group keeps the lift that leaves a gap, which is its own door's
4871 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4872 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4873 /// index, and for a lane that is not there. Changes the mapping: the
4874 /// caller must reseek.
4875 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4876 let Some(members) = self.group_of(lane, idx) else {
4877 return false;
4878 };
4879 if !members.alone() {
4880 return self.delete_members(&members);
4881 }
4882 let Some(clip) = self.lane(lane).get(idx).copied() else {
4883 return false;
4884 };
4885 self.ripple_delete(clip.start, clip.frames())
4886 }
4887
4888 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4889 /// caption in no group lifts, exactly as its own key always made it
4890 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4891 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4892 /// span out of its own lane, hole closed, captions and clips alike.
4893 /// `false` for a bad index.
4894 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4895 let Some(members) = self.group_of(lane, idx) else {
4896 return false;
4897 };
4898 if !members.alone() {
4899 return self.delete_members(&members);
4900 }
4901 self.lift_sub(lane, idx)
4902 }
4903
4904 /// The one whole-group delete both doors land in: every member's own span
4905 /// cut out of its own lane and the hole closed there -- clips and
4906 /// captions by the same law -- and nothing else on another lane moves,
4907 /// which is what keeps one member's ripple from dragging another
4908 /// member's lane out from under it. One snapshot, one undo step.
4909 fn delete_members(&mut self, members: &Members) -> bool {
4910 self.snapshot();
4911 for &(l, i) in &members.clips {
4912 let c = self.lanes[l].clips[i];
4913 ripple(&mut self.lanes, &[l], c.start, c.frames());
4914 }
4915 // The captions go by the same law their clip siblings do -- the span
4916 // out of its own lane, the hole closed -- and not by the lift a
4917 // *lone* caption's delete is: deleted with its group, the words after
4918 // it slide up with everything else, or the lane the group emptied is
4919 // the one lane the delete left a hole in. `ripple` is the one
4920 // mechanism (it clears the span and shifts the rest, clips and
4921 // captions alike); a sub lane holds no clips, so its other list is
4922 // untouched.
4923 for &(l, i) in &members.subs {
4924 let s = self.lanes[l].subs[i];
4925 ripple(&mut self.lanes, &[l], s.start, s.frames);
4926 }
4927 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4928 true
4929 }
4930
4931 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4932 #[cfg(test)]
4933 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4934 self.lane(lane)
4935 }
4936
4937 /// How many undo steps are stacked: what the sweep asks so "one op, one
4938 /// snapshot" is a count and not a guess.
4939 #[cfg(test)]
4940 pub(crate) fn history_len(&self) -> usize {
4941 self.history.len()
4942 }
4943
4944 /// How many redo steps are stacked: what the sweep asks to check `undo`
4945 /// left a branch behind, and that a fresh edit clears it.
4946 #[cfg(test)]
4947 pub(crate) fn redo_len(&self) -> usize {
4948 self.redo.len()
4949 }
4950
4951 /// Every part of the project that an edit can change, as comparable
4952 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4953 #[cfg(test)]
4954 pub(crate) fn parts(&self) -> SweepParts {
4955 SweepParts(
4956 self.sources.len(),
4957 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4958 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4959 )
4960 }
4961
4962 /// Restore every lane from before the last successful edit -- the clips and
4963 /// the lane list both. `false` when there is nothing left to undo. Pushes
4964 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4965 /// forward again.
4966 pub fn undo(&mut self) -> bool {
4967 match self.history.pop() {
4968 Some(prev) => {
4969 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4970 true
4971 }
4972 None => false,
4973 }
4974 }
4975
4976 /// Restore every lane from before the last [`Project::undo`] -- the
4977 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4978 /// is nothing left to redo, which is also true after any fresh edit: a
4979 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4980 pub fn redo(&mut self) -> bool {
4981 match self.redo.pop() {
4982 Some(next) => {
4983 self.history.push(std::mem::replace(&mut self.lanes, next));
4984 true
4985 }
4986 None => false,
4987 }
4988 }
4989
4990 /// The project an export renders from: everything a render reads, with the
4991 /// undo history left behind. An export never walks the history back, and
4992 /// cloning it costs a copy of every lane list in the session -- this is
4993 /// taken on the UI thread, so it clones the lanes and the sources alone.
4994 pub fn export_snapshot(&self) -> Self {
4995 Self {
4996 sources: self.sources.clone(),
4997 lanes: self.lanes.clone(),
4998 eq: self.eq.clone(),
4999 color: self.color.clone(),
5000 transform: self.transform.clone(),
5001 history: Vec::new(),
5002 redo: Vec::new(),
5003 next_link: self.next_link,
5004 subtitles: self.subtitles.clone(),
5005 limiter: self.limiter,
5006 tone: self.tone,
5007 }
5008 }
5009
5010 /// Half-open `(source, start, end)` segments in *source* seconds, from
5011 /// `timeline_frame` to the end of the timeline -- the play list for the
5012 /// audio worker, read off **`A1`**. A `None` source is a gap: the
5013 /// worker synthesises that many seconds of silence, which is what keeps the
5014 /// audio master clock counting across a hole instead of stalling on it.
5015 /// The first entry is partial when the position is mid-clip. Empty when the
5016 /// position is past the end or `fps` is not usable.
5017 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
5018 self.lane_segments_from(Lane::A1, timeline_frame, fps)
5019 }
5020
5021 /// [`segments_from`](Project::segments_from) for a named lane.
5022 pub fn lane_segments_from(
5023 &self,
5024 lane: Lane,
5025 timeline_frame: u32,
5026 fps: f64,
5027 ) -> Vec<(Option<usize>, f64, f64)> {
5028 if !(fps.is_finite() && fps > 0.0) {
5029 return Vec::new();
5030 }
5031 self.spans_from(lane, timeline_frame)
5032 .iter()
5033 .map(|span| match span.from {
5034 // A clip's window is in *source* seconds: where in the file it
5035 // reads from, which a delete before it never shifts. How many
5036 // source frames that is, is the span's own arithmetic -- at a
5037 // speed it is not the timeline length ([`Span::source_len`]).
5038 Some((source, in_frame)) => (
5039 Some(source),
5040 f64::from(in_frame) / fps,
5041 f64::from(in_frame + span.source_len()) / fps,
5042 ),
5043 // A gap has no file, so all it can say is how long it is.
5044 None => (None, 0.0, f64::from(span.len) / fps),
5045 })
5046 .collect()
5047 }
5048
5049 /// One play list per audio lane that *holds* something, in display order --
5050 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
5051 /// what an export asks how many lanes it would have to mix.
5052 ///
5053 /// Never empty: a timeline whose audio lanes are all empty (or which has no
5054 /// audio lane at all) still yields one all-gap list, so it plays silence
5055 /// against a master clock exactly as it did before there were lanes to
5056 /// count. Lanes with nothing on them are left out rather than mixed in as
5057 /// silence: they would cost a decode thread each and add zero.
5058 pub fn audio_segments_from(
5059 &self,
5060 timeline_frame: u32,
5061 fps: f64,
5062 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
5063 self.audio_lanes()
5064 .into_iter()
5065 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
5066 .collect()
5067 }
5068
5069 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
5070 /// builds a play list for, in the same order. Public because everything
5071 /// asked per audio lane -- which clip a segment's equalizer belongs to,
5072 /// which lane an mp4 export would copy -- has to read the very list the
5073 /// sound comes off, or the two answers drift apart (which is exactly how an
5074 /// `A2`-only project once exported silently, ledger).
5075 pub fn audio_lanes(&self) -> Vec<Lane> {
5076 let lanes: Vec<Lane> = self
5077 .lanes()
5078 .into_iter()
5079 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
5080 .collect();
5081 match lanes.is_empty() {
5082 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
5083 // no sound still plays silence against the master clock.
5084 true => vec![Lane::A1],
5085 false => lanes,
5086 }
5087 }
5088
5089 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
5090 /// segments plays at, and how long the timeline gives it: the same lanes in
5091 /// the same order, one entry per segment, `None` for a segment at real time
5092 /// -- which is every segment of a project nobody has speeded, and the path
5093 /// the audio worker leaves bit-identical.
5094 ///
5095 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
5096 /// the segment tuple is what every opener and a dozen tests speak, and a
5097 /// rate is not part of *which samples* a segment names.
5098 ///
5099 /// The seconds are what makes a resample exact: a segment's own window
5100 /// resolves to whole source frames, and dividing that by the rate would
5101 /// leave each clip a fraction of a frame short or long -- a drift that grows
5102 /// clip by clip. Told how much timeline it owes, the worker pads or trims
5103 /// the last few samples of each segment instead, so the sound stays locked
5104 /// to the picture however many speeded cuts it walks through.
5105 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
5106 self.audio_lanes()
5107 .into_iter()
5108 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
5109 .collect()
5110 }
5111
5112 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
5113 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5114 /// same walk, same `fps` refusal.
5115 pub fn lane_speeds_from(
5116 &self,
5117 lane: Lane,
5118 timeline_frame: u32,
5119 fps: f64,
5120 ) -> Vec<Option<Stretch>> {
5121 if !(fps.is_finite() && fps > 0.0) {
5122 return Vec::new();
5123 }
5124 self.spans_from(lane, timeline_frame)
5125 .iter()
5126 .map(|span| {
5127 (!span.speed.is_normal()).then(|| Stretch {
5128 step: span.speed.as_f64(),
5129 timeline_secs: f64::from(span.len) / fps,
5130 })
5131 })
5132 .collect()
5133 }
5134
5135 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
5136 /// segments plays through: the same lanes in the same order, one entry per
5137 /// segment, `None` where the segment is a gap or its clip plays flat.
5138 ///
5139 /// A parallel list rather than a fourth element of the segment tuple: that
5140 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
5141 /// and an effect is not part of *which samples* a segment names. A short
5142 /// list therefore means "flat from here on" rather than a length mismatch --
5143 /// see [`crate::AudioSession::open_mixed_streams_eq`].
5144 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
5145 self.audio_lanes()
5146 .into_iter()
5147 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
5148 .collect()
5149 }
5150
5151 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
5152 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
5153 /// same walk, same `fps` refusal, so the two lists cannot come out different
5154 /// lengths.
5155 pub fn lane_eqs_from(
5156 &self,
5157 lane: Lane,
5158 timeline_frame: u32,
5159 fps: f64,
5160 ) -> Vec<Option<EqParams>> {
5161 if !(fps.is_finite() && fps > 0.0) {
5162 return Vec::new();
5163 }
5164 self.spans_from(lane, timeline_frame)
5165 .iter()
5166 // A span off a clip covers that clip's frames and no others, so its
5167 // own start names the clip -- the index a [`Span`] does not carry.
5168 .map(|span| {
5169 self.map(lane, span.start)
5170 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
5171 })
5172 .collect()
5173 }
5174
5175 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
5176 /// segments plays through: the same lanes in the same order, one entry per
5177 /// segment, `None` where the segment is a gap or its clip has neither a
5178 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
5179 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
5180 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
5181 self.audio_lanes()
5182 .into_iter()
5183 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
5184 .collect()
5185 }
5186
5187 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
5188 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
5189 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
5190 if !(fps.is_finite() && fps > 0.0) {
5191 return Vec::new();
5192 }
5193 self.spans_from(lane, timeline_frame)
5194 .iter()
5195 .map(|span| {
5196 let (idx, _) = self.map(lane, span.start)?;
5197 let clip = self.lane(lane).get(idx)?;
5198 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
5199 // `span.len` is the clip's own remaining frames from
5200 // `span.start` on -- shorter than `clip.frames()` only
5201 // when this is the first span of a seek mid-clip.
5202 elapsed: clip.frames().saturating_sub(span.len),
5203 fade_in: clip.fade_in,
5204 fade_out: clip.fade_out,
5205 total: clip.frames(),
5206 })
5207 })
5208 .collect()
5209 }
5210
5211 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
5212 /// it has decided it will succeed -- a refusal must not cost an undo step.
5213 /// Clears the redo stack: a fresh edit branches off from here, so whatever
5214 /// `undo` had left to redo is no longer where this edit leads back to.
5215 fn snapshot(&mut self) {
5216 if self.history.len() == HISTORY_CAP {
5217 self.history.remove(0);
5218 }
5219 self.history.push(self.lanes.clone());
5220 self.redo.clear();
5221 }
5222
5223 fn new_link(&mut self) -> u32 {
5224 let id = self.next_link;
5225 self.next_link = self.next_link.saturating_add(1);
5226 id
5227 }
5228
5229}
5230
5231/// The handle of every lane, in storage order -- the one definition of what
5232/// [`Lane::ord`] counts.
5233fn handles(lanes: &[LaneData]) -> Vec<Lane> {
5234 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
5235 lanes
5236 .iter()
5237 .map(|l| match l.kind {
5238 LaneKind::Video => {
5239 video += 1;
5240 Lane::new(LaneKind::Video, video - 1)
5241 }
5242 LaneKind::Audio => {
5243 audio += 1;
5244 Lane::new(LaneKind::Audio, audio - 1)
5245 }
5246 LaneKind::Subtitle => {
5247 subtitle += 1;
5248 Lane::new(LaneKind::Subtitle, subtitle - 1)
5249 }
5250 })
5251 .collect()
5252}
5253
5254/// The one law a caption re-time scales by: frame `f` moves about the held
5255/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
5256/// commits it, [`Project::speeded_playhead`] previews it -- both build their
5257/// [`TimelineMap`] piece from this single answer so the two cannot drift
5258/// apart by a frame the way they once did.
5259fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
5260 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
5261 .round()
5262 .clamp(0., f64::from(u32::MAX)) as u32
5263}
5264
5265/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
5266/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
5267/// a speed cannot be applied twice or forgotten in one of them.
5268fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
5269 // Clamped inside the clip's own range: rounding at a slow rate can put the
5270 // last timeline frame of a clip a frame past its out-point, and a source
5271 // frame outside the range is one the next clip owns.
5272 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
5273}
5274
5275/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
5276/// finder generic makes the subtitle path use the same bounded-hole rules as
5277/// media lanes without teaching the media-specific take logic about captions.
5278trait GapPlacement {
5279 fn start_frame(&self) -> u32;
5280 fn end_frame(&self) -> u32;
5281}
5282
5283impl GapPlacement for Clip {
5284 fn start_frame(&self) -> u32 {
5285 self.start
5286 }
5287
5288 fn end_frame(&self) -> u32 {
5289 self.end()
5290 }
5291}
5292
5293impl GapPlacement for SubClip {
5294 fn start_frame(&self) -> u32 {
5295 self.start
5296 }
5297
5298 fn end_frame(&self) -> u32 {
5299 self.end()
5300 }
5301}
5302
5303/// Index of the placement covering `frame`, or `None` for a gap or past the
5304/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
5305fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
5306 let idx = items.partition_point(|item| item.start_frame() <= frame).checked_sub(1)?;
5307 (frame < items[idx].end_frame()).then_some(idx)
5308}
5309
5310/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
5311/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
5312/// invariant like [`at`]: the first placement whose start is past `frame` is
5313/// the far wall, and the last one that ends at or before `frame` (or the
5314/// timeline's own head, `0`, when there is none) is the near one.
5315fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
5316 if at(items, frame).is_some() {
5317 return None;
5318 }
5319 let idx = items.partition_point(|item| item.start_frame() <= frame);
5320 let next = items.get(idx)?;
5321 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
5322 Some((start, next.start_frame() - start))
5323}
5324
5325/// Every bounded hole in `items`, left to right. The tail after the last
5326/// placement is deliberately absent: there is no later placement for a ripple
5327/// to bring back.
5328fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
5329 let mut out = Vec::new();
5330 let mut next = 0;
5331 for item in items {
5332 if item.start_frame() > next {
5333 out.push((next, item.start_frame() - next));
5334 }
5335 next = item.end_frame();
5336 }
5337 out
5338}
5339
5340/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
5341/// there would cut in two. A placement's own first frame is not inside it.
5342fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
5343 let idx = at(clips, frame)?;
5344 // ...and, on a speeded clip, one its rate can actually address
5345 // ([`Speed::split_at`]): a cut between two showings of one source frame
5346 // would leave halves that no longer add up to the clip that was cut.
5347 (frame > clips[idx].start)
5348 .then_some(idx)
5349 .filter(|&idx| split_source(&clips[idx], frame).is_some())
5350}
5351
5352/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
5353/// rate cannot address that frame.
5354fn split_source(c: &Clip, frame: u32) -> Option<u32> {
5355 c.speed
5356 .split_at(c.len(), frame - c.start)
5357 .map(|src| c.in_frame + src)
5358}
5359
5360/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
5361/// rejoin: they must touch there, and be consecutive frames of one source.
5362fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
5363 let idx = clips.iter().position(|c| c.end() == frame)?;
5364 let next = clips.get(idx + 1)?;
5365 let joined = clips[idx].len() + next.len();
5366 (next.start == frame
5367 && next.source == clips[idx].source
5368 && next.in_frame == clips[idx].out_frame
5369 // ...at one rate, and one that puts the rejoined clip back in exactly
5370 // the room the two took up: what a split could have produced, which is
5371 // all this undoes.
5372 && next.speed == clips[idx].speed
5373 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
5374 .then_some(idx)
5375}
5376
5377/// The lane invariant: sorted by `start`, no two placements overlapping, no
5378/// empty placement. Checked at every constructor and asserted after every
5379/// mutation -- the offset model is only tractable while it holds.
5380/// The one thing an equalizer setting may not be: a value the text format
5381/// cannot write and read back as itself. Checked wherever params come in, so
5382/// what an edit produces is always what a save writes and a load reads.
5383fn finite(params: &EqParams) -> bool {
5384 params
5385 .bands
5386 .iter()
5387 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
5388}
5389
5390/// The same for a colour grade: [`crate::color`] itself falls back to identity
5391/// on a non-finite value, but a value that cannot be written and read back as
5392/// itself has no business reaching the model.
5393fn color_finite(p: &ColorParams) -> bool {
5394 p.brightness.is_finite()
5395 && p.contrast.is_finite()
5396 && p.saturation.is_finite()
5397 && p.tint.is_finite()
5398}
5399
5400/// The same for a transform: [`crate::scale`] clamps a non-finite value to
5401/// identity at read time, but a value that cannot round-trip has no business
5402/// reaching the model.
5403fn transform_finite(p: &TransformParams) -> bool {
5404 p.pos_x.is_finite()
5405 && p.pos_y.is_finite()
5406 && p.scale.is_finite()
5407 && p.rotate.is_finite()
5408 && p.crop_l.is_finite()
5409 && p.crop_r.is_finite()
5410 && p.crop_t.is_finite()
5411 && p.crop_b.is_finite()
5412}
5413
5414fn sorted_disjoint(clips: &[Clip]) -> bool {
5415 clips.iter().all(|c| c.out_frame > c.in_frame)
5416 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
5417}
5418
5419/// The very same invariant on a subtitle lane, in that lane's own two units:
5420/// sorted by `start`, no two placements overlapping, no empty placement at
5421/// either end. Asserted after every mutation, exactly as its twin is.
5422fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
5423 subs.iter()
5424 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
5425 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
5426}
5427
5428/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
5429/// the one conversion between a lane's clock and a cue's, and `0` for a rate
5430/// that is not one (every caller of this has already refused such a rate).
5431fn us_of(frames: i64, fps: f64) -> i64 {
5432 match fps.is_finite() && fps > 0.0 {
5433 true => ((frames as f64) / fps * 1e6).round() as i64,
5434 false => 0,
5435 }
5436}
5437
5438/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5439/// dropping what is inside the hole, splitting what straddles it and trimming
5440/// what overlaps an edge. The windows follow the cut by proportion
5441/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5442fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5443 let mut out = Vec::with_capacity(subs.len() + 1);
5444 for s in subs.drain(..) {
5445 if s.end() <= start || s.start >= end {
5446 out.push(s);
5447 continue;
5448 }
5449 if s.start < start {
5450 out.push(SubClip {
5451 frames: start - s.start,
5452 out_us: s.window_at(start),
5453 // Both pieces lose the group id, for [`clear`]'s reason: one
5454 // id on two boxes of one lane is the one thing it may never
5455 // mean.
5456 link: None,
5457 ..s
5458 });
5459 }
5460 if s.end() > end {
5461 out.push(SubClip {
5462 start: end,
5463 frames: s.end() - end,
5464 in_us: s.window_at(end),
5465 link: None,
5466 ..s
5467 });
5468 }
5469 }
5470 *subs = out;
5471}
5472
5473/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5474/// `len`, splitting a placement that straddles `at` so the two halves end up on
5475/// either side of the hole. A `len` of 0 is that split alone, which is what a
5476/// [`Project::split`] over a subtitle lane is.
5477fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5478 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5479 let s = subs[idx];
5480 let cut = s.window_at(at);
5481 subs[idx] = SubClip {
5482 frames: at - s.start,
5483 out_us: cut,
5484 link: None,
5485 ..s
5486 };
5487 subs.insert(
5488 idx + 1,
5489 SubClip {
5490 start: at,
5491 frames: s.end() - at,
5492 in_us: cut,
5493 link: None,
5494 ..s
5495 },
5496 );
5497 }
5498 for s in subs.iter_mut().filter(|s| s.start >= at) {
5499 s.start += len;
5500 }
5501}
5502
5503/// [`joinable`] for a subtitle lane: the first of the two placements a
5504/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5505/// produced and nothing else -- they touch on the timeline, they read the same
5506/// track, and the second one's window carries on where the first's stopped.
5507fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5508 let idx = subs.iter().position(|s| s.end() == frame)?;
5509 let next = subs.get(idx + 1)?;
5510 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5511 .then_some(idx)
5512}
5513
5514/// How far one `edge` of the caption at `idx` may travel against its own lane's
5515/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5516/// rate, which a caption *following* a group's trim does not have to be exact
5517/// about -- its own walls, its own one surviving frame, and nothing that needs
5518/// a clock.
5519fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5520 let s = &subs[idx];
5521 match edge {
5522 Edge::Start => (
5523 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5524 s.end() - 1,
5525 ),
5526 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5527 }
5528}
5529
5530/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5531/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5532/// forwards and backwards. The caption a group's trim is carrying has no rate
5533/// of its own and needs none: what one frame of it is worth in microseconds is
5534/// the window it already shows over the frames it already takes.
5535fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5536 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5537 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5538 match edge {
5539 Edge::Start => {
5540 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5541 s.frames = s.end() - to;
5542 s.start = to;
5543 }
5544 Edge::End => {
5545 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5546 s.frames = to - s.start;
5547 }
5548 }
5549 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5550}
5551
5552/// The grouping invariant, checked in release at [`Project::from_parts`] and
5553/// asserted by the tests after every edit: a link id names **at most one**
5554/// placement per lane -- a clip on a media lane or a caption on a subtitle
5555/// one, whichever carries it. That is all "these move together" can mean now
5556/// that a group is assembled by hand: the members keep their own spans and
5557/// their own offsets, and what binds them is the id alone.
5558///
5559/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5560/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5561/// placements of one group may cover different frames -- the offset-preserving
5562/// group a hand builds with [`Project::group_all`], which a drag moves by one
5563/// delta rather than by one span.
5564///
5565/// A link no other lane carries is legal and is not an error: lifting one half
5566/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5567/// timeline has to load again.
5568/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5569/// asked by the sweep suite's universal law.
5570#[cfg(test)]
5571pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5572 links_are_consistent(&p.lanes)
5573}
5574
5575fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5576 let handles = handles(lanes);
5577 for (data, lane) in lanes.iter().zip(&handles) {
5578 for (i, c) in data.clips.iter().enumerate() {
5579 let Some(id) = c.link else { continue };
5580 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5581 return Err(
5582 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5583 );
5584 }
5585 }
5586 // ...and the same for the captions, in their own list on the same lane:
5587 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5588 // id could be doubled on.
5589 for (i, s) in data.subs.iter().enumerate() {
5590 let Some(id) = s.link else { continue };
5591 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5592 return Err(format!(
5593 "link {id} names two captions in the {} lane",
5594 lane.label()
5595 )
5596 .into());
5597 }
5598 }
5599 }
5600 Ok(())
5601}
5602
5603/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5604/// it go, one straddling it is split in two, one overlapping an edge is
5605/// trimmed. Source frames follow the trim, so what is left plays what it always
5606/// played. Leaves the lane sorted and disjoint.
5607///
5608/// A piece the hole cut is no longer the take its group id names -- and both
5609/// halves of a straddled placement carrying that id would be the same id twice
5610/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5611fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5612 let mut out = Vec::with_capacity(clips.len() + 1);
5613 for c in clips.drain(..) {
5614 // Disjoint from the hole: untouched.
5615 if c.end() <= start || c.start >= end {
5616 out.push(c);
5617 continue;
5618 }
5619 // The head that survives in front of the hole -- as much source as fits
5620 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5621 // which at real time is that room itself. Never *more*: a head that
5622 // outgrew its room would reach into the hole it is being cut out of,
5623 // which is exactly the overlap a slow clip punched at a frame its rate
5624 // cannot address used to leave (at 0.25x a single source frame is four
5625 // timeline frames, and three frames of room hold none of it). `None`
5626 // there means no remainder at all, and the piece simply goes.
5627 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5628 && c.start < start
5629 {
5630 out.push(Clip {
5631 fade_in: 0,
5632 fade_out: 0,
5633 transition_out: 0,
5634 out_frame: c.in_frame + keep.min(c.len()),
5635 link: None,
5636 ..c
5637 });
5638 }
5639 // ...and the tail behind it, which keeps reading up to where it would
5640 // have: measured from its out-point for the head's reason, so what it
5641 // occupies still ends where the whole clip did -- and dropped whole on
5642 // the same `None`.
5643 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5644 && c.end() > end
5645 {
5646 out.push(Clip {
5647 fade_in: 0,
5648 fade_out: 0,
5649 transition_out: 0,
5650 start: end,
5651 in_frame: c.out_frame - keep.min(c.len()),
5652 link: None,
5653 ..c
5654 });
5655 }
5656 }
5657 *clips = out;
5658}
5659
5660/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5661/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5662/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5663/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5664/// the caller.
5665fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5666 for &i in on {
5667 let clips = &mut lanes[i].clips;
5668 clear(clips, at, at + len);
5669 for c in clips.iter_mut().filter(|c| c.start >= at) {
5670 c.start -= len;
5671 }
5672 debug_assert!(sorted_disjoint(clips));
5673 // The subtitle lanes close the hole with everything else: a caption
5674 // left standing where the picture it belongs to was cut out is the
5675 // desync a lane model exists to make impossible.
5676 let subs = &mut lanes[i].subs;
5677 sub_clear(subs, at, at + len);
5678 for s in subs.iter_mut().filter(|s| s.start >= at) {
5679 s.start -= len;
5680 }
5681 debug_assert!(subs_sorted_disjoint(subs));
5682 }
5683}
5684
5685/// Every lane, as the index list the two above take: what "the whole timeline"
5686/// is spelled as, and the scope [`Project::ripple_delete`] and
5687/// [`Project::split`] have always had.
5688fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5689 (0..lanes.len()).collect()
5690}
5691
5692/// A caller's region list as a batch may use it: sorted by start, empty entries
5693/// dropped, and touching or overlapping entries merged into one.
5694///
5695/// Overlapping regions are the one thing a batch cannot take -- cutting the
5696/// second would cut frames the first already moved -- and a detector handing
5697/// back two that touch means one silence, not two cuts. Merged rather than
5698/// refused: this is arithmetic on a preview, not a user's mistake.
5699fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5700 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5701 sorted.sort_by_key(|&(at, _)| at);
5702 let mut out: Vec<(u32, u32)> = Vec::new();
5703 for (at, len) in sorted {
5704 let end = at.saturating_add(len);
5705 match out.last_mut() {
5706 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5707 _ => out.push((at, len)),
5708 }
5709 }
5710 out
5711}
5712
5713/// Slides everything from `at` on later by `len`, splitting a placement that
5714/// straddles `at` so the two halves end up on either side of the hole. The
5715/// insert half of a rippling paste. The two halves lose the group id for the
5716/// reason [`clear`] gives.
5717fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5718 if let Some(idx) = splittable(clips, at) {
5719 let mut tail = clips[idx];
5720 // The cut in *source* frames, at the clip's own rate. `splittable` has
5721 // already refused a frame the rate cannot address, which is why
5722 // [`Project::paste`] refuses one too rather than opening room inside a
5723 // clip that cannot be cut there.
5724 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5725 tail.start = at;
5726 tail.link = None;
5727 clips[idx].out_frame = tail.in_frame;
5728 clips[idx].link = None;
5729 clips.insert(idx + 1, tail);
5730 }
5731 for c in clips.iter_mut().filter(|c| c.start >= at) {
5732 c.start += len;
5733 }
5734}
5735
5736/// Absolute, symlink-resolved when the file is reachable; the path as given
5737/// when it is not -- an unreadable path still deserves an index, it simply
5738/// dedups by spelling.
5739pub(crate) fn canonical(path: &Path) -> PathBuf {
5740 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5741}
5742
5743#[cfg(test)]
5744mod tests {
5745 use super::*;
5746
5747 const FPS: f64 = 30.0;
5748 /// Never opened -- `Project` is pure data, so a path that does not exist is
5749 /// simply a path that dedups by spelling.
5750 const FILE: &str = "/nonexistent/a.mp4";
5751 const FILE2: &str = "/nonexistent/b.mp4";
5752
5753 /// A contiguous placement, group id ignored: what most assertions compare.
5754 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5755 Clip {
5756 fade_in: 0,
5757 fade_out: 0,
5758 transition_out: 0,
5759 visualizer: 0,
5760 viz_paint: 0,
5761 start,
5762 in_frame,
5763 out_frame,
5764 source,
5765 link: None,
5766 eq: None,
5767 color: None,
5768 transform: None,
5769 fit: FitPolicy::default(),
5770 speed: Speed::NORMAL,
5771 }
5772 }
5773
5774 /// A caption placement for pure timeline tests: the track window is the
5775 /// same duration as the placement, so assertions can stay in frames.
5776 fn caption(start: u32, frames: u32) -> SubClip {
5777 SubClip {
5778 start,
5779 frames,
5780 track: 0,
5781 in_us: 0,
5782 out_us: i64::from(frames) * 1_000_000,
5783 link: None,
5784 }
5785 }
5786
5787 /// A subtitle palette row for tests that place captions on lanes.
5788 fn subtitle_track() -> SubtitleTrack {
5789 SubtitleTrack {
5790 path: FILE.into(),
5791 track: None,
5792 language: "eng".into(),
5793 name: String::new(),
5794 label: "eng".into(),
5795 cues: Vec::new(),
5796 bitmap: false,
5797 refused: None,
5798 }
5799 }
5800
5801 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5802 /// apart -- which is what makes the table's dedup and its prune visible.
5803 fn band_at(n: u32) -> EqParams {
5804 EqParams {
5805 bands: vec![crate::eq::Band {
5806 freq_hz: 1000.0,
5807 gain_db: f64::from(n) as f32 * 1.5,
5808 q: 0.707,
5809 kind: crate::eq::BandKind::Peak,
5810 }],
5811 }
5812 }
5813
5814 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5815 /// for the colour table.
5816 fn grade_at(n: u32) -> ColorParams {
5817 ColorParams {
5818 brightness: f64::from(n) as f32 * 0.05,
5819 ..Default::default()
5820 }
5821 }
5822
5823 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5824 /// twin for the transform table.
5825 fn transform_at(n: u32) -> TransformParams {
5826 TransformParams {
5827 pos_x: f64::from(n) as f32 * 0.05,
5828 ..Default::default()
5829 }
5830 }
5831
5832 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5833 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5834 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5835 }
5836
5837 /// Every lane with its group ids blanked, for comparing shape.
5838 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5839 p.lanes()
5840 .into_iter()
5841 .map(|l| {
5842 p.lane(l)
5843 .iter()
5844 .map(|c| Clip { link: None, ..*c })
5845 .collect()
5846 })
5847 .collect()
5848 }
5849
5850 /// The *source frame* every timeline frame reads, per lane -- the traversal
5851 /// a player performs. Deliberately not the clip index: a split changes which
5852 /// clip a frame belongs to, and nothing else.
5853 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5854 (0..p.timeline_frames() + 2)
5855 .map(|f| {
5856 p.lanes()
5857 .into_iter()
5858 .map(|l| p.map(l, f).map(|(_, source)| source))
5859 .collect()
5860 })
5861 .collect()
5862 }
5863
5864 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5865 /// fixture. Built through `split` so the constructor path is exercised too.
5866 fn three() -> Project {
5867 let mut p = Project::single(FILE, 9);
5868 assert!(p.split(3));
5869 assert!(p.split(5));
5870 assert_eq!(
5871 shape(&p),
5872 [
5873 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5874 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5875 ]
5876 );
5877 p
5878 }
5879
5880 #[test]
5881 fn single_is_the_whole_file_on_both_lanes() {
5882 let p = Project::single(FILE, 150);
5883 assert_eq!(p.clips().len(), 1);
5884 assert_eq!(p.lane(Lane::A1).len(), 1);
5885 assert_eq!(p.timeline_frames(), 150);
5886 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5887 // grouped: video and audio carry the same link
5888 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5889 assert!(p.clips()[0].link.is_some());
5890 // degenerate mapping: timeline == source
5891 assert_eq!(p.map_timeline(0), Some((0, 0)));
5892 assert_eq!(p.map_timeline(149), Some((0, 149)));
5893 assert_eq!(p.map_timeline(150), None);
5894 // never-empty invariant survives a bogus frame count
5895 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5896 }
5897
5898 #[test]
5899 fn split_cuts_every_lane_and_regroups_it_back() {
5900 let mut p = Project::single(FILE, 9);
5901 let before = traversal(&p);
5902 let before_shape = shape(&p);
5903
5904 assert!(p.split(4));
5905 for l in p.lanes() {
5906 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5907 }
5908 // The two sides are two groups, one per side, matching across the lanes.
5909 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5910 assert_eq!(v[0].link, a[0].link);
5911 assert_eq!(v[1].link, a[1].link);
5912 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5913 // A split changes no mapping, in either lane.
5914 assert_eq!(traversal(&p), before, "a split moves nothing");
5915
5916 assert!(p.regroup(4), "the inverse rejoins them");
5917 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5918 assert_eq!(traversal(&p), before);
5919 assert_eq!(
5920 p.lane(Lane::V1)[0].link,
5921 p.lane(Lane::A1)[0].link,
5922 "and the rejoined clip is one group again"
5923 );
5924 }
5925
5926 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
5927 /// the very first frame of a fade-in, unity at its last, equal-power
5928 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
5929 /// at all.
5930 #[test]
5931 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
5932 let f = Fade {
5933 elapsed: 0,
5934 fade_in: 10,
5935 fade_out: 10,
5936 total: 40,
5937 };
5938 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
5939 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
5940 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
5941 assert!(
5942 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
5943 "equal-power midpoint is sin(pi/4)"
5944 );
5945 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
5946 // The fade-out is the same curve, mirrored, counting down from the
5947 // clip's end: unity at the frame the ramp starts, the same
5948 // equal-power midpoint, and -- since `total` itself is one past the
5949 // clip's last valid frame -- the very last frame is one step short of
5950 // the silence a fade-in's own frame `0` lands on exactly.
5951 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
5952 assert!(
5953 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
5954 "the fade-out's own equal-power midpoint"
5955 );
5956 assert!(
5957 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
5958 "one step short of silence at the clip's last playable frame"
5959 );
5960 }
5961
5962 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
5963 /// not adjacent, and otherwise sets the shared edge's fades and nothing
5964 /// else.
5965 #[test]
5966 fn crossfade_only_joins_adjacent_audio_clips() {
5967 let mut p = Project::single(FILE, 20);
5968 assert!(p.split(10));
5969 assert!(
5970 !p.crossfade(Lane::V1, 0, 5),
5971 "video is not an audio lane"
5972 );
5973 assert!(
5974 !p.crossfade(Lane::A1, 1, 5),
5975 "there is no clip after idx 1"
5976 );
5977 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
5978 let a = p.lane(Lane::A1);
5979 assert_eq!(a[0].fade_out, 5);
5980 assert_eq!(a[1].fade_in, 5);
5981 assert_eq!(a[0].fade_in, 0);
5982 assert_eq!(a[1].fade_out, 0);
5983
5984 // A gap between two clips is not adjacency, even on an audio lane.
5985 let mut p2 = Project::single(FILE, 1);
5986 let a2 = p2.add_lane(LaneKind::Audio);
5987 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
5988 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5989 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
5990 }
5991
5992 /// The rule [`Project::write_split`] follows for the edge the razor makes:
5993 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
5994 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
5995 /// mirror image.
5996 #[test]
5997 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
5998 let mut p = Project::single(FILE, 20);
5999 assert!(p.set_fade_in(Lane::V1, 0, 15));
6000 assert!(p.set_fade_out(Lane::V1, 0, 15));
6001 assert!(p.split(5));
6002 let v = p.lane(Lane::V1);
6003 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
6004 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
6005 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
6006 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
6007 }
6008
6009 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
6010 /// no successor, and two clips that do not touch, and otherwise clamps
6011 /// the dissolve to the shorter of the two clips it spans.
6012 #[test]
6013 fn set_transition_out_only_dissolves_adjacent_video_clips() {
6014 let mut p = Project::single(FILE, 20);
6015 assert!(p.split(15), "a short 5-frame tail to clamp against");
6016 assert!(
6017 !p.set_transition_out(Lane::A1, 0, 5),
6018 "audio is not a video lane"
6019 );
6020 assert!(
6021 !p.set_transition_out(Lane::V1, 1, 5),
6022 "there is no clip after idx 1"
6023 );
6024 assert!(
6025 p.set_transition_out(Lane::V1, 0, 100),
6026 "the two halves are adjacent"
6027 );
6028 assert_eq!(
6029 p.transition_out_of(Lane::V1, 0),
6030 5,
6031 "clamped to the shorter neighbour's 5 frames"
6032 );
6033
6034 // A gap between two clips is not adjacency, even on the video lane.
6035 let mut p2 = Project::single(FILE, 1);
6036 let v2 = p2.add_lane(LaneKind::Video);
6037 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
6038 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
6039 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
6040 }
6041
6042 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
6043 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
6044 /// only the half that kept the clip's original *end* keeps the dissolve,
6045 /// re-clamped to its own now-shorter length; the head the cut just made
6046 /// has no successor to dissolve into and starts flat.
6047 #[test]
6048 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
6049 let mut p = Project::single(FILE, 20);
6050 assert!(
6051 !p.set_transition_out(Lane::V1, 0, 0),
6052 "one clip on the lane, no successor to dissolve into yet"
6053 );
6054 // Give the clip a dissolve by hand, then cut it in two.
6055 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
6056 assert!(p.split(5));
6057 let v = p.lane(Lane::V1);
6058 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
6059 assert_eq!(
6060 v[1].transition_out, 15,
6061 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
6062 );
6063 }
6064
6065 /// The music video's own path: the take comes apart into halves that carry
6066 /// ids of their own, one undo puts it back, and two clips over the same
6067 /// frames become one take again by hand.
6068 #[test]
6069 fn a_take_comes_apart_and_goes_back_together() {
6070 let mut p = Project::single(FILE, 9);
6071 let one = p.clips()[0].link.expect("a fresh project is one take");
6072 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
6073
6074 // A third lane in the same group -- and the merge case with it: a
6075 // placement is in no group, and grouping it in leaves *one* group.
6076 let v2 = p.add_lane(LaneKind::Video);
6077 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6078 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
6079 p.group(Lane::V1, 0, v2, 0)
6080 .expect("the same frames, one lane over");
6081 let id = p.clips()[0].link.expect("still a group");
6082 assert!(
6083 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6084 "one id over the three, not two groups sharing a span"
6085 );
6086 links_are_consistent(&p.lanes).expect("one id, one span");
6087
6088 // Detached by the sound: every half of the group, not only the two.
6089 assert!(p.ungroup(Lane::A1, 0));
6090 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
6091 assert!(
6092 ids.iter().all(Option::is_some),
6093 "a half keeps an id of its own"
6094 );
6095 assert!(
6096 ids.iter()
6097 .enumerate()
6098 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
6099 "and no two halves are the same group any more: {ids:?}"
6100 );
6101 links_are_consistent(&p.lanes).expect("a lone id is legal");
6102
6103 // One snapshot for the whole detach.
6104 assert!(p.undo());
6105 assert!(
6106 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
6107 "one undo puts the whole group back"
6108 );
6109
6110 // And back together by hand: the two the pointer named, and only them.
6111 assert!(p.ungroup(Lane::V1, 0));
6112 p.group(Lane::V1, 0, Lane::A1, 0)
6113 .expect("both cover [0, 9)");
6114 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
6115 assert_ne!(
6116 p.lane(v2)[0].link,
6117 p.lane(Lane::V1)[0].link,
6118 "the third half stayed detached"
6119 );
6120 links_are_consistent(&p.lanes).expect("one id, one span");
6121 }
6122
6123 /// What a group may not be, and what a detach has nothing to take apart --
6124 /// none of which may cost an undo step.
6125 #[test]
6126 fn a_group_is_one_span_and_one_clip_per_lane() {
6127 let mut p = three();
6128 let before = shape(&p);
6129 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
6130
6131 assert!(
6132 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
6133 "two clips of one lane are never one take"
6134 );
6135 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
6136 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
6137 assert!(
6138 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
6139 "{spans}"
6140 );
6141 assert!(
6142 spans.contains("trim them to matching bounds first"),
6143 "{spans}"
6144 );
6145 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
6146
6147 // A half nothing else is grouped with is already detached, a placement
6148 // is in no group at all, and an index that is not there has nothing to
6149 // detach either.
6150 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
6151 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
6152 assert!(p.lift(Lane::A1, 0));
6153 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
6154 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
6155
6156 // Two undos, one per edit: not one of the refusals pushed a snapshot.
6157 assert!(p.undo());
6158 assert!(p.undo());
6159 assert_eq!(shape(&p), before);
6160 }
6161
6162 /// Where a re-rate puts a playhead: the scene under the cursor stays the
6163 /// scene under the cursor, measured the way a viewer would -- the source
6164 /// frame playing at the playhead is the same frame after the write, at
6165 /// every playhead position the re-rate can catch one.
6166 #[test]
6167 fn a_re_rate_keeps_the_frame_under_the_playhead() {
6168 let caption = |start: u32, frames: u32| SubClip {
6169 start,
6170 frames,
6171 track: 0,
6172 in_us: 0,
6173 out_us: i64::from(frames) * 1_000_000,
6174 link: None,
6175 };
6176 let track = || SubtitleTrack {
6177 path: FILE.into(),
6178 track: None,
6179 language: "eng".into(),
6180 name: String::new(),
6181 label: "eng".into(),
6182 cues: Vec::new(),
6183 bitmap: false,
6184 refused: None,
6185 };
6186 // A group of a 300-frame clip and a caption offset 30 frames into it.
6187 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
6188 let s1 = p.add_lane(LaneKind::Subtitle);
6189 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
6190 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6191
6192 // The frame playing at `at`: which clip, and which source frame of it.
6193 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
6194 p.span_at(Lane::V1, at)
6195 .and_then(|s| s.from.map(|(source, from)| (source, from)))
6196 };
6197
6198 // Inside the held clip: the source frame under the playhead is the
6199 // same one after the re-rate, at 2x and at half speed both.
6200 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
6201 let at = 120;
6202 let before = playing(&p, at).expect("a clip under the playhead");
6203 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
6204 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
6205 .expect("room for it");
6206 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
6207 assert_eq!(before, after, "{what}: the same source frame plays");
6208 // ...and the write itself is untouched by the question.
6209 assert!(p.undo(), "{what}: one step back");
6210 }
6211
6212 // Past the group -- the clip ends at 300 and the caption at 270, so
6213 // from 300 on nothing is re-timed under the playhead: unmoved.
6214 for at in [300u32, 301, 1_000] {
6215 assert_eq!(
6216 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
6217 Some(at),
6218 "at {at}: outside every member, unmoved"
6219 );
6220 }
6221 // The boundary is exact: the held clip's own last frame (299) maps
6222 // to its new one (149 -- the last frame inside [0, 150), where the
6223 // shrunken clip's last source frame plays), and its first stays put.
6224 assert_eq!(
6225 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
6226 Some(149)
6227 );
6228 assert_eq!(
6229 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
6230 Some(0)
6231 );
6232 // A spot the caption shares with the clip maps by the clip (it is
6233 // what is *playing* there): the held clip's own proportion, which on
6234 // this fixture is also its head.
6235 assert_eq!(
6236 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
6237 Some(45),
6238 "the clip under the caption owns the spot"
6239 );
6240 }
6241
6242 /// A playhead inside another clip member of the group: that member keeps
6243 /// its own head, so the mapping is by its proportion and not the held
6244 /// clip's -- and the frame under the cursor is still the frame that was.
6245 #[test]
6246 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
6247 let mut p = Project::single(FILE, 300);
6248 // A second clip, grouped with the first but starting 300 later: the
6249 // head the group shares and its own differ by exactly that.
6250 let v2 = p.add_lane(LaneKind::Video);
6251 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
6252 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
6253 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
6254
6255 let at = 450; // inside the second member, 150 past its head
6256 let before = p.span_at(v2, at).and_then(|s| s.from);
6257 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
6258 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6259 .expect("room for it");
6260 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
6261 assert_eq!(before, after, "the second member's own frame plays");
6262 // ...and the mapping itself: 150 past its head halves, the head stays.
6263 assert_eq!(mapped, Some(375));
6264 }
6265
6266 /// The link counter a load seeds sits past every id the file names,
6267 /// captions included: a hand-grouped caption may carry the highest id there
6268 /// is, and a counter that read the clips alone would hand it to the next
6269 /// group that asked -- silently grouping the caption with clips it never
6270 /// met.
6271 #[test]
6272 fn the_link_counter_sits_past_a_caption_only_id() {
6273 let track = || SubtitleTrack {
6274 path: FILE.into(),
6275 track: None,
6276 language: "eng".into(),
6277 name: String::new(),
6278 label: "eng".into(),
6279 cues: Vec::new(),
6280 bitmap: false,
6281 refused: None,
6282 };
6283 let mut p = Project::single(FILE, 9);
6284 p.add_lane(LaneKind::Subtitle);
6285 let caption = SubClip {
6286 start: 0,
6287 frames: 6,
6288 track: 0,
6289 in_us: 0,
6290 out_us: 6_000_000,
6291 // The highest id in the file, and only a caption carries it.
6292 link: Some(1),
6293 };
6294 let mut p = p
6295 .with_subtitles(vec![track()])
6296 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
6297 .expect("a caption may carry the file's highest id");
6298
6299 // A new group on lanes the caption is not on mints the next id -- which
6300 // must not be the caption's.
6301 let v2 = p.add_lane(LaneKind::Video);
6302 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
6303 p.group_all(&[(Lane::V1, 0), (v2, 0)])
6304 .expect("the clips group");
6305 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
6306 assert_ne!(
6307 minted,
6308 1,
6309 "the caption's id is not re-issued to clips"
6310 );
6311 assert_eq!(
6312 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
6313 Some(1),
6314 "the caption keeps its own group"
6315 );
6316 assert!(links_are_consistent(&p.lanes).is_ok());
6317 }
6318
6319 /// A rate re-times the caption members of the group by the ratio it gives
6320 /// the held clip: the span on the timeline compresses about the held clip's
6321 /// head, the words' own window untouched -- and one undo puts it back.
6322 #[test]
6323 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
6324 let caption = |start: u32, frames: u32| SubClip {
6325 start,
6326 frames,
6327 track: 0,
6328 in_us: 0,
6329 out_us: i64::from(frames) * 1_000_000,
6330 link: None,
6331 };
6332 let track = || SubtitleTrack {
6333 path: FILE.into(),
6334 track: None,
6335 language: "eng".into(),
6336 name: String::new(),
6337 label: "eng".into(),
6338 cues: Vec::new(),
6339 bitmap: false,
6340 refused: None,
6341 };
6342 let grouped = || {
6343 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6344 let s1 = p.add_lane(LaneKind::Subtitle);
6345 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6346 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6347 (p, s1)
6348 };
6349
6350 // An aligned take, doubled: the caption plays in half the frames.
6351 let (mut p, s1) = grouped();
6352 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6353 .expect("room for it");
6354 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
6355 let s = p.sub_lane(s1)[0];
6356 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
6357 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
6358 assert!(links_are_consistent(&p.lanes).is_ok());
6359 assert!(p.undo());
6360 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
6361
6362 // An offset group, slowed to half: the caption's *offset from the held
6363 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
6364 // 0.5x, and still ends where the clip does.
6365 let (mut p, s1) = grouped();
6366 p.lift_sub(s1, 0);
6367 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
6368 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6369 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
6370 .expect("room for it");
6371 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
6372 let s = p.sub_lane(s1)[0];
6373 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
6374 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
6375
6376 // A stretch that runs the caption into its neighbour is refused, by
6377 // lane and frame, and costs no undo step.
6378 let (mut p, s1) = grouped();
6379 p.lift_sub(s1, 0);
6380 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6381 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
6382 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6383 let history = p.history.len();
6384 let err = p
6385 .set_speed(Lane::V1, 0, Speed::from_permille(500))
6386 .unwrap_err()
6387 .to_string();
6388 assert!(
6389 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
6390 "{err}"
6391 );
6392 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
6393 }
6394
6395 /// The silence scan's speed-up re-times the captions on a scoped lane with
6396 /// everything else: the piece inside the region plays in the region's new
6397 /// frames, and what sits behind the region slides up with the clips.
6398 #[test]
6399 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
6400 let caption = |start: u32, frames: u32| SubClip {
6401 start,
6402 frames,
6403 track: 0,
6404 in_us: 0,
6405 out_us: i64::from(frames) * 1_000_000,
6406 link: None,
6407 };
6408 let track = || SubtitleTrack {
6409 path: FILE.into(),
6410 track: None,
6411 language: "eng".into(),
6412 name: String::new(),
6413 label: "eng".into(),
6414 cues: Vec::new(),
6415 bitmap: false,
6416 refused: None,
6417 };
6418 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6419 let s1 = p.add_lane(LaneKind::Subtitle);
6420 // Words over the region [30, 60) and words behind it.
6421 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6422 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
6423
6424 // The region [30, 60) plays at 4x: 30 frames become 8, everything
6425 // behind slides up 22.
6426 // The scope is what the card's Take row says, caption lane included.
6427 p.speed_regions(
6428 &[(30, 30)],
6429 Speed::from_permille(4000),
6430 &[Lane::V1, Lane::A1, s1],
6431 )
6432 .expect("the region speeds up");
6433 let subs = p.sub_lane(s1);
6434 assert_eq!(
6435 (subs[0].start, subs[0].frames),
6436 (30, 8),
6437 "the piece inside plays in the region's new frames"
6438 );
6439 assert_eq!(
6440 (subs[1].start, subs[1].frames),
6441 (38, 30),
6442 "the piece behind slides up by what the region gave back"
6443 );
6444 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
6445 }
6446
6447 /// [`Project::speeded_playhead`]'s caption arm fires only when the
6448 /// playhead is inside a caption member and outside every clip member --
6449 /// a shape every other fixture avoids by keeping its caption inside the
6450 /// held clip. Here the caption overhangs the clip's tail, and the
6451 /// playhead standing in that overhang is answered by the caption's own
6452 /// piece: it scales about the held clip's head by the held clip's own
6453 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
6454 #[test]
6455 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
6456 let caption = |start: u32, frames: u32| SubClip {
6457 start,
6458 frames,
6459 track: 0,
6460 in_us: 0,
6461 out_us: i64::from(frames) * 1_000_000,
6462 link: None,
6463 };
6464 let track = || SubtitleTrack {
6465 path: FILE.into(),
6466 track: None,
6467 language: "eng".into(),
6468 name: String::new(),
6469 label: "eng".into(),
6470 cues: Vec::new(),
6471 bitmap: false,
6472 refused: None,
6473 };
6474 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6475 let s1 = p.add_lane(LaneKind::Subtitle);
6476 // The caption spans [80, 100) -- ten frames past the clip's own end
6477 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6478 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6479 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6480 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6481 // no clip member's old span reaches, is the caption's own question:
6482 // half of 95 is 47.5, rounded to 48.
6483 assert_eq!(
6484 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6485 Some(48),
6486 "the overhang frame answers through the caption's own piece"
6487 );
6488 }
6489
6490 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6491 /// map ([`map`]'s architecture law): a caption's landed span comes from
6492 /// the map's own ends, and the playhead standing at the caption's own
6493 /// last frame before the write has to land exactly where the write put
6494 /// it -- across clip lengths and rates that round differently, and an
6495 /// odd-length caption straddling the clip's own tail edge, the corner
6496 /// where `write_speed` used to answer a frame short.
6497 #[test]
6498 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6499 let caption = |start: u32, frames: u32| SubClip {
6500 start,
6501 frames,
6502 track: 0,
6503 in_us: 0,
6504 out_us: i64::from(frames) * 1_000_000,
6505 link: None,
6506 };
6507 let track = || SubtitleTrack {
6508 path: FILE.into(),
6509 track: None,
6510 language: "eng".into(),
6511 name: String::new(),
6512 label: "eng".into(),
6513 cues: Vec::new(),
6514 bitmap: false,
6515 refused: None,
6516 };
6517 for &len in &[90u32, 91, 177, 300, 301] {
6518 for &permille in &[500u16, 2000, 2500, 3000] {
6519 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6520 let s1 = p.add_lane(LaneKind::Subtitle);
6521 // An odd-length caption straddling the clip's tail edge: its
6522 // own last frame lands past the held clip.
6523 let c_start = len.saturating_sub(3);
6524 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6525 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6526 let speed = Speed::from_permille(permille);
6527 let last = c_start + 7 - 1;
6528 let mapped = p
6529 .speeded_playhead(Lane::V1, 0, speed, last)
6530 .expect("the caption is there");
6531 if p.set_speed(Lane::V1, 0, speed).is_err() {
6532 continue; // a refusal changes nothing: not this law's cell
6533 }
6534 let landed = p.sub_lane(s1)[0];
6535 if permille >= 1000 {
6536 // A speed-up compresses the timeline: many old frames
6537 // share one new frame, so the caption's own last old
6538 // frame lands flush with the write's own boundary --
6539 // the exact law [`write_speed`]'s worked drift-fix case
6540 // is stated against.
6541 assert_eq!(
6542 mapped,
6543 landed.end() - 1,
6544 "len {len} permille {permille}: the playhead at the caption's own \
6545 last frame lands where the write actually put it"
6546 );
6547 } else {
6548 // A slow-down expands it: one old frame becomes several
6549 // new ones, and `apply` answers where that frame's own
6550 // block *starts*, not where the caption's last new
6551 // frame (the end of that same block) sits -- a
6552 // one-frame gap inherent to the piece's own semantics,
6553 // not a drift between the two callers. Both still have
6554 // to agree the answer sits inside the caption the write
6555 // actually landed.
6556 assert!(
6557 (landed.start..landed.end()).contains(&mapped),
6558 "len {len} permille {permille}: the playhead lands inside the \
6559 caption the write actually put ({landed:?}), got {mapped}"
6560 );
6561 }
6562 }
6563 }
6564 }
6565
6566 /// A grouped caption's cues re-time with its clip: the placement's window
6567 /// crossed the timeline at its own proportion before any rate, and a
6568 /// re-rate changes that proportion (the frames compress, the window does
6569 /// not). A cue eight seconds into a window played at 2x crosses the screen
6570 /// four seconds in -- and at unity every cue lands exactly where it always
6571 /// did, byte for byte.
6572 #[test]
6573 fn a_grouped_captions_cues_re_time_with_its_clip() {
6574 let track = SubtitleTrack {
6575 path: FILE.into(),
6576 track: None,
6577 language: "eng".into(),
6578 name: String::new(),
6579 label: "eng".into(),
6580 cues: vec![crate::subtitle::Cue {
6581 start_us: 8_000_000,
6582 end_us: 9_000_000,
6583 text: "late line".into(),
6584 image: None,
6585 }],
6586 bitmap: false,
6587 refused: None,
6588 };
6589 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6590 let s1 = p.add_lane(LaneKind::Subtitle);
6591 // Ten seconds of the track over ten seconds of timeline: unity.
6592 p.place_sub(
6593 s1,
6594 0,
6595 SubClip {
6596 start: 0,
6597 frames: 300,
6598 track: 0,
6599 in_us: 0,
6600 out_us: 10_000_000,
6601 link: None,
6602 },
6603 )
6604 .expect("placed");
6605
6606 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6607 let unity = p.sub_lane_cues(s1, FPS);
6608 assert_eq!(
6609 unity
6610 .iter()
6611 .map(|c| (c.start_us, c.end_us, &*c.text))
6612 .collect::<Vec<_>>(),
6613 [(8_000_000, 9_000_000, "late line")],
6614 "a unity placement maps exactly as it always did"
6615 );
6616
6617 // Grouped with the clip and re-rated to 2x: the same window now crosses
6618 // in half the time, so the cue at 8s of it lands 4s in.
6619 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6620 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6621 .expect("room for it");
6622 let re_timed = p.sub_lane_cues(s1, FPS);
6623 assert_eq!(
6624 re_timed
6625 .iter()
6626 .map(|c| (c.start_us, c.end_us))
6627 .collect::<Vec<_>>(),
6628 [(4_000_000, 4_500_000)],
6629 "the cue crosses with the clip's new rate"
6630 );
6631 }
6632
6633 /// A video arriving on a timeline of words mutates none of them: the
6634 /// import's rippling insert used to open room on the subtitle lanes too,
6635 /// splitting a caption it landed inside and sliding the rest behind the
6636 /// video -- the hand asked for an add, and got a cut it never made. The
6637 /// words keep their own clock; co-travel is what a group is for.
6638 #[test]
6639 fn an_arriving_clip_never_touches_the_captions() {
6640 let caption = |start: u32, frames: u32| SubClip {
6641 start,
6642 frames,
6643 track: 0,
6644 in_us: i64::from(start) * 1_000_000 / 30,
6645 out_us: i64::from(start + frames) * 1_000_000 / 30,
6646 link: None,
6647 };
6648 let track = || SubtitleTrack {
6649 path: FILE.into(),
6650 track: None,
6651 language: "eng".into(),
6652 name: String::new(),
6653 label: "eng".into(),
6654 cues: Vec::new(),
6655 bitmap: false,
6656 refused: None,
6657 };
6658 // A timeline of words alone: 60 frames of caption, no media clips.
6659 let mut p = Project::single(FILE, 60)
6660 .with_subtitles(vec![track()]);
6661 for l in [Lane::V1, Lane::A1] {
6662 while !p.lane(l).is_empty() {
6663 p.lift(l, 0);
6664 }
6665 }
6666 let s1 = p.add_lane(LaneKind::Subtitle);
6667 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6668 let before = p.sub_lane(s1).to_vec();
6669
6670 // The video lands BEFORE the caption's span: nothing moves.
6671 let vid = clip(0, 0, 30, 0);
6672 assert!(p.paste(0, vid), "the video goes down at the head");
6673 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6674
6675 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6676 // byte the placement the hand made.
6677 assert!(p.paste(15, vid), "a second video lands inside the caption");
6678 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6679 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6680 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6681 assert!(links_are_consistent(&p.lanes).is_ok());
6682 }
6683
6684 /// The region's caption pieces re-time by mapped boundaries forced apart:
6685 /// rounding start and length independently can land two cues on one frame,
6686 /// and the artifact is clamped -- one frame each, in order, none past the
6687 /// region's new end -- never an overlap on the lane.
6688 #[test]
6689 fn a_regions_caption_pieces_never_round_onto_one_another() {
6690 let caption = |start: u32, frames: u32| SubClip {
6691 start,
6692 frames,
6693 track: 0,
6694 in_us: 0,
6695 out_us: i64::from(frames) * 1_000_000,
6696 link: None,
6697 };
6698 let track = |n| SubtitleTrack {
6699 path: FILE.into(),
6700 track: None,
6701 language: "eng".into(),
6702 name: String::new(),
6703 label: format!("eng{n}"),
6704 cues: Vec::new(),
6705 bitmap: false,
6706 refused: None,
6707 };
6708 // Three lanes, one repro shape each: adjacent one-frame cues, a
6709 // three-frame pair, and the region's last cue against the first
6710 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6711 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6712 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6713 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6714 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6715 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6716 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6717 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6718 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6719
6720 let mut scope = vec![Lane::V1, Lane::A1];
6721 scope.extend(lanes.iter().copied());
6722 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6723 .expect("the region speeds up");
6724 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6725 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6726 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6727 };
6728 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6729 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6730 // and the walk pushes the second to where the first ends.
6731 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6732 // The last cue of the region ends exactly where the region now does
6733 // (frame 15), and the caption behind it lands on that same frame:
6734 // touching, never overlapping.
6735 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6736 for &lane in &lanes {
6737 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6738 }
6739 }
6740
6741 /// The scope law names a caption half too: a scoped cut that would move one
6742 // track of a group whose caption sits outside the scope is refused.
6743 #[test]
6744 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6745 let caption = |start: u32, frames: u32| SubClip {
6746 start,
6747 frames,
6748 track: 0,
6749 in_us: 0,
6750 out_us: i64::from(frames) * 1_000_000,
6751 link: None,
6752 };
6753 let track = || SubtitleTrack {
6754 path: FILE.into(),
6755 track: None,
6756 language: "eng".into(),
6757 name: String::new(),
6758 label: "eng".into(),
6759 cues: Vec::new(),
6760 bitmap: false,
6761 refused: None,
6762 };
6763 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6764 let s1 = p.add_lane(LaneKind::Subtitle);
6765 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6766 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6767
6768 // The subtitle lane is not in the scope, so the group's caption half
6769 // sits outside it: refused, in the law's own words.
6770 let err = p
6771 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6772 .unwrap_err()
6773 .to_string();
6774 assert!(
6775 err.contains("is one take with the S1 caption at frame 0"),
6776 "{err}"
6777 );
6778
6779 // ...and with the caption's lane in the scope, the cut carries it:
6780 // the words over the hole go, and the words behind slide up.
6781 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6782 .expect("the whole group is in the scope");
6783 let subs = p.sub_lane(s1);
6784 assert_eq!(
6785 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6786 [(0, 10), (10, 75)],
6787 "the caption is cut and shifted with the clips"
6788 );
6789 }
6790
6791 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6792 /// mates riding along, the offsets kept, the refusals in words.
6793 #[test]
6794 fn a_hand_built_group_holds_clips_and_a_caption() {
6795 let caption = |start: u32, frames: u32| SubClip {
6796 start,
6797 frames,
6798 track: 0,
6799 in_us: 0,
6800 out_us: i64::from(frames) * 1_000_000,
6801 link: None,
6802 };
6803 let track = || SubtitleTrack {
6804 path: FILE.into(),
6805 track: None,
6806 language: "eng".into(),
6807 name: String::new(),
6808 label: "eng".into(),
6809 cues: Vec::new(),
6810 bitmap: false,
6811 refused: None,
6812 };
6813 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6814 let v2 = p.add_lane(LaneKind::Video);
6815 let s1 = p.add_lane(LaneKind::Subtitle);
6816 // A layer at its own offset, and a caption over the head of the take.
6817 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6818 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6819
6820 // Too few, one lane twice, and an index that is not there: words, no
6821 // snapshot.
6822 let history = p.history.len();
6823 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6824 assert!(p
6825 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6826 .unwrap_err()
6827 .to_string()
6828 .contains("V1 is picked twice"));
6829 assert!(p
6830 .group_all(&[(Lane::V1, 0), (s1, 9)])
6831 .unwrap_err()
6832 .to_string()
6833 .contains("no subtitle 9"));
6834 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6835
6836 // The group: the picture, the layer, and the caption -- and the sound
6837 // the picture was already grouped with comes along unasked.
6838 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6839 .expect("three picks, three lanes");
6840 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6841 for lane in [Lane::V1, Lane::A1, v2] {
6842 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6843 }
6844 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6845 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6846 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6847 assert!(links_are_consistent(&p.lanes).is_ok());
6848 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6849
6850 // ...and one undo takes it apart again.
6851 assert!(p.undo());
6852 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
6853
6854 // Detach names a caption like it names a clip: every member an id of
6855 // its own, which is never `None` (see `ungroup`).
6856 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
6857 assert!(p.ungroup(s1, 0));
6858 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
6859 assert!(loose_sub.is_some() && loose_clip.is_some());
6860 assert_ne!(loose_sub, loose_clip);
6861 assert!(links_are_consistent(&p.lanes).is_ok());
6862 }
6863
6864 /// Two captions on one sub lane, each already grouped with a *different*
6865 /// clip: `group_all` over both those clips would merge the two existing
6866 /// groups into one id and leave both captions on `s1` carrying it --
6867 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
6868 /// group closes. Refused by name, and nothing moves.
6869 #[test]
6870 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
6871 let caption = |start: u32, frames: u32| SubClip {
6872 start,
6873 frames,
6874 track: 0,
6875 in_us: 0,
6876 out_us: i64::from(frames) * 1_000_000,
6877 link: None,
6878 };
6879 let track = || SubtitleTrack {
6880 path: FILE.into(),
6881 track: None,
6882 language: "eng".into(),
6883 name: String::new(),
6884 label: "eng".into(),
6885 cues: Vec::new(),
6886 bitmap: false,
6887 refused: None,
6888 };
6889 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6890 let v2 = p.add_lane(LaneKind::Video);
6891 let s1 = p.add_lane(LaneKind::Subtitle);
6892 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
6893 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
6894 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6895 // V1 grouped with the first caption, v2 with the second -- two
6896 // separate groups, each already one member per lane.
6897 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6898 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
6899 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
6900
6901 let history = p.history.len();
6902 let err = p
6903 .group_all(&[(Lane::V1, 0), (v2, 0)])
6904 .unwrap_err()
6905 .to_string();
6906 assert!(err.contains("one placement per lane"), "{err}");
6907 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
6908 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
6909 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
6910 assert!(links_are_consistent(&p.lanes).is_ok());
6911 }
6912
6913 /// A split hands the caption of a group the same ids it hands the clips:
6914 /// the left halves keep the group, the right halves share a fresh one.
6915 #[test]
6916 fn a_split_cuts_a_grouped_caption_with_its_clips() {
6917 let caption = |start: u32, frames: u32| SubClip {
6918 start,
6919 frames,
6920 track: 0,
6921 in_us: 0,
6922 out_us: i64::from(frames) * 1_000_000,
6923 link: None,
6924 };
6925 let track = || SubtitleTrack {
6926 path: FILE.into(),
6927 track: None,
6928 language: "eng".into(),
6929 name: String::new(),
6930 label: "eng".into(),
6931 cues: Vec::new(),
6932 bitmap: false,
6933 refused: None,
6934 };
6935 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6936 let s1 = p.add_lane(LaneKind::Subtitle);
6937 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
6938 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6939 let take = p.lane(Lane::V1)[0].link.expect("the group id");
6940
6941 assert!(p.split(4));
6942 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6943 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6944 assert_eq!(left.frames, 4);
6945 assert_eq!(
6946 right.link,
6947 p.lane(Lane::V1)[1].link,
6948 "the caption's tail shares the clips' fresh id"
6949 );
6950 assert_ne!(right.link, Some(take));
6951 assert!(links_are_consistent(&p.lanes).is_ok());
6952
6953 // Regroup at the seam restores the take, caption included.
6954 assert!(p.regroup(4));
6955 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6956 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6957 }
6958
6959 /// Deleting a member of a hand-built group takes the group: every
6960 /// member's own span out of its own lane, hole closed -- the lanes may
6961 /// end up out of step, which is what one undo restores together.
6962 #[test]
6963 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6964 let caption = |start: u32, frames: u32| SubClip {
6965 start,
6966 frames,
6967 track: 0,
6968 in_us: 0,
6969 out_us: i64::from(frames) * 1_000_000,
6970 link: None,
6971 };
6972 let track = || SubtitleTrack {
6973 path: FILE.into(),
6974 track: None,
6975 language: "eng".into(),
6976 name: String::new(),
6977 label: "eng".into(),
6978 cues: Vec::new(),
6979 bitmap: false,
6980 refused: None,
6981 };
6982 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6983 let s1 = p.add_lane(LaneKind::Subtitle);
6984 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6985 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6986 // A neighbour on a lane the group does not touch.
6987 let v2 = p.add_lane(LaneKind::Video);
6988 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6989
6990 // By the picture or by the caption, the same whole-group delete.
6991 assert!(p.delete_sub_in(s1, 0));
6992 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6993 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6994 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6995 assert!(links_are_consistent(&p.lanes).is_ok());
6996 assert!(p.undo(), "one step puts the group back");
6997 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6998 }
6999
7000 /// The delete law, one statement for every anchor: a caption deleted
7001 /// WITH its group ripples its lane exactly as its clip siblings do --
7002 /// the hole closes and what follows slides up -- while a caption lifted
7003 /// alone leaves its gap, as it always has. And the delete of a grouped
7004 /// clip takes the group from whichever member was clicked.
7005 #[test]
7006 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
7007 let caption = |start: u32, frames: u32| SubClip {
7008 start,
7009 frames,
7010 track: 0,
7011 in_us: 0,
7012 out_us: i64::from(frames) * 1_000_000,
7013 link: None,
7014 };
7015 let track = || SubtitleTrack {
7016 path: FILE.into(),
7017 track: None,
7018 language: "eng".into(),
7019 name: String::new(),
7020 label: "eng".into(),
7021 cues: Vec::new(),
7022 bitmap: false,
7023 refused: None,
7024 };
7025 // V+A+S grouped, with a second caption BEHIND the group's caption:
7026 // closing the hole is what the second caption's position says.
7027 let group = || {
7028 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
7029 let s1 = p.add_lane(LaneKind::Subtitle);
7030 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
7031 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
7032 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7033 (p, s1)
7034 };
7035
7036 // Deleted by the picture: all three lanes close.
7037 let (mut p, s1) = group();
7038 assert!(p.delete_in(Lane::V1, 0));
7039 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
7040 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
7041 assert_eq!(
7042 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
7043 [60],
7044 "the caption's lane closed by its own span: the follower slid up"
7045 );
7046 assert!(p.undo(), "one step");
7047 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
7048
7049 // By the sound: the same whole-group delete.
7050 let (mut p, s1) = group();
7051 assert!(p.delete_in(Lane::A1, 0));
7052 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7053 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
7054
7055 // By the caption itself: the same again.
7056 let (mut p, s1) = group();
7057 assert!(p.delete_sub_in(s1, 0));
7058 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
7059 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
7060 assert!(links_are_consistent(&p.lanes).is_ok());
7061
7062 // A caption lifted ALONE still leaves its gap: the ungrouped law,
7063 // unchanged.
7064 let (mut p, s1) = group();
7065 assert!(p.ungroup(s1, 0), "the caption stands alone");
7066 assert!(p.lift_sub(s1, 0));
7067 assert_eq!(
7068 p.sub_lane(s1)[0].start, 90,
7069 "the follower stayed put: a lone caption's lift is a gap"
7070 );
7071 }
7072
7073 /// Dragging a grouped caption carries its clips, one delta for all of them
7074 /// -- and a caption in no group refuses an overlap exactly as it always did.
7075 #[test]
7076 fn dragging_a_grouped_caption_carries_its_group() {
7077 let caption = |start: u32, frames: u32| SubClip {
7078 start,
7079 frames,
7080 track: 0,
7081 in_us: 0,
7082 out_us: i64::from(frames) * 1_000_000,
7083 link: None,
7084 };
7085 let track = || SubtitleTrack {
7086 path: FILE.into(),
7087 track: None,
7088 language: "eng".into(),
7089 name: String::new(),
7090 label: "eng".into(),
7091 cues: Vec::new(),
7092 bitmap: false,
7093 refused: None,
7094 };
7095 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7096 let s1 = p.add_lane(LaneKind::Subtitle);
7097 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
7098 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7099
7100 // Same lane, further along: everyone moves by the same eight frames.
7101 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
7102 assert_eq!(p.sub_lane(s1)[0].start, 10);
7103 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
7104 assert!(links_are_consistent(&p.lanes).is_ok());
7105
7106 // ...and an ungrouped caption is the caption it always was.
7107 assert!(p.ungroup(s1, 0));
7108 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
7109 let s1 = q.add_lane(LaneKind::Subtitle);
7110 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
7111 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
7112 assert!(q
7113 .move_sub(s1, 0, s1, 3)
7114 .unwrap_err()
7115 .to_string()
7116 .contains("already covers"));
7117 }
7118
7119 /// A trim carries a group's caption by the same delta as its clips, clamped
7120 /// to the caption's own walls -- the offsets between the members survive.
7121 #[test]
7122 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
7123 let caption = |start: u32, frames: u32| SubClip {
7124 start,
7125 frames,
7126 track: 0,
7127 in_us: 0,
7128 out_us: i64::from(frames) * 1_000_000,
7129 link: None,
7130 };
7131 let track = || SubtitleTrack {
7132 path: FILE.into(),
7133 track: None,
7134 language: "eng".into(),
7135 name: String::new(),
7136 label: "eng".into(),
7137 cues: Vec::new(),
7138 bitmap: false,
7139 refused: None,
7140 };
7141 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
7142 let s1 = p.add_lane(LaneKind::Subtitle);
7143 // The caption sits two frames into the take and ends one early. The
7144 // source runs past the clip, or there is no tail to pull out.
7145 let src = &[20];
7146 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
7147 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
7148
7149 // The tail goes out by three: the clip to 12, the caption to 11.
7150 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
7151 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
7152 assert_eq!(
7153 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
7154 (2, 11),
7155 "the caption follows by the delta"
7156 );
7157 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
7158
7159 // The head comes in by two: everyone's start moves two along.
7160 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
7161 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
7162 assert!(links_are_consistent(&p.lanes).is_ok());
7163 }
7164
7165 #[test]
7166 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
7167 let mut p = three();
7168 let before = shape(&p);
7169 assert!(!p.split(0), "timeline 0 has nothing before it");
7170 assert!(!p.split(3), "existing boundary");
7171 assert!(!p.split(5), "existing boundary");
7172 assert!(!p.split(9), "one past the last frame");
7173 assert!(!p.split(1_000));
7174 assert_eq!(shape(&p), before);
7175 // one undo lands before the *second* split, so the refusals pushed nothing
7176 assert!(p.undo());
7177 assert_eq!(p.clips().len(), 2, "refused splits push no history");
7178
7179 // ...and a frame that is a gap in both lanes has nothing to split.
7180 let mut p = three();
7181 assert!(p.lift(Lane::V1, 1));
7182 assert!(p.lift(Lane::A1, 1));
7183 assert!(!p.split(4), "a gap is not a clip");
7184 }
7185
7186 #[test]
7187 fn regroup_refuses_what_a_split_could_not_have_made() {
7188 let mut p = three();
7189 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
7190 assert!(p.regroup(5));
7191 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
7192 // A boundary with a gap on one side, and one where the sources do not
7193 // meet, are both refused.
7194 let mut p = three();
7195 assert!(p.lift(Lane::V1, 1));
7196 assert!(p.lift(Lane::A1, 1));
7197 assert!(!p.regroup(3), "nothing starts at 3 any more");
7198 let mut p = three();
7199 for l in p.lanes() {
7200 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
7201 }
7202 assert!(!p.regroup(3), "source 100 does not follow source 3");
7203 assert!(!p.regroup(0), "nothing ends at 0");
7204 assert!(!p.regroup(1_000));
7205 }
7206
7207 #[test]
7208 fn map_and_spans_sweep_every_boundary() {
7209 let p = three();
7210 assert_eq!(p.timeline_frames(), 9);
7211 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
7212 // contiguous source here, so the clip index is what actually moves
7213 let expect = [
7214 (0, (0, 0)),
7215 (1, (0, 1)),
7216 (2, (0, 2)),
7217 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
7218 (4, (1, 4)),
7219 (5, (2, 5)),
7220 (6, (2, 6)),
7221 (7, (2, 7)),
7222 (8, (2, 8)),
7223 ];
7224 for (t, want) in expect {
7225 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
7226 }
7227 assert_eq!(p.map_timeline(9), None);
7228 // A span is the rest of the clip from where it was asked about.
7229 assert_eq!(
7230 p.span_at(Lane::V1, 6),
7231 Some(Span {
7232 start: 6,
7233 len: 3,
7234 from: Some((0, 6)),
7235 speed: Speed::NORMAL
7236 })
7237 );
7238 assert_eq!(p.span_at(Lane::V1, 9), None);
7239 }
7240
7241 /// The fit policy is one byte *in* the clip rather than an index into a
7242 /// table like the eq and the grade: there is nothing for a table to share.
7243 /// It costs the clip nothing at all -- the fields before it (a `usize`
7244 /// source and two `Option<u16>`s) already left the struct padded to 40
7245 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
7246 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
7247 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
7248 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
7249 /// words after it pads out to the next multiple of 8: 56 bytes total.
7250 /// The transform index is a third `Option<u16>`, same reason as the eq and
7251 /// colour ones before it -- it lands in bytes already spent on padding, so
7252 /// the struct still costs 56.
7253 /// The visualizer look is the first field whose own width outgrows the
7254 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
7255 /// the clip's own four), so the words after it come to 60 and the
7256 /// alignment rounds them to 64 -- one word more than a clip used to cost.
7257 /// This is the assert that says so: a clip that grows a word grows every
7258 /// undo snapshot and every clipboard copy with it.
7259 #[test]
7260 fn a_fit_policy_costs_the_clip_no_word() {
7261 assert_eq!(
7262 std::mem::size_of::<Clip>(),
7263 64,
7264 "Clip changed size: {} bytes",
7265 std::mem::size_of::<Clip>()
7266 );
7267 }
7268
7269 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
7270 /// anything in `three()` so it is recognisable wherever it lands.
7271 const PASTED: Clip = Clip {
7272 fade_in: 0,
7273 fade_out: 0,
7274 transition_out: 0,
7275 visualizer: 0,
7276 viz_paint: 0,
7277 start: 0,
7278 in_frame: 100,
7279 out_frame: 102,
7280 source: 0,
7281 link: None,
7282 eq: None,
7283 color: None,
7284 transform: None,
7285 fit: FitPolicy::Fit,
7286 speed: Speed::NORMAL,
7287 };
7288
7289 #[test]
7290 fn paste_mid_clip_splits_around_it() {
7291 let mut p = three();
7292 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
7293 assert_eq!(p.timeline_frames(), 11);
7294 assert_eq!(
7295 shape(&p)[0],
7296 vec![
7297 clip(0, 0, 3, 0),
7298 clip(3, 3, 5, 0),
7299 clip(5, 5, 6, 0),
7300 clip(6, 100, 102, 0),
7301 clip(8, 6, 9, 0),
7302 ]
7303 );
7304 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
7305 // The pasted frames are exactly where they were asked for, and the
7306 // split-off remainder resumes after them.
7307 assert_eq!(p.map_timeline(6), Some((3, 100)));
7308 assert_eq!(p.map_timeline(7), Some((3, 101)));
7309 assert_eq!(p.map_timeline(8), Some((4, 6)));
7310 }
7311
7312 #[test]
7313 fn paste_at_boundary_zero_and_end() {
7314 let mut p = three();
7315 assert!(p.paste(3, PASTED), "existing boundary: no split");
7316 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
7317 assert_eq!(p.map_timeline(3), Some((1, 100)));
7318
7319 let mut p = three();
7320 assert!(p.paste(0, PASTED));
7321 assert_eq!(p.map_timeline(0), Some((0, 100)));
7322 assert_eq!(p.map_timeline(2), Some((1, 0)));
7323
7324 // At the end: appended, there being nothing in front to leave black.
7325 let mut p = three();
7326 assert!(p.paste(9, PASTED));
7327 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
7328 // Past it: down on the frame it was asked for, black in front of it --
7329 // a row let go on the open bed lands under the ghost that promised it.
7330 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
7331 assert!(p.paste(1_000, PASTED));
7332 assert_eq!(p.timeline_frames(), 1_002);
7333 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
7334 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
7335
7336 // An empty clip is the one thing refused, and it pushes no history.
7337 let mut p = three();
7338 assert!(!p.paste(4, clip(0, 7, 7, 0)));
7339 assert_eq!(p.clips().len(), 3);
7340 }
7341
7342 /// The data-loss paste: a clip of a source with no picture used to land on
7343 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
7344 /// carried it was refused on the way back in ("a box with a larger size").
7345 #[test]
7346 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
7347 let mut p = three();
7348 let wav = p.import("/nonexistent/song.wav", 0);
7349 let copied = Clip {
7350 fade_in: 0,
7351 fade_out: 0,
7352 transition_out: 0,
7353 visualizer: 0,
7354 viz_paint: 0,
7355 source: wav,
7356 ..PASTED
7357 };
7358 assert!(p.paste(3, copied));
7359 // The room is opened on every lane, or the two would slide apart...
7360 assert_eq!(p.timeline_frames(), 11);
7361 assert_eq!(
7362 shape(&p)[0],
7363 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
7364 "the video lane got room and nothing else"
7365 );
7366 // ...but the clip itself only reaches the lane that can play it.
7367 assert_eq!(
7368 shape(&p)[1],
7369 vec![
7370 clip(0, 0, 3, 0),
7371 clip(3, 100, 102, wav),
7372 clip(5, 3, 5, 0),
7373 clip(7, 5, 9, 0)
7374 ]
7375 );
7376 // A source with a picture is unchanged: still the grouped pair.
7377 let mut p = three();
7378 assert!(p.paste(3, PASTED));
7379 assert_eq!(shape(&p)[0], shape(&p)[1]);
7380 }
7381
7382 /// A hand-written file may hold a clip that ends at the very last frame
7383 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
7384 /// to wrap its start round to the front of the lane: an overlap in debug, a
7385 /// project no reload would accept in release.
7386 #[test]
7387 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
7388 let far = clip(u32::MAX - 90, 0, 90, 0);
7389 let parts = |c: Clip| {
7390 Project::from_parts(
7391 vec![Source::new(FILE, 0)],
7392 two(vec![c], vec![c]),
7393 Vec::new(),
7394 Vec::new(),
7395 Vec::new(),
7396 )
7397 .expect("valid parts")
7398 };
7399 let mut p = parts(far);
7400 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
7401 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
7402 assert!(!p.undo(), "...and pushes no history either");
7403 assert!(
7404 !p.paste(u32::MAX, PASTED),
7405 "appending has nowhere to go either: the timeline ends at the last frame"
7406 );
7407 // With room for exactly those frames the same paste is taken.
7408 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
7409 assert!(p.paste(0, PASTED));
7410 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
7411 }
7412
7413 #[test]
7414 fn paste_undoes_in_one_step() {
7415 let mut p = three();
7416 let before = shape(&p);
7417 assert!(p.paste(6, PASTED));
7418 assert!(p.undo());
7419 assert_eq!(shape(&p), before, "a paste is one undo step");
7420 }
7421
7422 #[test]
7423 fn a_copy_outlives_the_clip_it_came_from() {
7424 let mut p = three();
7425 let copied = p.clips()[1]; // [3,5)
7426 assert!(p.delete(1));
7427 // Just a frame range: the source is still on disk either way.
7428 assert!(p.paste(0, copied));
7429 assert_eq!(p.map_timeline(0), Some((0, 3)));
7430 assert_eq!(p.timeline_frames(), 9);
7431 }
7432
7433 #[test]
7434 fn delete_closes_the_gap_on_both_lanes() {
7435 let mut p = three();
7436 assert!(p.delete(1));
7437 assert_eq!(p.timeline_frames(), 7);
7438 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
7439 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
7440 // timeline 3 used to be source 3; the gap closed so it is source 5 now
7441 assert_eq!(p.map_timeline(3), Some((1, 5)));
7442 assert_eq!(p.map_timeline(6), Some((1, 8)));
7443 assert_eq!(p.map_timeline(7), None);
7444 }
7445
7446 #[test]
7447 fn delete_first_last_and_only() {
7448 let mut p = three();
7449 assert!(p.delete(0));
7450 assert_eq!(p.map_timeline(0), Some((0, 3)));
7451 assert_eq!(p.timeline_frames(), 6);
7452
7453 let mut p = three();
7454 assert!(p.delete(2));
7455 assert_eq!(p.timeline_frames(), 5);
7456 assert_eq!(p.map_timeline(4), Some((1, 4)));
7457
7458 assert!(!p.delete(2), "index past the end");
7459 assert!(p.delete(1));
7460 assert!(p.delete(0), "and the last remaining clip goes too");
7461 assert_eq!(p.clips().len(), 0);
7462 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
7463 assert!(!p.delete(0), "there is nothing left to delete");
7464 assert!(p.undo(), "one gesture, one undo");
7465 assert_eq!(p.clips().len(), 1);
7466 }
7467
7468 /// The offset model's point: one lane loses a clip, the other does not move.
7469 #[test]
7470 fn a_lift_leaves_a_gap_and_moves_nothing() {
7471 let mut p = three();
7472 let video_before = shape(&p)[0].clone();
7473 assert!(p.lift(Lane::A1, 1));
7474 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7475 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7476 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7477 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7478 assert_eq!(p.map(Lane::A1, 4), None);
7479 assert_eq!(
7480 p.span_at(Lane::A1, 3),
7481 Some(Span {
7482 start: 3,
7483 len: 2,
7484 from: None,
7485 speed: Speed::NORMAL
7486 })
7487 );
7488 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7489 assert!(p.undo());
7490 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7491 }
7492
7493 #[test]
7494 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7495 let mut p = three();
7496 assert!(p.lift(Lane::A1, 2));
7497 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7498 assert_eq!(
7499 p.span_at(Lane::A1, 5),
7500 Some(Span {
7501 start: 5,
7502 len: 4,
7503 from: None,
7504 speed: Speed::NORMAL
7505 }),
7506 "the audio lane holds silence to the end of the picture"
7507 );
7508 assert_eq!(p.span_at(Lane::A1, 9), None);
7509 // Every lane covers the timeline exactly, gaps included.
7510 for l in p.lanes() {
7511 let spans = p.spans_from(l, 0);
7512 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7513 assert_eq!(spans[0].start, 0);
7514 }
7515 }
7516
7517 /// The timeline is emptiable: the last placement comes off like any other,
7518 /// the project holds "nothing on any lane" as a state, and one undo per
7519 /// gesture brings it back.
7520 #[test]
7521 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7522 let mut p = Project::single(FILE, 9);
7523 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7524 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7525 assert_eq!(p.timeline_frames(), 0);
7526 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7527 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7528 assert!(!p.lift(Lane::A1, 0), "index past the end");
7529 assert!(p.undo(), "and the last lift comes back");
7530 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7531 // A saved-and-loaded empty timeline is a project like any other, and it
7532 // still names the file its frame rate came from.
7533 assert!(p.lift(Lane::V1, 0));
7534 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7535 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7536 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7537 assert_eq!(back.timeline_frames(), 0);
7538 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7539 }
7540
7541 /// What a keyboard selection walks: one answer per lane, gaps included --
7542 /// the composite's own answer is one lane's and cannot say what the audio
7543 /// lane holds under the same playhead.
7544 #[test]
7545 fn lane_clip_at_answers_for_each_lane_separately() {
7546 let mut p = Project::single(FILE, 9);
7547 assert!(p.split(3), "both lanes split");
7548 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7549 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7550 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7551 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7552 // A gap on one lane leaves the other's clip selectable there.
7553 assert!(p.lift(Lane::A1, 0));
7554 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7555 assert_eq!(
7556 p.lane_clip_at(Lane::A1, 3),
7557 Some(0),
7558 "indices moved with it"
7559 );
7560 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7561 // A lane that is not there is not a panic.
7562 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7563 }
7564
7565 #[test]
7566 fn place_overwrites_only_its_own_lane() {
7567 let mut p = three();
7568 let audio_before = shape(&p)[1].clone();
7569 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7570 // is trimmed, nothing shifts.
7571 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7572 assert_eq!(
7573 shape(&p)[0],
7574 vec![
7575 clip(0, 0, 3, 0),
7576 clip(3, 3, 4, 0),
7577 clip(4, 100, 102, 0),
7578 clip(6, 6, 9, 0),
7579 ]
7580 );
7581 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7582 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7583
7584 // Placed inside one clip, it splits it in two.
7585 let mut p = Project::single(FILE, 9);
7586 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7587 assert_eq!(
7588 shape(&p)[0],
7589 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7590 );
7591 // ...and placed past the end it makes a gap, which is the whole point.
7592 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7593 assert_eq!(p.timeline_frames(), 22);
7594 assert_eq!(
7595 p.span_at(Lane::V1, 9),
7596 Some(Span {
7597 start: 9,
7598 len: 11,
7599 from: None,
7600 speed: Speed::NORMAL
7601 })
7602 );
7603 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7604 }
7605
7606 /// A file with sound let go over a further video track: both halves go down,
7607 /// on the same frames, and the audio row is added when the `+ V` button left
7608 /// the project without one. One undo takes the lane and both clips back.
7609 #[test]
7610 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7611 let mut p = three();
7612 let v2 = p.add_lane(LaneKind::Video);
7613 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7614
7615 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7616 let a2 = Lane::new(LaneKind::Audio, 1);
7617 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7618 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7619 assert_eq!(p.lane(v2)[0].start, 4);
7620 assert_eq!(p.lane(v2)[0].end(), 6);
7621 assert_eq!(
7622 p.lane(v2)[0].link,
7623 p.lane(a2)[0].link,
7624 "one take, not two placements"
7625 );
7626 assert!(p.lane(v2)[0].link.is_some());
7627 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7628 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7629
7630 // The pair overwrites its own two lanes and nothing else, exactly as a
7631 // one-lane place does.
7632 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7633 assert_eq!(p.lane(v2), p.lane(a2));
7634 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7635 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7636
7637 assert!(p.undo(), "one step for the second pair");
7638 assert_eq!(p.lane(v2).len(), 1);
7639 assert!(p.undo(), "one step for the first pair *and* its lane");
7640 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7641 assert!(p.lane(v2).is_empty());
7642
7643 // Refusals cost nothing: sound placed alone is `place`'s door.
7644 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7645 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7646 assert!(
7647 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7648 "a lane that is not there"
7649 );
7650 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7651 }
7652
7653 /// The drag between tracks: let go at the frames it already covers the clip
7654 /// keeps them, one undo takes it back, and every way it can be refused
7655 /// leaves the project untouched.
7656 #[test]
7657 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7658 let v2 = Lane::new(LaneKind::Video, 1);
7659 let mut p = three();
7660 assert_eq!(p.add_lane(LaneKind::Video), v2);
7661 let before = shape(&p);
7662
7663 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7664 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7665 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7666 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7667 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7668 // One snapshot: a single undo, and the lane list survives it.
7669 assert!(p.undo());
7670 assert_eq!(shape(&p), before);
7671
7672 // A lane that is not there, the lane and frame it is already at, an
7673 // index that is not there, and a move across kinds: all refused,
7674 // nothing changed.
7675 let history = p.history.len();
7676 for (from, idx, to, start) in [
7677 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7678 (Lane::V1, 1, Lane::V1, 3),
7679 (Lane::V1, 9, v2, 3),
7680 (Lane::V1, 1, Lane::A1, 3),
7681 (Lane::A1, 1, v2, 3),
7682 ] {
7683 assert!(
7684 !p.move_clip(from, idx, to, start),
7685 "{from:?} {idx} -> {to:?} at {start}"
7686 );
7687 }
7688 assert_eq!(shape(&p), before);
7689 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7690
7691 // Landing on another clip is refused rather than overwriting it: the
7692 // pointer named the lane, never the take already sitting there.
7693 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7694 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7695 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7696 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7697 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7698 }
7699
7700 /// The drag *along* a track, which is the one every other editor has: the
7701 /// clip lands on the frame the pointer let it go at, and stops dead against
7702 /// the neighbour rather than overwriting it.
7703 #[test]
7704 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7705 let sources = vec![Source::new(FILE, 0)];
7706 let lanes = vec![
7707 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7708 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7709 ];
7710 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7711 let before = shape(&p);
7712
7713 // Into the gap, exactly where it was let go -- nothing else moves.
7714 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7715 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7716 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7717 // Dragged past the clip in front of it: clamped to its wall, laid end
7718 // to end with it, never over it.
7719 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7720 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7721 // One undo per drag, and both of them together are the state it started
7722 // in -- the frames each clip plays never changed.
7723 assert!(p.undo() && p.undo());
7724 assert_eq!(shape(&p), before);
7725
7726 // A drop that changes nothing is a click, not an edit.
7727 let history = p.history.len();
7728 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7729 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7730 }
7731
7732 /// A drag carries the whole take: the sound half travels exactly as far as
7733 /// the picture does, and the tighter of their two walls stops both.
7734 #[test]
7735 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7736 let mut p = three();
7737 assert!(
7738 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7739 "room to the right"
7740 );
7741 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7742 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7743 // Something in the sound's way, and nothing at all in the picture's.
7744 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7745 let before = shape(&p);
7746
7747 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7748 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7749 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7750 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7751 assert!(p.undo());
7752 assert_eq!(shape(&p), before, "one undo for the whole take");
7753 }
7754
7755 /// The drag that does both at once -- another lane *and* another frame --
7756 /// which is what a pointer let go over a lane always names.
7757 #[test]
7758 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7759 let v2 = Lane::new(LaneKind::Video, 1);
7760 let mut p = three();
7761 assert_eq!(p.add_lane(LaneKind::Video), v2);
7762
7763 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7764 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7765 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7766 assert_eq!(
7767 p.lane(Lane::A1)[2].start,
7768 20,
7769 "its sound travelled the same distance"
7770 );
7771 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7772 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7773 }
7774
7775 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7776 /// [`three`] cuts up all nine of its frames.
7777 const SRC: &[u32] = &[9];
7778
7779 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7780 /// else on the lane moves, and every wall stops the edge rather than
7781 /// refusing the gesture.
7782 #[test]
7783 fn trimming_the_tail_stops_at_every_wall() {
7784 let mut p = three();
7785
7786 // Pulled in: a gap opens behind it and the clip after it stays put.
7787 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7788 assert_eq!(
7789 shape(&p)[0],
7790 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7791 );
7792 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7793 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7794
7795 // ...and back out, no further than the clip behind it.
7796 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7797 assert_eq!(
7798 shape(&p)[0][1],
7799 clip(3, 3, 5, 0),
7800 "stopped at the neighbour"
7801 );
7802 assert!(
7803 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7804 "already at the wall"
7805 );
7806
7807 // One frame of clip always survives, however far back the pointer went.
7808 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7809 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7810
7811 // The last clip has no neighbour, so what stops it is the file: nine
7812 // frames is nine frames.
7813 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7814 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7815 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7816 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7817 // A source nobody told us the length of may not grow at all -- an
7818 // out-point past the end of a file is a save that will not open again.
7819 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7820 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7821 }
7822
7823 /// The head pulled in takes the in-point with it -- what stays plays what it
7824 /// always played -- and stops at the source's own first frame.
7825 #[test]
7826 fn trimming_the_head_moves_the_in_point() {
7827 let mut p = three();
7828 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7829 assert_eq!(
7830 shape(&p)[0][0],
7831 clip(2, 2, 3, 0),
7832 "two frames off the front"
7833 );
7834 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7835 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7836 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7837 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7838 // One frame survives here too.
7839 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7840 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7841
7842 // A clip that does not begin at its source's first frame: its head goes
7843 // back to source frame 0 and not one frame further.
7844 let mut p = Project::single(FILE, 9);
7845 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7846 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7847 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7848 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7849 }
7850
7851 /// A clip whose in-point is *past* its own start -- what a ripple delete
7852 /// leaves, the piece in front of it gone and this one slid back to frame 0
7853 /// carrying the in-point the cut gave it. Its head has more source behind it
7854 /// than the timeline has room for, and the timeline's own first frame is the
7855 /// wall: asking is not an overflow, and the answer is 0.
7856 #[test]
7857 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
7858 let mut p = Project::single(FILE, 9);
7859 assert!(p.split(5));
7860 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
7861 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
7862
7863 assert_eq!(
7864 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
7865 Some((0, 3)),
7866 "back to frame 0 at most, and one frame of clip always survives"
7867 );
7868 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
7869 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7870 assert_eq!(
7871 shape(&p)[0],
7872 vec![clip(2, 7, 9, 0)],
7873 "the in-point followed"
7874 );
7875 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
7876 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
7877 }
7878
7879 /// A still is trimmed from its head exactly as it is from its tail: it has
7880 /// no earlier frame to walk an in-point back to, so the wall is the length
7881 /// the caller's table allows it, measured back from the tail. Measured from
7882 /// the in-point -- which a placed picture has at 0 -- its left edge could
7883 /// never be dragged outwards at all.
7884 #[test]
7885 fn a_stills_head_stretches_out_like_its_tail() {
7886 const STILL: &str = "/nonexistent/card.png";
7887 /// What a still is held to, as `PlaybackSession` fills the table in.
7888 const CAP: &[u32] = &[60];
7889
7890 let mut p = Project::single(STILL, 20);
7891 assert!(p.lift(Lane::A1, 0), "a picture is silent");
7892 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
7893 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
7894
7895 // A source with no entry in the table may not grow, here as at the tail.
7896 assert_eq!(
7897 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
7898 Some((100, 119)),
7899 "a length nobody told us buys no head room"
7900 );
7901 assert_eq!(
7902 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
7903 Some((60, 119)),
7904 "back to a whole cap's worth, one frame of clip surviving"
7905 );
7906 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
7907 assert_eq!(
7908 shape(&p)[0][0],
7909 clip(80, 0, 40, 0),
7910 "twenty frames longer, and still read from the source's first frame"
7911 );
7912 // Past the cap is clamped, exactly as the tail is -- not refused.
7913 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
7914 assert_eq!(
7915 shape(&p)[0][0],
7916 clip(60, 0, 60, 0),
7917 "a cap's worth, no more"
7918 );
7919 // ...and the clip in front is the nearer wall of the two: no head trim
7920 // may open an overlap.
7921 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
7922 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
7923 assert_eq!(
7924 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
7925 Some((85, 119)),
7926 "up to the neighbour's last frame and not over it"
7927 );
7928 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
7929 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
7930 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
7931 }
7932
7933 /// Linked halves trim as one: a link is one span on however many lanes, so
7934 /// the sound follows the picture's edge -- and the tightest wall of the two
7935 /// is what stops both.
7936 #[test]
7937 fn linked_halves_trim_together() {
7938 let mut p = three();
7939 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
7940 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
7941
7942 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
7943 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
7944 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
7945 assert!(
7946 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
7947 "either half drags it"
7948 );
7949 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
7950 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7951
7952 // Something in the way on the *audio* lane stops the picture's tail as
7953 // well: the group can only go as far as its tightest member.
7954 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
7955 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7956 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
7957 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
7958 links_are_consistent(&p.lanes).expect("still one span");
7959 }
7960
7961 /// A whole drag is one undo step -- the front-end commits once, at the
7962 /// release -- and an edge asked to stay where it is costs none at all.
7963 #[test]
7964 fn a_trim_is_one_undo_step() {
7965 let mut p = three();
7966 let before = shape(&p);
7967 let history = p.history.len();
7968
7969 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7970 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7971 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7972 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7973 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7974 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7975
7976 assert!(p.undo());
7977 assert_eq!(shape(&p), before, "both halves back, in one step");
7978 }
7979
7980 /// A moved half stays in its group: a link names a span, not a lane, so the
7981 /// picture on `V2` is still the same take as the sound under it on `A1`.
7982 #[test]
7983 fn move_clip_keeps_the_group() {
7984 let v2 = Lane::new(LaneKind::Video, 1);
7985 let mut p = three();
7986 p.add_lane(LaneKind::Video);
7987 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7988 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7989 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7990 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7991 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7992 assert_eq!(
7993 p.lane(v2)[0].start,
7994 p.lane(Lane::A1)[1].start,
7995 "and still covers the same span as its sound"
7996 );
7997 }
7998
7999 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
8000 /// head of a lane, between two clips, inside a clip, past the last one,
8001 /// and on a lane holding nothing at all.
8002 #[test]
8003 fn gap_at_finds_the_hole_a_frame_sits_in() {
8004 let mut p = Project::single(FILE, 1);
8005 let v = p.add_lane(LaneKind::Video);
8006 // Empty lane: nothing before and nothing after -- not a gap, since
8007 // there is nothing to ripple toward.
8008 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
8009
8010 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
8011 // Before the only clip: the gap runs from the timeline's own head.
8012 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
8013 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
8014 // Inside the clip: not a gap.
8015 assert_eq!(p.gap_at(v, 5), None);
8016 assert_eq!(p.gap_at(v, 7), None);
8017 // Past the only clip: the open end of the lane, not a gap -- there is
8018 // nothing after it to slide back.
8019 assert_eq!(p.gap_at(v, 8), None);
8020 assert_eq!(p.gap_at(v, 100), None);
8021
8022 assert!(p.place(v, 12, clip(12, 0, 2, 0)), "a second clip at [12,14)");
8023 // Between the two: the gap [8,12).
8024 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
8025 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
8026 assert_eq!(p.gap_at(v, 14), None, "still the open end");
8027
8028 assert!(
8029 p.place(v, 8, clip(8, 0, 4, 0)),
8030 "fills [8,12) exactly, meeting both neighbours"
8031 );
8032 assert_eq!(p.gap_at(v, 8), None, "adjacent clips leave no frame to name a gap");
8033 assert_eq!(p.gap_at(v, 11), None);
8034 }
8035
8036 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
8037 /// menu named: the clip after the gap slides back on that lane, a clip on
8038 /// another lane at the very same frame range does not move, and the whole
8039 /// close is one press of undo.
8040 #[test]
8041 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
8042 let mut p = Project::single(FILE, 1);
8043 let v = p.add_lane(LaneKind::Video);
8044 let a = p.add_lane(LaneKind::Audio);
8045 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
8046 assert!(
8047 p.place(a, 0, clip(0, 0, 3, 0)),
8048 "A clip at [0,3) -- outside the video lane's gap and this scope"
8049 );
8050 let before = shape(&p);
8051 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
8052 assert_eq!((start, len), (0, 5));
8053 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
8054 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
8055 assert_eq!(p.lane(a)[0].start, 0, "the untouched lane's clip did not move");
8056 assert!(p.undo(), "one press undoes the whole close");
8057 assert_eq!(shape(&p), before, "back to exactly where it was");
8058 }
8059
8060 /// A clip carrying an explicit link id -- what a
8061 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
8062 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
8063 /// already builds inline.
8064 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
8065 Clip {
8066 fade_in: 0,
8067 fade_out: 0,
8068 transition_out: 0,
8069 visualizer: 0,
8070 viz_paint: 0,
8071 start,
8072 in_frame,
8073 out_frame,
8074 source: 0,
8075 link: Some(link),
8076 eq: None,
8077 color: None,
8078 transform: None,
8079 fit: FitPolicy::default(),
8080 speed: Speed::NORMAL,
8081 }
8082 }
8083
8084 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
8085 /// bordered by a linked take whose `A1` half is empty across the very
8086 /// same stretch widens the scope to both lanes, so the ripple carries the
8087 /// take rather than tearing it -- and one undo puts both halves back.
8088 #[test]
8089 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
8090 let sources = vec![Source::new(FILE, 0)];
8091 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8092 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8093 let mut p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8094 .expect("valid parts");
8095 let before = shape(&p);
8096 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8097 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 2)), "the same stretch is empty on A1 too");
8098
8099 let scope = p
8100 .gap_take_scope(Lane::V1, 3, 2)
8101 .expect("a matching gap on both halves widens the scope");
8102 assert_eq!(scope.len(), 2, "the take's other lane joins");
8103 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
8104
8105 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
8106 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
8107 assert_eq!(p.lane(Lane::A1)[1].start, 3, "A1's far half rode along, in sync");
8108 assert!(p.undo(), "one press undoes the whole close");
8109 assert_eq!(shape(&p), before, "back to exactly where it was");
8110 }
8111
8112 /// The real design question: a take whose gap is not the *same size* on
8113 /// both lanes cannot ripple by one number without pulling a lane's clip
8114 /// out from under the other's sync -- refused by name, with the frame
8115 /// naming which lane is out of step, rather than silently taking real
8116 /// media off the shorter side.
8117 #[test]
8118 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
8119 let sources = vec![Source::new(FILE, 0)];
8120 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8121 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
8122 // shorter than V1's [3,5) -- a legal offset-preserving group, and
8123 // still one take.
8124 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
8125 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8126 .expect("valid parts");
8127 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8128 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
8129
8130 let err = p
8131 .gap_take_scope(Lane::V1, 3, 2)
8132 .expect_err("a mismatched gap cannot ripple by one number")
8133 .to_string();
8134 assert!(err.contains("A1"), "{err}");
8135 assert!(err.contains("out of sync"), "{err}");
8136 }
8137
8138 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
8139 /// there -- cannot close without cutting that audio out from under
8140 /// nothing asked to touch it: refused, not widened silently past.
8141 #[test]
8142 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
8143 let sources = vec![Source::new(FILE, 0)];
8144 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
8145 // A1 plays through the whole span as one continuous clip, sharing
8146 // V1's first-half link: nothing empty at frame 3 there at all.
8147 let audio = vec![linked(0, 0, 9, 1)];
8148 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8149 .expect("valid parts");
8150 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
8151 assert_eq!(p.gap_at(Lane::A1, 3), None, "A1 plays through, no gap there");
8152
8153 let err = p
8154 .gap_take_scope(Lane::V1, 3, 2)
8155 .expect_err("a solid partner cannot ripple with the gap")
8156 .to_string();
8157 assert!(err.contains("A1"), "{err}");
8158 assert!(err.contains("detach"), "{err}");
8159 }
8160
8161
8162 /// The sweep is the single-gap close repeated on one lane, but measured once
8163 /// and applied from the right. The differing gap lengths here expose a
8164 /// front-to-back bug: the last clip would be cut against a stale frame after
8165 /// the first gap shifted it.
8166 #[test]
8167 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
8168 let mut p = Project::single(FILE, 1);
8169 let v = p.add_lane(LaneKind::Video);
8170 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
8171 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
8172 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
8173 let before = shape(&p);
8174
8175 assert_eq!(p.gap_count(v), 3);
8176 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
8177 assert_eq!(report.closed, 3);
8178 assert!(report.skipped.is_empty());
8179 assert_eq!(
8180 p.lane(v),
8181 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
8182 "all gaps closed without eating source frames"
8183 );
8184 assert!(p.undo(), "one undo for the whole sweep");
8185 assert_eq!(shape(&p), before);
8186 }
8187
8188 /// Empty, already-contiguous and tail-only lanes are not controls that do
8189 /// work. A single clip with a head gap does close, because there is a real
8190 /// placement to ripple back.
8191 #[test]
8192 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
8193 let mut p = Project::single(FILE, 9);
8194 let v = p.add_lane(LaneKind::Video);
8195 let history = p.history.len();
8196 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
8197 assert_eq!(report, GapSweep::default(), "an empty lane has no bounded gap");
8198 assert_eq!(p.history.len(), history, "no undo step for a no-op");
8199
8200 let mut p = Project::single(FILE, 9);
8201 let v = p.add_lane(LaneKind::Video);
8202 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
8203 let before = shape(&p);
8204 let report = p.close_all_gaps_on_lane(v).expect("single clip lane exists");
8205 assert_eq!(report.closed, 1, "the head gap closes");
8206 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8207 assert!(p.undo());
8208 assert_eq!(shape(&p), before);
8209
8210 let mut p = Project::single(FILE, 9);
8211 let history = p.history.len();
8212 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8213 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
8214 assert_eq!(p.history.len(), history);
8215
8216 let mut p = Project::single(FILE, 9);
8217 let v = p.add_lane(LaneKind::Video);
8218 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
8219 let history = p.history.len();
8220 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
8221 assert_eq!(report, GapSweep::default(), "the open-ended tail is not closed");
8222 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
8223 assert_eq!(p.history.len(), history);
8224 }
8225
8226 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
8227 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
8228 /// while V1's [6,9) has only [6,8) empty on A1.
8229 #[test]
8230 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
8231 let sources = vec![Source::new(FILE, 0)];
8232 let video = vec![
8233 linked(0, 0, 2, 1),
8234 linked(4, 4, 6, 2),
8235 clip(9, 9, 11, 0),
8236 ];
8237 let audio = vec![
8238 linked(0, 0, 2, 1),
8239 linked(4, 4, 6, 2),
8240 clip(8, 8, 11, 0),
8241 ];
8242 let mut p =
8243 Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
8244 .expect("valid parts");
8245 let before = shape(&p);
8246
8247 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
8248 assert_eq!(report.closed, 1);
8249 assert_eq!(report.skipped.len(), 1);
8250 assert_eq!(report.skipped[0].start, 6);
8251 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
8252 assert!(report.skipped[0].reason.contains("out of sync"), "{report:?}");
8253
8254 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
8255 assert_eq!(p.lane(Lane::A1)[1].start, 2, "and its other half stayed in sync");
8256 assert_eq!(p.lane(Lane::V1)[2].start, 7, "the skipped later gap remains");
8257 assert_eq!(p.lane(Lane::A1)[2].start, 6, "A1's shorter gap remains shorter");
8258 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
8259 assert!(p.undo(), "one undo restores every closed gap");
8260 assert_eq!(shape(&p), before);
8261 }
8262
8263 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
8264 /// their own caption storage: head gaps and gaps between cues count, an
8265 /// empty lane and the tail after the last cue do not.
8266 #[test]
8267 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
8268 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8269 let s = p.add_lane(LaneKind::Subtitle);
8270 assert_eq!(p.gap_at(s, 0), None, "an empty subtitle lane has nothing to close");
8271
8272 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8273 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
8274 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
8275 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
8276 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
8277
8278 p.place_sub(s, 12, caption(0, 2)).expect("second cue at [12,14)");
8279 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
8280 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
8281 assert_eq!(p.gap_at(s, 14), None, "tail after the last cue is still open-ended");
8282 }
8283
8284 /// Closing a caption gap ripples the subtitle lane only. It is not a media
8285 /// take close, so the video and audio lanes keep their frame positions.
8286 #[test]
8287 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
8288 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
8289 let s = p.add_lane(LaneKind::Subtitle);
8290 p.place_sub(s, 5, caption(0, 3)).expect("single cue at [5,8)");
8291 let before_clips = shape(&p);
8292 let before_subs = p.sub_lane(s).to_vec();
8293
8294 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
8295 assert_eq!((start, len), (0, 5));
8296 p.cut_regions(&[(start, len)], &[s]).expect("caption lane gap closes");
8297
8298 assert_eq!(shape(&p), before_clips, "media lanes did not move");
8299 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
8300 assert!(p.undo(), "one undo restores the caption close");
8301 assert_eq!(shape(&p), before_clips);
8302 assert_eq!(p.sub_lane(s), before_subs);
8303 }
8304
8305 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
8306 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
8307 /// history entry for empty or already-contiguous lanes.
8308 #[test]
8309 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
8310 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8311 let s = p.add_lane(LaneKind::Subtitle);
8312 let history = p.history.len();
8313 let report = p.close_all_gaps_on_lane(s).expect("empty subtitle lane exists");
8314 assert_eq!(report, GapSweep::default(), "empty subtitle lane has no bounded gap");
8315 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
8316
8317 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
8318 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
8319 p.place_sub(s, 14, caption(0, 1)).expect("middle gap [9,14), tail after 15");
8320 let before = p.sub_lane(s).to_vec();
8321
8322 assert_eq!(p.gap_count(s), 3);
8323 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8324 assert_eq!(report.closed, 3);
8325 assert!(report.skipped.is_empty());
8326 assert_eq!(
8327 p.sub_lane(s),
8328 &[caption(0, 2), caption(2, 2), caption(4, 1)],
8329 "all bounded caption gaps closed without touching windows"
8330 );
8331 assert!(p.undo(), "one undo restores every caption gap");
8332 assert_eq!(p.sub_lane(s), before);
8333
8334 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
8335 let s = p.add_lane(LaneKind::Subtitle);
8336 p.place_sub(s, 0, caption(0, 3)).expect("contiguous at the head");
8337 let history = p.history.len();
8338 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
8339 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
8340 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
8341 assert_eq!(p.history.len(), history);
8342 }
8343
8344 #[test]
8345 fn ripple_delete_spans_partial_clips() {
8346 let mut p = three();
8347 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
8348 assert!(p.ripple_delete(2, 4));
8349 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
8350 assert_eq!(shape(&p)[1], shape(&p)[0]);
8351 assert_eq!(p.timeline_frames(), 5);
8352 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
8353 assert!(p.undo());
8354 assert_eq!(shape(&p), shape(&three()));
8355 // One that takes everything is a delete like any other: the timeline
8356 // empties, and the undo it cost brings it back whole.
8357 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
8358 assert_eq!(p.timeline_frames(), 0);
8359 assert!(
8360 !p.ripple_delete(0, 100),
8361 "and a delete with nothing left to take is not an undo step"
8362 );
8363 assert!(p.undo());
8364 assert_eq!(shape(&p), shape(&three()));
8365 }
8366
8367 #[test]
8368 fn undo_restores_exactly() {
8369 let mut p = three();
8370 let after_splits = shape(&p);
8371 assert!(p.delete(1));
8372 assert!(p.undo());
8373 assert_eq!(shape(&p), after_splits);
8374
8375 // walk all the way back through both splits, then run dry
8376 assert!(p.undo());
8377 assert_eq!(p.clips().len(), 2);
8378 assert!(p.undo());
8379 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8380 assert!(!p.undo(), "empty history");
8381 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
8382 }
8383
8384 #[test]
8385 fn redo_restores_exactly() {
8386 let mut p = three();
8387 assert!(p.delete(1));
8388 let after_delete = p.parts();
8389 assert!(p.undo());
8390 assert!(p.redo());
8391 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
8392 assert!(!p.redo(), "empty redo stack");
8393 }
8394
8395 #[test]
8396 fn edit_after_undo_empties_redo() {
8397 let mut p = three();
8398 assert!(p.delete(1));
8399 assert!(p.undo());
8400 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
8401 assert!(p.split(1), "a fresh edit");
8402 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
8403 assert!(!p.redo(), "so redo has nothing left");
8404 }
8405
8406 #[test]
8407 fn redo_on_empty_stack_is_false() {
8408 let mut p = three();
8409 assert!(!p.redo(), "nothing has been undone yet");
8410 }
8411
8412 /// Past the cap the *oldest* step goes, so a long session undoes exactly
8413 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
8414 #[test]
8415 fn history_stops_at_the_cap() {
8416 let mut p = Project::single(FILE, 400);
8417 for frame in 1..=150 {
8418 assert!(p.split(frame), "split {frame} is an edit");
8419 }
8420 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
8421 for step in 0..HISTORY_CAP {
8422 assert!(p.undo(), "undo {step} is inside the cap");
8423 }
8424 assert!(!p.undo(), "and the 101st has nothing left to take");
8425 // 100 undos off 150 splits is the timeline after the 50th: the older
8426 // steps were dropped, not the newer ones.
8427 assert_eq!(p.clips().len(), 51);
8428 }
8429
8430 /// Undo/redo by hand across a split must never merge two takes into one
8431 /// group by reusing an id.
8432 #[test]
8433 fn group_ids_are_never_reused() {
8434 let mut p = Project::single(FILE, 9);
8435 assert!(p.split(3));
8436 let first = p.clips()[1].link;
8437 assert!(p.undo());
8438 assert!(p.split(5));
8439 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
8440 }
8441
8442 #[test]
8443 fn segments_from_reads_the_audio_lane() {
8444 let p = three();
8445 // mid-clip: partial first segment, whole clips after it
8446 assert_eq!(
8447 p.segments_from(4, FPS),
8448 vec![
8449 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8450 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8451 ]
8452 );
8453 // on a boundary: nothing partial
8454 assert_eq!(
8455 p.segments_from(3, FPS),
8456 vec![
8457 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
8458 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
8459 ]
8460 );
8461 // from the top: one entry per clip
8462 assert_eq!(p.segments_from(0, FPS).len(), 3);
8463 // last clip only
8464 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
8465 // past the end / unusable fps
8466 assert!(p.segments_from(9, FPS).is_empty());
8467 assert!(p.segments_from(0, 0.0).is_empty());
8468 assert!(p.segments_from(0, f64::NAN).is_empty());
8469 }
8470
8471 #[test]
8472 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
8473 let mut p = three();
8474 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
8475 assert_eq!(
8476 p.segments_from(0, FPS),
8477 vec![
8478 (Some(0), 0.0, 3.0 / 30.0),
8479 (None, 0.0, 2.0 / 30.0),
8480 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8481 ]
8482 );
8483 // The list still covers exactly the timeline: that is what stops the
8484 // master clock stalling at the hole.
8485 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8486 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
8487 // Starting inside the gap trims the silence, not the clip after it.
8488 assert_eq!(
8489 p.segments_from(4, FPS),
8490 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
8491 );
8492 // ...and a lane that is nothing but gap is a run of silence.
8493 assert!(p.lift(Lane::A1, 0));
8494 assert!(p.lift(Lane::A1, 0));
8495 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
8496 }
8497
8498 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
8499 /// of source 0 then [0,4) of source 1.
8500 fn two_sources() -> Project {
8501 let mut p = three();
8502 let s = p.import(FILE2, 0);
8503 assert_eq!(s, 1);
8504 assert!(p.append_clip(s, 4));
8505 p
8506 }
8507
8508 #[test]
8509 fn import_dedups_and_appends() {
8510 let mut p = Project::single(FILE, 9);
8511 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
8512 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
8513 assert_eq!(p.import(FILE2, 0), 1);
8514 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
8515 // ...but the same file on another audio stream is another source: it is
8516 // what a clip names, and a clip plays exactly one stream.
8517 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
8518 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
8519 assert_eq!(p.sources()[2].audio_stream, 1);
8520 assert!(p.append_clip(2, 4), "a stream entry is placeable");
8521 assert!(p.undo());
8522 assert_eq!(p.sources().len(), 3);
8523 assert!(!p.append_clip(3, 5), "unknown source index");
8524 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
8525
8526 // Two spellings of one real file are one source: this is the case the
8527 // raw-path comparison above would get wrong.
8528 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
8529 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
8530 let mut p = Project::single(here, 9);
8531 assert_eq!(p.import(detour, 0), 0);
8532 assert_eq!(p.sources().len(), 1);
8533 }
8534
8535 #[test]
8536 fn append_clip_is_one_undo_step() {
8537 let mut p = two_sources();
8538 assert_eq!(p.timeline_frames(), 13);
8539 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
8540 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
8541 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
8542 assert!(p.undo());
8543 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
8544 assert_eq!(
8545 p.sources().len(),
8546 2,
8547 "the orphan source entry stays -- indexes are forever"
8548 );
8549 // ...and it is still usable, so a redo-by-hand costs no reimport.
8550 assert!(p.append_clip(1, 0));
8551 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
8552 }
8553
8554 #[test]
8555 fn edits_carry_the_source_along() {
8556 let mut p = two_sources();
8557 // A split inside the second source splits into two source-1 clips.
8558 assert!(p.split(11));
8559 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
8560 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
8561
8562 // A source-1 clip pasted into source-0 territory keeps its file, and so
8563 // does the source-0 half that got split off around it.
8564 let copied = p.clips()[4];
8565 assert!(p.paste(1, copied));
8566 assert_eq!(p.clips()[1].source, 1);
8567 assert_eq!(p.clips()[1].in_frame, 2);
8568 assert_eq!(p.clips()[2].source, 0);
8569 assert!(p.undo());
8570 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
8571 }
8572
8573 #[test]
8574 fn segments_from_names_the_source() {
8575 let p = two_sources();
8576 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
8577 assert_eq!(
8578 p.segments_from(4, FPS),
8579 vec![
8580 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8581 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8582 (Some(1), 0.0, 4.0 / 30.0),
8583 ]
8584 );
8585 // Mid-clip in source 1: only that source is left.
8586 assert_eq!(
8587 p.segments_from(10, FPS),
8588 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
8589 );
8590 assert!(p.segments_from(13, FPS).is_empty());
8591 // Segments still cover exactly the timeline across the join.
8592 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8593 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
8594 }
8595
8596 #[test]
8597 fn segments_follow_deletes_and_fps() {
8598 let mut p = three();
8599 assert!(p.delete(0));
8600 // source seconds, not timeline: deleting the head does not shift them
8601 let segs = p.segments_from(0, 25.0);
8602 assert_eq!(
8603 segs,
8604 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
8605 );
8606 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
8607 assert!(
8608 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
8609 "segments must cover exactly the timeline: {played}"
8610 );
8611 }
8612
8613 #[test]
8614 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
8615 // Import a second file, undo it: source 1 is now an orphan.
8616 let mut p = two_sources();
8617 assert!(p.undo());
8618 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8619 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
8620 assert!(eq.is_empty(), "and a project with no equalizer writes none");
8621 assert!(color.is_empty(), "nor a colour it never graded with");
8622 assert_eq!(
8623 lanes,
8624 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
8625 "the clips are untouched"
8626 );
8627
8628 // Three sources where only the middle one is orphaned: the survivors
8629 // renumber, and the clips follow.
8630 let mut p = Project::single(FILE, 9);
8631 assert_eq!(p.import(FILE2, 0), 1);
8632 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
8633 assert!(p.append_clip(2, 4));
8634 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8635 assert_eq!(
8636 sources,
8637 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
8638 );
8639 assert_eq!(
8640 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
8641 [0, 1]
8642 );
8643 // ...and what comes out is loadable, with the same timeline.
8644 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8645 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
8646 assert_eq!(reloaded.sources().len(), 2);
8647 }
8648
8649 /// Taking a file out of the library: refused by name -- lanes and counts --
8650 /// while a clip still plays from it, and once nothing does, the entry goes
8651 /// and every clip that indexed past it is renumbered onto the short list.
8652 #[test]
8653 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
8654 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
8655 // plus a second stream of FILE as source 2 with a take of its own.
8656 let mut p = two_sources();
8657 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
8658 assert!(p.append_clip(2, 4));
8659
8660 let refusal = p
8661 .remove_source(1)
8662 .expect_err("a source with clips on it cannot go")
8663 .to_string();
8664 assert!(refusal.contains(FILE2), "names the file: {refusal}");
8665 assert!(
8666 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
8667 "names the lanes holding it: {refusal}"
8668 );
8669 assert!(refusal.contains("still plays"), "{refusal}");
8670 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
8671 assert_eq!(shape(&p)[0][3].source, 1);
8672
8673 // Delete FILE2's take -- the whole span, on every lane -- and the entry
8674 // is free to go. Source 2's clips become source 1's.
8675 assert!(p.delete_in(Lane::V1, 3));
8676 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
8677 p.remove_source(1).expect("nothing plays FILE2 any more");
8678 assert_eq!(
8679 p.sources(),
8680 [Source::new(FILE, 0), Source::new(FILE, 1)],
8681 "the middle entry is gone"
8682 );
8683 assert_eq!(
8684 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
8685 [0, 0, 0, 1],
8686 "the clips past it renumbered"
8687 );
8688 assert_eq!(
8689 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
8690 [0, 0, 0, 1],
8691 "on every lane"
8692 );
8693 // What is left is a project that still loads, which is the whole point
8694 // of renumbering rather than leaving a hole.
8695 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8696 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8697 }
8698
8699 /// The two edges of a removal: it retires the undo stack (the corner-cut on
8700 /// [`Project::remove_source`]), and the last entry goes like any other
8701 /// once nothing plays it -- a project may name no file at all.
8702 #[test]
8703 fn remove_source_retires_undo_and_empties_the_library() {
8704 let mut p = two_sources();
8705 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
8706 assert!(!p.history.is_empty(), "there is something to undo");
8707 p.remove_source(1).expect("nothing plays FILE2");
8708 assert!(
8709 p.history.is_empty(),
8710 "a snapshot naming the removed source must not survive it"
8711 );
8712 assert!(!p.undo(), "and so there is nothing left to undo");
8713
8714 // The last file standing is held to the one rule every row is -- what
8715 // plays cannot go -- and to no other.
8716 assert_eq!(p.sources().len(), 1);
8717 let refusal = p
8718 .remove_source(0)
8719 .expect_err("its clips are still on the lanes")
8720 .to_string();
8721 assert!(refusal.contains("still plays"), "{refusal}");
8722 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
8723 while p.delete_in(Lane::V1, 0) {}
8724 p.remove_source(0)
8725 .expect("the last row goes like any other");
8726 assert!(
8727 p.sources().is_empty(),
8728 "a project may name no file at all: an empty library over an empty timeline"
8729 );
8730 assert_eq!(p.timeline_frames(), 0);
8731 assert!(
8732 p.remove_source(0).is_err(),
8733 "and an index that is not there is refused, not panicked on"
8734 );
8735 }
8736
8737 /// A clip's equalizer is the clip's: it survives every edit that copies a
8738 /// placement, and it comes back with an undo.
8739 #[test]
8740 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
8741 let mut p = three();
8742 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
8743 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
8744 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8745 assert!(
8746 p.eq_of(Lane::V1, 0).is_none(),
8747 "one clip, not the lane above"
8748 );
8749
8750 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
8751 assert!(p.split(1));
8752 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8753 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
8754 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
8755
8756 // A clipboard copy carries it -- onto another lane, at that.
8757 let copied = p.lane(Lane::A1)[1];
8758 assert!(p.place(Lane::V1, 20, copied));
8759 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
8760 assert!(p.undo());
8761 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
8762
8763 // ...and a change to one is one undo step, in both directions.
8764 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
8765 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
8766 assert!(p.undo());
8767 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8768 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
8769 assert!(p.eq_of(Lane::A1, 0).is_none());
8770 assert!(p.undo());
8771 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8772
8773 // Two refusals, neither of which costs an undo step.
8774 let mut nan = band_at(1);
8775 nan.bands[0].q = f32::INFINITY;
8776 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
8777 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
8778 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8779 assert!(p.undo());
8780 assert_eq!(
8781 p.lane(Lane::A1).len(),
8782 3,
8783 "one step back is before the split"
8784 );
8785 assert!(p.undo());
8786 assert!(
8787 p.eq_of(Lane::A1, 0).is_none(),
8788 "and the next is before the setting: the refusals pushed none"
8789 );
8790 }
8791
8792 /// The table is append-only within a session, exactly as the sources are, so
8793 /// an undone setting is still in it -- and a save is where it goes.
8794 #[test]
8795 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
8796 let mut p = three();
8797 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
8798 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
8799 assert!(p.undo(), "back to the first setting");
8800 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
8801
8802 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8803 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
8804 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
8805 assert_eq!(lanes[0].1[1].eq, None);
8806
8807 // One curve on three clips is one entry: settings that are equal share.
8808 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
8809 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
8810 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8811 assert_eq!(eq.len(), 1, "equal settings share their entry");
8812 assert_eq!(lanes[1].1[2].eq, Some(0));
8813 reloads(&p, "an equalizer that outlived an undo");
8814 }
8815
8816 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8817 /// grade is the clip's, through every edit that copies a placement.
8818 #[test]
8819 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
8820 let mut p = three();
8821 assert!(
8822 p.color_of(Lane::V1, 0).is_none(),
8823 "a fresh clip is ungraded"
8824 );
8825 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8826 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8827 assert!(
8828 p.color_of(Lane::A1, 0).is_none(),
8829 "one clip, not the lane below"
8830 );
8831 assert!(
8832 p.eq_of(Lane::V1, 0).is_none(),
8833 "and a grade is not an equalizer"
8834 );
8835
8836 // Cutting a graded clip must not grade half of it: both halves inherit.
8837 assert!(p.split(1));
8838 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8839 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
8840 assert!(
8841 p.color_of(Lane::V1, 2).is_none(),
8842 "the clip after it is ungraded"
8843 );
8844
8845 // A clipboard copy carries it -- onto another lane, at that.
8846 let copied = p.lane(Lane::V1)[1];
8847 assert!(p.place(Lane::A1, 20, copied));
8848 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
8849 assert!(p.undo());
8850 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8851
8852 // ...and a change to one is one undo step, in both directions.
8853 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
8854 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
8855 assert!(p.undo());
8856 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8857 assert!(
8858 p.set_color(Lane::V1, 0, None),
8859 "and taking it off is an edit"
8860 );
8861 assert!(p.color_of(Lane::V1, 0).is_none());
8862 assert!(p.undo());
8863 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8864
8865 // Two refusals, neither of which costs an undo step.
8866 let nan = ColorParams {
8867 contrast: f32::NAN,
8868 ..grade_at(1)
8869 };
8870 assert!(
8871 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
8872 "no clip there"
8873 );
8874 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
8875 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8876 assert!(p.undo());
8877 assert_eq!(
8878 p.lane(Lane::V1).len(),
8879 3,
8880 "one step back is before the split"
8881 );
8882 assert!(p.undo());
8883 assert!(
8884 p.color_of(Lane::V1, 0).is_none(),
8885 "and the next is before the grade: the refusals pushed none"
8886 );
8887 }
8888
8889 /// A slider drag is one gesture: the press snapshots, every sample after it
8890 /// only regrades, and the single undo lands on what the clip was *before*
8891 /// the hand touched it -- not one step back down the drag.
8892 #[test]
8893 fn a_whole_colour_drag_undoes_in_one_step() {
8894 let mut p = three();
8895 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
8896 for n in 2..=8 {
8897 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
8898 }
8899 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
8900 assert!(p.undo());
8901 assert!(
8902 p.color_of(Lane::V1, 0).is_none(),
8903 "one undo is the whole gesture, back to ungraded"
8904 );
8905
8906 // The live write refuses what the snapshotting one refuses, and a
8907 // refusal still costs no history either way.
8908 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
8909 assert!(!p.set_color_live(
8910 Lane::V1,
8911 0,
8912 Some(ColorParams {
8913 contrast: f32::NAN,
8914 ..grade_at(1)
8915 })
8916 ));
8917 assert!(p.undo());
8918 assert_eq!(
8919 p.lane(Lane::V1).len(),
8920 2,
8921 "the next step back is the split before the drag: no sample pushed one"
8922 );
8923 }
8924
8925 /// A drag across the colour wheel is one gesture -- the look's twin of
8926 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
8927 /// sample after it only repaints, and the single undo lands on the look
8928 /// the clip had *before* the hand touched it. The committing setter is
8929 /// still exactly one step, refusals included.
8930 #[test]
8931 fn a_whole_look_drag_undoes_in_one_step() {
8932 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
8933 let mut p = three();
8934 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
8935 for hue in 2..=8u8 {
8936 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
8937 }
8938 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
8939 assert!(p.undo());
8940 assert_eq!(
8941 p.lane(Lane::V1)[0].viz_paint,
8942 0,
8943 "one undo is the whole gesture, back to the default look"
8944 );
8945
8946 // The live write refuses an index that is not there -- and a refusal
8947 // costs no history -- while one committing write is one step back.
8948 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
8949 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
8950 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
8951 assert!(p.undo());
8952 assert_eq!(
8953 p.lane(Lane::V1)[0].viz_paint,
8954 0,
8955 "the committing setter is one undo step, no more"
8956 );
8957 }
8958
8959 /// The colour table is append-only within a session, exactly as the eq one
8960 /// is -- and a save is where an undone grade goes.
8961 #[test]
8962 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
8963 let mut p = three();
8964 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
8965 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8966 assert!(p.undo(), "back to the first grade");
8967 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
8968
8969 let (_, lanes, _, color, _) = p.without_orphan_sources();
8970 assert_eq!(
8971 color,
8972 vec![grade_at(1)],
8973 "what nothing plays is not written"
8974 );
8975 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
8976 assert_eq!(lanes[0].1[1].color, None);
8977
8978 // One grade on three clips is one entry: settings that are equal share.
8979 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
8980 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
8981 let (_, lanes, _, color, _) = p.without_orphan_sources();
8982 assert_eq!(color.len(), 1, "equal grades share their entry");
8983 assert_eq!(lanes[1].1[2].color, Some(0));
8984 reloads(&p, "a colour that outlived an undo");
8985
8986 // An equalizer and a grade on one clip are two independent tables.
8987 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
8988 let (_, lanes, eq, color, _) = p.without_orphan_sources();
8989 assert_eq!((eq.len(), color.len()), (1, 1));
8990 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
8991 }
8992
8993 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8994 /// placement is the clip's, through every edit that copies one.
8995 #[test]
8996 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
8997 let mut p = three();
8998 assert!(
8999 p.transform_of(Lane::V1, 0).is_none(),
9000 "a fresh clip is untransformed"
9001 );
9002 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9003 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9004 assert!(
9005 p.transform_of(Lane::A1, 0).is_none(),
9006 "one clip, not the lane below"
9007 );
9008 assert!(
9009 p.color_of(Lane::V1, 0).is_none(),
9010 "and a placement is not a grade"
9011 );
9012
9013 // Cutting a transformed clip must not transform half of it: both
9014 // halves inherit.
9015 assert!(p.split(1));
9016 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9017 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
9018 assert!(
9019 p.transform_of(Lane::V1, 2).is_none(),
9020 "the clip after it is untransformed"
9021 );
9022
9023 // A clipboard copy carries it -- onto another lane, at that.
9024 let copied = p.lane(Lane::V1)[1];
9025 assert!(p.place(Lane::A1, 20, copied));
9026 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
9027 assert!(p.undo());
9028 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
9029
9030 // ...and a change to one is one undo step, in both directions.
9031 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
9032 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
9033 assert!(p.undo());
9034 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9035 assert!(
9036 p.set_transform(Lane::V1, 0, None),
9037 "and taking it off is an edit"
9038 );
9039 assert!(p.transform_of(Lane::V1, 0).is_none());
9040 assert!(p.undo());
9041 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9042
9043 // Two refusals, neither of which costs an undo step.
9044 let nan = TransformParams {
9045 scale: f32::NAN,
9046 ..transform_at(1)
9047 };
9048 assert!(
9049 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
9050 "no clip there"
9051 );
9052 assert!(
9053 !p.set_transform(Lane::V1, 0, Some(nan)),
9054 "not a finite value"
9055 );
9056 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
9057 assert!(p.undo());
9058 assert_eq!(
9059 p.lane(Lane::V1).len(),
9060 3,
9061 "one step back is before the split"
9062 );
9063 assert!(p.undo());
9064 assert!(
9065 p.transform_of(Lane::V1, 0).is_none(),
9066 "and the next is before the placement: the refusals pushed none"
9067 );
9068 }
9069
9070 /// The transform table is append-only within a session, exactly as the eq
9071 /// and colour ones are -- and a save is where an undone placement goes.
9072 #[test]
9073 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
9074 let mut p = three();
9075 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
9076 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
9077 assert!(p.undo(), "back to the first placement");
9078 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
9079
9080 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9081 assert_eq!(
9082 transform,
9083 vec![transform_at(1)],
9084 "what nothing plays is not written"
9085 );
9086 assert_eq!(
9087 lanes[0].1[0].transform,
9088 Some(0),
9089 "and the survivor renumbers"
9090 );
9091 assert_eq!(lanes[0].1[1].transform, None);
9092
9093 // One placement on three clips is one entry: settings that are equal
9094 // share.
9095 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
9096 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
9097 let (_, lanes, _, _, transform) = p.without_orphan_sources();
9098 assert_eq!(transform.len(), 1, "equal placements share their entry");
9099 assert_eq!(lanes[1].1[2].transform, Some(0));
9100 reloads(&p, "a transform that outlived an undo");
9101
9102 // A grade and a placement on one clip are two independent tables.
9103 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
9104 let (_, lanes, _, color, transform) = p.without_orphan_sources();
9105 assert_eq!((color.len(), transform.len()), (1, 1));
9106 assert_eq!(
9107 (lanes[0].1[0].color, lanes[0].1[0].transform),
9108 (Some(0), Some(0))
9109 );
9110 }
9111
9112 /// Not a claim about correctness but about cost: a clip is copied on every
9113 /// paste, every undo snapshot and every lane clone, so its size is worth
9114 /// knowing. The eq index fit the padding a `Copy` clip already had; the
9115 /// colour one did not, and the struct grew a word. The transform index is
9116 /// a third `Option<u16>`, and it fits the padding the fit policy and the
9117 /// transition byte already left behind, so the struct did not grow again.
9118 /// The packed visualizer look is a `u64` -- the strand colour has bytes
9119 /// above the clip's own four -- and nothing left in the struct is wide
9120 /// enough to hold it, so it grew a word again.
9121 #[test]
9122 fn a_clip_is_still_a_small_copy() {
9123 assert_eq!(
9124 std::mem::size_of::<Clip>(),
9125 64,
9126 "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"
9127 );
9128 }
9129
9130 #[test]
9131 fn from_parts_has_no_history_and_checks_the_invariants() {
9132 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
9133 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
9134 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
9135 .expect("valid parts");
9136 assert_eq!(p.clips(), three().clips());
9137 assert!(!p.undo(), "a loaded project has nothing to undo");
9138 assert!(p.split(4), "...and is editable from there");
9139 assert!(p.undo());
9140
9141 // A lane may be empty, and so may every lane -- an emptied timeline is a
9142 // project. No lane at all is not one: there would be nothing to place on.
9143 assert!(
9144 Project::from_parts(
9145 sources.clone(),
9146 two(video.clone(), Vec::new()),
9147 Vec::new(),
9148 Vec::new(),
9149 Vec::new(),
9150 )
9151 .is_ok()
9152 );
9153 assert!(
9154 Project::from_parts(
9155 sources.clone(),
9156 two(Vec::new(), Vec::new()),
9157 Vec::new(),
9158 Vec::new(),
9159 Vec::new(),
9160 )
9161 .is_ok()
9162 );
9163 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
9164 let bad: [Vec<Clip>; 5] = [
9165 vec![clip(0, 0, 3, 1)], // source that is not there
9166 vec![clip(0, 3, 3, 0)], // empty clip
9167 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
9168 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
9169 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
9170 ];
9171 for clips in bad {
9172 assert!(
9173 Project::from_parts(
9174 sources.clone(),
9175 two(clips.clone(), Vec::new()),
9176 Vec::new(),
9177 Vec::new(),
9178 Vec::new(),
9179 )
9180 .is_err(),
9181 "{clips:?}"
9182 );
9183 assert!(
9184 Project::from_parts(
9185 sources.clone(),
9186 two(video.clone(), clips.clone()),
9187 Vec::new(),
9188 Vec::new(),
9189 Vec::new(),
9190 )
9191 .is_err()
9192 );
9193 // ...and on a third lane, which is checked by the same walk.
9194 assert!(
9195 Project::from_parts(
9196 sources.clone(),
9197 vec![
9198 (LaneKind::Video, video.clone()),
9199 (LaneKind::Audio, audio.clone()),
9200 (LaneKind::Video, clips),
9201 ],
9202 Vec::new(),
9203 Vec::new(),
9204 Vec::new(),
9205 )
9206 .is_err()
9207 );
9208 }
9209 // An equalizer index no table entry answers, and a table entry the file
9210 // format could not have written, are refused at this door too.
9211 let eqd = |i: u16| {
9212 vec![Clip {
9213 fade_in: 0,
9214 fade_out: 0,
9215 transition_out: 0,
9216 visualizer: 0,
9217 viz_paint: 0,
9218 eq: Some(i),
9219 ..video[0]
9220 }]
9221 };
9222 assert!(
9223 Project::from_parts(
9224 sources.clone(),
9225 two(eqd(0), Vec::new()),
9226 Vec::new(),
9227 Vec::new(),
9228 Vec::new(),
9229 )
9230 .is_err()
9231 );
9232 let mut nan = band_at(1);
9233 nan.bands[0].freq_hz = f32::NAN;
9234 assert!(
9235 Project::from_parts(
9236 sources.clone(),
9237 two(eqd(0), Vec::new()),
9238 vec![nan],
9239 Vec::new(),
9240 Vec::new(),
9241 )
9242 .is_err()
9243 );
9244 let loaded = Project::from_parts(
9245 sources.clone(),
9246 two(eqd(0), Vec::new()),
9247 vec![band_at(1)],
9248 Vec::new(),
9249 Vec::new(),
9250 )
9251 .expect("an eq the table holds");
9252 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
9253
9254 // The same two refusals for a colour, at the same door.
9255 let graded = |i: u16| {
9256 vec![Clip {
9257 fade_in: 0,
9258 fade_out: 0,
9259 transition_out: 0,
9260 visualizer: 0,
9261 viz_paint: 0,
9262 color: Some(i),
9263 fit: FitPolicy::default(),
9264 speed: Speed::NORMAL,
9265 ..video[0]
9266 }]
9267 };
9268 assert!(
9269 Project::from_parts(
9270 sources.clone(),
9271 two(graded(0), Vec::new()),
9272 Vec::new(),
9273 Vec::new(),
9274 Vec::new(),
9275 )
9276 .is_err(),
9277 "a colour index no entry answers"
9278 );
9279 assert!(
9280 Project::from_parts(
9281 sources.clone(),
9282 two(graded(0), Vec::new()),
9283 Vec::new(),
9284 vec![ColorParams {
9285 tint: f32::NAN,
9286 ..grade_at(1)
9287 }],
9288 Vec::new(),
9289 )
9290 .is_err(),
9291 "a value the file format could not have written"
9292 );
9293 let loaded = Project::from_parts(
9294 sources.clone(),
9295 two(graded(0), Vec::new()),
9296 Vec::new(),
9297 vec![grade_at(1)],
9298 Vec::new(),
9299 )
9300 .expect("a colour the table holds");
9301 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
9302
9303 // Group ids survive a load, and the next split gets a fresh one.
9304 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
9305 assert!(p.split(4));
9306 assert!(p.clips().iter().all(|c| c.link.is_some()));
9307 }
9308
9309 /// The grouping rules, at the untrusted door and after every edit that can
9310 /// touch a link. A link id is at most one placement per lane -- a clip or a
9311 /// caption, whichever carries it -- and no sequence of edits may produce
9312 /// otherwise, because what an edit produces is what a save writes and a load
9313 /// reads.
9314 ///
9315 /// Amended for the offset-preserving group: the members keep their own
9316 /// spans, so two placements of one id covering different frames is *legal*
9317 /// -- it is what a hand-built group is -- and the only refusal left is the
9318 /// doubled id inside one lane.
9319 #[test]
9320 fn a_link_id_is_never_two_clips_of_one_lane() {
9321 let sources = vec![Source::new(FILE, 0)];
9322 let linked = |start, in_frame, out_frame, link| Clip {
9323 fade_in: 0,
9324 fade_out: 0,
9325 transition_out: 0,
9326 visualizer: 0,
9327 viz_paint: 0,
9328 start,
9329 in_frame,
9330 out_frame,
9331 source: 0,
9332 link: Some(link),
9333 eq: None,
9334 color: None,
9335 transform: None,
9336 fit: FitPolicy::default(),
9337 speed: Speed::NORMAL,
9338 };
9339
9340 // The door: a doubled id inside one lane, refused by name.
9341 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
9342 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
9343 .expect_err("refused")
9344 .to_string()
9345 };
9346 assert!(
9347 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
9348 .contains("link 7 names two clips in the V1 lane"),
9349 "a duplicate id inside one lane is refused by name"
9350 );
9351 // ...and the same doubling on a subtitle lane, in its own words: a
9352 // caption is the other placement an id may name.
9353 let caption = |start: u32, frames: u32, link| SubClip {
9354 start,
9355 frames,
9356 track: 0,
9357 in_us: 0,
9358 out_us: i64::from(frames) * 1_000_000,
9359 link: Some(link),
9360 };
9361 let subs = LaneData {
9362 clips: Vec::new(),
9363 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
9364 ..LaneData::new(LaneKind::Subtitle, Vec::new())
9365 };
9366 assert_eq!(
9367 links_are_consistent(&[subs]).unwrap_err().to_string(),
9368 "link 7 names two captions in the S1 lane"
9369 );
9370 // A pair covering *different* frames is legal now: the members of a
9371 // hand-built group keep their own spans, and what binds them is the id.
9372 let apart = Project::from_parts(
9373 sources.clone(),
9374 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
9375 Vec::new(),
9376 Vec::new(),
9377 Vec::new(),
9378 );
9379 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
9380 // A one-sided link is *not* an error: it is what a lift leaves behind.
9381 let mut p = Project::single(FILE, 9);
9382 assert!(p.lift(Lane::A1, 0));
9383 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
9384 assert!(
9385 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
9386 "a lifted lane's project has to load again"
9387 );
9388
9389 // The edits: nothing below may break either rule.
9390 let consistent = |p: &Project, what: &str| {
9391 assert!(
9392 links_are_consistent(&p.lanes).is_ok(),
9393 "{what}: {:?}",
9394 p.lanes
9395 );
9396 };
9397 let mut p = three();
9398 let copied = p.clips()[0];
9399 assert!(
9400 copied.link.is_some(),
9401 "the clipboard clip carries its group"
9402 );
9403 assert!(p.lift(Lane::V1, 0));
9404 assert!(p.place(Lane::V1, 0, copied));
9405 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
9406 assert_eq!(
9407 p.clips().iter().filter(|c| c.link == copied.link).count(),
9408 0,
9409 "a placement belongs to no group, so it cannot duplicate one"
9410 );
9411 consistent(&p, "lift + place twice");
9412 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
9413 consistent(&p, "place through a grouped clip");
9414 assert!(p.paste(6, copied), "a rippling paste through another");
9415 consistent(&p, "paste");
9416 assert!(p.split(2));
9417 consistent(&p, "split");
9418 assert!(p.ripple_delete(1, 3));
9419 consistent(&p, "ripple_delete");
9420 assert!(p.undo());
9421 consistent(&p, "undo");
9422 }
9423
9424 /// What an edit produces is what a save writes, so *every* state the public
9425 /// API can reach has to load again. The two the verifier panel found where
9426 /// it did not: a split and a regroup handed one group id to two clips that
9427 /// were not the same span, because the lanes had been edited apart.
9428 #[test]
9429 fn every_reachable_state_reloads() {
9430 let mut p = Project::single(FILE, 150);
9431 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
9432 assert!(p.split(10), "the lanes are cut apart at 10");
9433 reloads(&p, "place on one lane, then split");
9434
9435 let mut p = Project::single(FILE, 150);
9436 assert!(p.split(30));
9437 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
9438 assert!(p.regroup(30), "only the audio lane can rejoin");
9439 assert!(p.split(60));
9440 reloads(&p, "lift, regroup one lane, split");
9441
9442 // Two audio streams of one file, both placed: two source entries with
9443 // one path between them, which is the state a stream picked out of the
9444 // library reaches -- and the state a save has to write and read back.
9445 let mut p = Project::single(FILE, 150);
9446 let second = p.import(FILE, 1);
9447 assert_eq!(second, 1, "the same file on another stream is a new source");
9448 assert!(p.append_clip(second, 150));
9449 assert!(p.split(200));
9450 reloads(
9451 &p,
9452 "a second audio stream of the same file, placed and split",
9453 );
9454 let (sources, ..) = p.without_orphan_sources();
9455 assert_eq!(
9456 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
9457 [0, 1],
9458 "both entries survive the orphan prune: both are played"
9459 );
9460 }
9461
9462 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
9463 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
9464 /// is the stamp playback puts on a decoded source frame -- and the *last*
9465 /// source frame the pump is still holding at a timeline frame has to be
9466 /// exactly the one the export encoded there, at every rate. Anything else is
9467 /// A/V drift that grows with the clip, and no test of either side alone
9468 /// would see it.
9469 ///
9470 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
9471 /// is a better answer than the floor/floor this had: floor/floor put the
9472 /// preview a whole held frame off the export at slow rates.)
9473 #[test]
9474 fn speed_maps_both_ways() {
9475 for permille in (250..=4000).step_by(1) {
9476 let speed = Speed::from_permille(permille);
9477 assert_eq!(speed.permille(), permille, "no clamping in range");
9478 for d in 0..200u32 {
9479 let want = speed.source_at(d);
9480 // What the pump shows at `d` is the last frame whose stamp has
9481 // come due -- and it is `want`, the frame the export encodes
9482 // there. Slowed, that is the frame it is still holding; sped up,
9483 // it is the newest of the several that arrived.
9484 let held = (0..=want + 8)
9485 .filter(|&s| speed.timeline_at(s) <= d)
9486 .next_back();
9487 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
9488 }
9489 for n in 1..300u32 {
9490 // A footprint is never zero: a clip occupying no timeline frame
9491 // is a placement the lane invariants cannot hold.
9492 let frames = speed.frames(n);
9493 assert!(frames >= 1, "{speed} of {n} frames");
9494 // ...and its last timeline frame never reads past the clip.
9495 assert!(
9496 speed.source_at(frames - 1) < n,
9497 "{speed}: the last timeline frame of {n} reads past the clip"
9498 );
9499 // The trim inverse never overshoots the room it was given, and
9500 // answers for every room a footprint can be.
9501 let fit = speed.fit(frames).expect("a clip fits its own footprint");
9502 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
9503 // A room narrower than one source frame's own footprint holds
9504 // nothing, and says so rather than rounding something into it.
9505 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
9506 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
9507 }
9508 }
9509 // Real time is the identity map, byte for byte.
9510 for d in 0..1000 {
9511 assert_eq!(Speed::NORMAL.source_at(d), d);
9512 assert_eq!(Speed::NORMAL.timeline_at(d), d);
9513 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
9514 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
9515 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
9516 }
9517 // The one door: no zero, no reverse, nothing past the ends.
9518 assert_eq!(Speed::from_permille(0), Speed::MIN);
9519 assert_eq!(Speed::from_permille(249), Speed::MIN);
9520 assert_eq!(Speed::from_permille(4001), Speed::MAX);
9521 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
9522 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
9523 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
9524 }
9525
9526 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
9527 /// export encodes at a timeline frame is the one playback is holding there,
9528 /// a file is as long in timeline frames as the seconds it lasts, and the two
9529 /// compose so a speeded clip at another rate is exactly both.
9530 #[test]
9531 fn rate_composes_with_speed() {
9532 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
9533 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
9534 // the identity map or a single-rate project would move.
9535 for (source_fps, timeline_fps) in [
9536 (24000. / 1001., 30.),
9537 (30., 24000. / 1001.),
9538 (60., 30.),
9539 (25., 30.),
9540 (30., 30.),
9541 ] {
9542 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
9543 for n in 0..2000u32 {
9544 let source = rate.source_at(n);
9545 // The stamp is the *first* timeline-rate frame that shows it, so
9546 // the picture on screen at `n` is the picture encoded at `n`.
9547 let held = (0..=source + 4)
9548 .filter(|&s| rate.timeline_at(s) <= n)
9549 .next_back();
9550 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
9551 }
9552 // A file of `count` frames is `timeline_at(count)` frames long here,
9553 // and its last one still reads a frame the file has.
9554 for count in 1..500u32 {
9555 let frames = rate.timeline_at(count);
9556 assert!(frames >= 1, "a file is never zero frames long");
9557 assert!(
9558 rate.source_at(frames - 1) < count,
9559 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
9560 );
9561 }
9562 // No drift: the mapping is one exact division of the *rate itself*,
9563 // not an accumulation and not a rounded rate, so an hour in is as
9564 // true as the first second. (Held to the real ratio of the two rates
9565 // the caller asked for -- `as_f64` would be true of a wrong rate.)
9566 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
9567 let want = f64::from(n) * source_fps / timeline_fps;
9568 assert!(
9569 (f64::from(rate.source_at(n)) - want).abs() < 1.,
9570 "{source_fps} on {timeline_fps}: frame {n} drifted"
9571 );
9572 }
9573 }
9574 // The timeline's own rate is the identity, whichever way it is written.
9575 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
9576 assert!(
9577 Rate::from_fps(30.0004, 30.)
9578 .expect("30.0004 over 30")
9579 .is_real_time(),
9580 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
9581 );
9582 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
9583 // one thing `matches_timeline` refuses a file for now that the rate gate
9584 // is gone.
9585 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
9586 assert!(Rate::from_fps(30., f64::NAN).is_err());
9587 for n in 0..1000 {
9588 assert_eq!(Rate::REAL_TIME.source_at(n), n);
9589 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
9590 }
9591 // ...and the composition, in the order the decoder's door applies it:
9592 // the speed picks the clip's (timeline-rate) frame, the rate picks the
9593 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
9594 // timeline frames per frame shown, each of them exactly 800/1001 of a
9595 // file frame.
9596 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
9597 let speed = Speed::from_permille(2000);
9598 for d in 0..100u32 {
9599 assert_eq!(
9600 rate.source_at(speed.source_at(d)),
9601 (u64::from(d) * 2 * 800 / 1001) as u32,
9602 "2x of a 23.976 fps file at timeline frame {d}"
9603 );
9604 }
9605 }
9606
9607 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
9608 /// source frames per timeline frame and still starts at its own in-point,
9609 /// and a half-speed one shows every source frame twice.
9610 #[test]
9611 fn a_rate_maps_timeline_frames_onto_source_frames() {
9612 let mut p = Project::single(FILE, 40);
9613 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9614 .expect("room enough");
9615 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
9616 assert_eq!(
9617 p.map(Lane::V1, 0),
9618 Some((0, 0)),
9619 "and it starts where it did"
9620 );
9621 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
9622 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
9623 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
9624 // The span a decoder is handed: as many source frames as it will read,
9625 // which is the last shown frame's own and not one more -- timeline frame
9626 // 19 shows source frame 38, so 39 frames are read and the 40th is a
9627 // picture nothing would display.
9628 let span = p.span_at(Lane::V1, 0).expect("a span");
9629 assert_eq!((span.len, span.source_len()), (20, 39));
9630 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
9631 // ...and the same clip the other way round.
9632 let mut p = Project::single(FILE, 40);
9633 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9634 .expect("room enough");
9635 assert_eq!(p.timeline_frames(), 80);
9636 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
9637 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
9638 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
9639 assert_eq!(
9640 p.map(Lane::V1, 79),
9641 Some((0, 39)),
9642 "and the last timeline frame is still inside the source range"
9643 );
9644 }
9645
9646 /// A trim of a speeded clip is still a trim of its *source*, and the edge
9647 /// still stops at the wall: the room a rate leaves is measured in timeline
9648 /// frames and the range it commits in source ones.
9649 #[test]
9650 fn trimming_a_speeded_clip_stays_inside_its_room() {
9651 let mut p = Project::single(FILE, 40);
9652 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9653 .expect("room enough");
9654 // A second clip butted against the first, so the wall is a real one.
9655 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
9656 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
9657 assert_eq!(room, (1, 20), "out to the neighbour and no further");
9658 assert!(
9659 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
9660 "clamped to the wall, which is where the edge already is"
9661 );
9662 let c = p.clips()[0];
9663 assert_eq!(c.end(), 20, "so nothing moved");
9664 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
9665 // ...and in: half the timeline frames is half the source range.
9666 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
9667 let c = p.clips()[0];
9668 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
9669 assert_eq!(c.end(), 10, "and ten timeline frames of them");
9670 assert!(sorted_disjoint(p.clips()));
9671 }
9672
9673 /// The frames a rate cannot address: at half speed each source frame is on
9674 /// screen twice, and the cut between the two showings is not a cut in the
9675 /// file. Refused, so the two halves always add up to the clip that was cut.
9676 #[test]
9677 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
9678 let mut p = Project::single(FILE, 10);
9679 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9680 .expect("room enough");
9681 assert_eq!(p.timeline_frames(), 20);
9682 assert!(
9683 !p.split(3),
9684 "an odd frame is between two showings of one frame"
9685 );
9686 assert_eq!(p.clips().len(), 1, "and nothing was cut");
9687 assert!(p.split(4), "an even one is a frame boundary");
9688 let halves = p.clips().to_vec();
9689 assert_eq!(
9690 (halves[0].end(), halves[1].start, halves[1].end()),
9691 (4, 4, 20),
9692 "the halves meet, and still end where the clip did"
9693 );
9694 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
9695 assert!(p.regroup(4), "and the inverse puts it back");
9696 assert_eq!(p.clips().len(), 1);
9697 }
9698
9699 /// The same claim, swept: random op sequences off the public surface, the
9700 /// project reloaded after every one of them. A failure prints its seed, and
9701 /// the seed replays the whole sequence.
9702 #[test]
9703 fn random_edit_sequences_reload() {
9704 // Two thousand, not two hundred: the overlap a hole punched into a slow
9705 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
9706 // sequences, and a 200-seed sweep walked straight past it (it took a
9707 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
9708 // has no business being the narrow one.
9709 for seed in 0..2000u64 {
9710 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9711 let mut next = move |n: u32| {
9712 // xorshift64*: no dependency, and the seed replays it exactly.
9713 rng ^= rng << 13;
9714 rng ^= rng >> 7;
9715 rng ^= rng << 17;
9716 (rng >> 33) as u32 % n
9717 };
9718 let mut p = Project::single(FILE, 40);
9719 for step in 0..24 {
9720 let frame = next(44);
9721 // A clipboard copy carries the group id of the take it came from
9722 // -- the input that made a placement duplicate an id -- and, one
9723 // time in three, a rate of its own: a *speeded clip placed over
9724 // a speeded clip* is the shape whose remainders have to be run
9725 // through `Speed::fit`, and it is not a shape the lanes hand out
9726 // on their own often enough to be sure of.
9727 let mut copied = *p
9728 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
9729 .get(next(4) as usize)
9730 .unwrap_or(&clip(0, 0, 5, 0));
9731 if next(3) == 0 {
9732 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
9733 }
9734 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
9735 let idx = next(4) as usize;
9736 let _ = match next(16) {
9737 // A clip dragged along its own lane to wherever the pointer
9738 // let it go: the op that moves a placement without changing
9739 // what it plays, so what it may not do is land on top of the
9740 // neighbour it was dragged at.
9741 15 => p.move_clip(lane, idx, lane, frame),
9742 // ...and a second `place`, so a punch lands inside a clip
9743 // far more often than one op in fourteen would put it there.
9744 14 => p.place(lane, frame, copied),
9745 0 => p.split(frame),
9746 1 => p.regroup(frame),
9747 2 => p.lift(lane, idx),
9748 3 => p.place(lane, frame, copied),
9749 4 => p.paste(frame, copied),
9750 5 => p.ripple_delete(frame, next(9)),
9751 6 => p.delete(idx),
9752 7 => p.undo(),
9753 // An equalizer put on and taken off in the mix: what a clip
9754 // carries has to reload with it, and the entries an undo
9755 // orphans must not come back out of the prune.
9756 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9757 9 => p.set_eq(lane, idx, None),
9758 // ...and a colour grade in the same mix, for the same
9759 // reason: it rides on the clip and its orphans must go.
9760 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
9761 11 => p.set_color(lane, idx, None),
9762 // ...and a rate in with them, which is the one of the three
9763 // that moves *placements*: a clip that grew has to be
9764 // refused rather than overlap, and one that shrank leaves a
9765 // lane that still loads. Both are what `reloads` asks.
9766 12 => p
9767 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9768 .is_ok(),
9769 _ => p.append_clip(0, 1 + next(9)),
9770 };
9771 reloads(&p, &format!("seed {seed}, step {step}"));
9772 }
9773 }
9774 }
9775
9776 /// The save/load round trip a project must survive: the parts a save writes,
9777 /// handed back to the constructor a load goes through -- every lane of them,
9778 /// and the reloaded timeline has to be the same lanes in the same order.
9779 fn reloads(p: &Project, what: &str) {
9780 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
9781 match Project::from_parts(sources, lanes, eq, color, transform) {
9782 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
9783 Ok(back) => {
9784 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
9785 // Placements, not whole clips: an orphan prune renumbers the
9786 // sources a clip names, which is the point of it.
9787 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
9788 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
9789 };
9790 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
9791 // The prune renumbers the eq table too, so what has to survive
9792 // is the settings themselves, clip by clip.
9793 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
9794 p.lanes()
9795 .into_iter()
9796 .map(|l| {
9797 (0..p.lane(l).len())
9798 .map(|i| p.eq_of(l, i).cloned())
9799 .collect()
9800 })
9801 .collect()
9802 };
9803 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
9804 // The colour table renumbers in the same prune, so the same
9805 // claim: the params a clip names, not the index it names them by.
9806 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
9807 p.lanes()
9808 .into_iter()
9809 .map(|l| {
9810 (0..p.lane(l).len())
9811 .map(|i| p.color_of(l, i).copied())
9812 .collect()
9813 })
9814 .collect()
9815 };
9816 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
9817 // ...and the transform table, by the same claim again.
9818 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
9819 p.lanes()
9820 .into_iter()
9821 .map(|l| {
9822 (0..p.lane(l).len())
9823 .map(|i| p.transform_of(l, i).copied())
9824 .collect()
9825 })
9826 .collect()
9827 };
9828 assert_eq!(
9829 transforms(&back),
9830 transforms(p),
9831 "{what}: the transforms changed"
9832 );
9833 }
9834 }
9835 }
9836
9837 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
9838 /// -- each one sorted and disjoint, and one span per group id -- asserted
9839 /// directly, where the point is the invariant rather than the round trip.
9840 fn invariants_hold(p: &Project, what: &str) {
9841 for lane in p.lanes() {
9842 assert!(
9843 sorted_disjoint(p.lane(lane)),
9844 "{what}: {} is out of order or overlaps itself: {:?}",
9845 lane.label(),
9846 p.lane(lane)
9847 );
9848 }
9849 if let Err(e) = links_are_consistent(&p.lanes) {
9850 panic!("{what}: {e}\n{:?}", p.lanes);
9851 }
9852 }
9853
9854 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
9855 /// edited without any other lane hearing about it. A handle naming a lane
9856 /// that is not there reads as empty and refuses to mutate.
9857 #[test]
9858 fn a_third_lane_is_a_peer() {
9859 let mut p = three();
9860 assert_eq!(p.lane_count(LaneKind::Video), 1);
9861 assert_eq!(p.lane_count(LaneKind::Audio), 1);
9862 let v2 = p.add_lane(LaneKind::Video);
9863 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
9864 assert_eq!(v2.label(), "V2");
9865 assert_eq!(p.lane_count(LaneKind::Video), 2);
9866 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9867 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
9868
9869 // A handle for a lane that is not there: empty, and no mutation takes.
9870 let v3 = Lane::new(LaneKind::Video, 2);
9871 assert!(p.lane(v3).is_empty());
9872 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
9873 assert!(!p.lift(v3, 0));
9874 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
9875
9876 // Placing on V2 moves nothing else, and the lane can outrun the rest.
9877 let before = shape(&p);
9878 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9879 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
9880 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
9881 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9882 assert_eq!(
9883 p.timeline_frames(),
9884 16,
9885 "the last lane to end sets the length"
9886 );
9887 assert_eq!(p.map(v2, 5), Some((0, 21)));
9888 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
9889 assert_eq!(
9890 p.span_at(v2, 0),
9891 Some(Span {
9892 start: 0,
9893 len: 4,
9894 from: None,
9895 speed: Speed::NORMAL
9896 })
9897 );
9898 // Every lane still covers the whole timeline, gaps included.
9899 for l in p.lanes() {
9900 let spans = p.spans_from(l, 0);
9901 assert_eq!(
9902 spans.iter().map(|s| s.len).sum::<u32>(),
9903 16,
9904 "{}",
9905 l.label()
9906 );
9907 }
9908 // ...and playback still reads V1 and A1, whatever else is there.
9909 assert_eq!(p.clips(), p.lane(Lane::V1));
9910 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
9911 let segments = p.segments_from(0, FPS);
9912 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
9913 assert_eq!(
9914 segments[3],
9915 (None, 0.0, 7.0 / FPS),
9916 "A1 keeps the clock counting over the picture V2 added"
9917 );
9918 invariants_hold(&p, "place on V2");
9919
9920 // A lift is that lane's business too, and the lane list undoes.
9921 assert!(p.lift(v2, 0));
9922 assert!(p.lane(v2).is_empty());
9923 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
9924 assert!(p.undo());
9925 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9926 assert!(p.undo());
9927 assert!(p.lane(v2).is_empty(), "the placement came off V2");
9928 assert!(p.undo(), "and one more step takes the lane itself back");
9929 assert_eq!(p.lane_count(LaneKind::Video), 1);
9930 assert_eq!(shape(&p), shape(&three()));
9931 }
9932
9933 /// The add taken back: an empty lane comes off, a lane holding clips never
9934 /// does (and says which clips), the last lane of a kind never does, the
9935 /// lanes below the one that went move up an `ord`, and one undo puts it
9936 /// back where it stood.
9937 #[test]
9938 fn an_empty_lane_comes_off_again() {
9939 let mut p = three();
9940 let v2 = p.add_lane(LaneKind::Video);
9941 let v3 = p.add_lane(LaneKind::Video);
9942 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
9943 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
9944 let history = p.history.len();
9945
9946 // The last lane of its kind stays: `V1`/`A1` are where an import and a
9947 // paste land, and a project missing one would swallow half of a file
9948 // dropped on it.
9949 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
9950 assert_eq!(
9951 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
9952 "there is no V10 to remove"
9953 );
9954
9955 // A lane with clips on it refuses and names them: a track removal never
9956 // deletes a take.
9957 let refusal = why(p.remove_lane(v3));
9958 assert!(refusal.contains("V3 still holds"), "{refusal}");
9959 assert!(refusal.contains(FILE), "{refusal}");
9960 assert!(refusal.contains("at frame 0"), "{refusal}");
9961 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
9962 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
9963
9964 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
9965 // all.
9966 p.remove_lane(v2).expect("V2 is empty");
9967 assert_eq!(p.lane_count(LaneKind::Video), 2);
9968 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9969 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
9970 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
9971 invariants_hold(&p, "remove V2");
9972
9973 // ...and one stroke puts the empty lane back above it.
9974 assert!(p.undo());
9975 assert_eq!(p.lane_count(LaneKind::Video), 3);
9976 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
9977 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
9978 }
9979
9980 /// A track dragged to another place in the stack: the whole lane travels --
9981 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
9982 /// a video one, a lane that crosses one of its own kind swaps names with it
9983 /// (and swaps the composite with it), one undo puts the order back, and a
9984 /// save carries it.
9985 #[test]
9986 fn a_track_is_dragged_to_another_place_in_the_stack() {
9987 let mut p = three();
9988 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
9989 let before = shape(&p);
9990 let history = p.history.len();
9991
9992 // A1 over V1: the screen is rearranged and nothing else is. Both keep
9993 // their names -- neither crossed a lane of its own kind -- so every
9994 // handle a front-end holds still names the track it named before.
9995 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
9996 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
9997 assert_eq!(
9998 shape(&p),
9999 vec![before[1].clone(), before[0].clone()],
10000 "each lane's clips travelled with it, and none was remapped"
10001 );
10002 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
10003 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
10004 invariants_hold(&p, "A1 over V1");
10005
10006 // Nothing moves for a lane that is not there, a slot that is not, or a
10007 // lane already standing in the one it was pointed at.
10008 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
10009 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
10010 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
10011 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
10012
10013 // ...and one stroke puts the order back.
10014 assert!(p.undo());
10015 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
10016 assert_eq!(shape(&p), before);
10017
10018 // A second video lane over the first: display order *is* the stack, so
10019 // the last video lane covering a frame is the picture that shows.
10020 let v2 = p.add_lane(LaneKind::Video);
10021 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
10022 let over = shape(&p)[2].clone();
10023 assert_eq!(
10024 p.composite_span_at(0).map(|s| s.len),
10025 Some(5),
10026 "V2's five frames are what frame 0 shows"
10027 );
10028
10029 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
10030 // a position among the lanes of its kind. The picture that wins changes
10031 // with it: the take that was covering is the covered one now.
10032 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
10033 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
10034 assert_eq!(
10035 shape(&p),
10036 vec![over.clone(), before[0].clone(), before[1].clone()],
10037 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
10038 );
10039 assert_eq!(
10040 p.composite_span_at(0).map(|s| s.len),
10041 Some(3),
10042 "the lower video lane wins, and it is the old V1 now"
10043 );
10044 invariants_hold(&p, "V2 over V1");
10045
10046 // A save writes that order and a load takes it back.
10047 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10048 assert_eq!(
10049 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10050 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
10051 );
10052 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
10053 assert_eq!(back.lanes(), p.lanes());
10054 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
10055
10056 assert!(p.undo(), "and the stack goes back to how it stood");
10057 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
10058 }
10059
10060 /// The grouping rule across more than two lanes, under the offset model: a
10061 /// split *keeps* the group on the left halves and hands the right halves of
10062 /// that group one fresh id of their own -- a clip in no group comes out of
10063 /// the cut in none. So a take cut apart is two takes, one per side, and a
10064 /// lane that was never part of it stays out of both.
10065 #[test]
10066 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
10067 let mut p = Project::single(FILE, 9);
10068 let take = p.clips()[0].link.expect("a fresh project is one take");
10069 let v2 = p.add_lane(LaneKind::Video);
10070 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
10071 assert!(p.split(4));
10072 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
10073 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
10074 };
10075 let (left, right) = (side(&p, 0), side(&p, 1));
10076 // The lanes in order are V1, A1, V2: the take's two keep its id on the
10077 // left, and the placed clip never had one for the cut to keep.
10078 assert_eq!(
10079 left,
10080 vec![Some(take), Some(take), None],
10081 "the left halves keep the take"
10082 );
10083 // ...and the right halves of that take are one fresh group.
10084 assert_eq!(right[0], right[1]);
10085 assert_ne!(right[0], Some(take));
10086 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
10087 invariants_hold(&p, "split across three lanes");
10088
10089 // V2 ends early: the left halves still keep what each clip carried --
10090 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
10091 // shared by exactly the take's lanes.
10092 let mut p = Project::single(FILE, 9);
10093 let v2 = p.add_lane(LaneKind::Video);
10094 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
10095 assert!(p.split(3));
10096 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
10097 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
10098 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
10099 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
10100 invariants_hold(&p, "split where one lane ends early");
10101
10102 // The inverse rejoins each lane into the group its left half kept.
10103 assert!(p.regroup(3));
10104 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
10105 assert_eq!(
10106 p.lane(Lane::V1)[0].link,
10107 Some(take),
10108 "the take's id is back, not a fresh one"
10109 );
10110 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
10111 invariants_hold(&p, "regroup across three lanes");
10112 }
10113
10114 /// A group is one placement per lane, on however many lanes carry the id --
10115 /// not a video/audio pair and not a pairing by `ord` -- and the members may
10116 /// cover whatever frames they cover: the offset between them is what a
10117 /// hand-built group keeps. Lanes built by hand, because the rule is checked
10118 /// at the untrusted door and no edit can produce the one thing it refuses.
10119 #[test]
10120 fn a_group_may_span_any_lane() {
10121 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
10122 let one = |start: u32, end: u32, link| Clip {
10123 fade_in: 0,
10124 fade_out: 0,
10125 transition_out: 0,
10126 visualizer: 0,
10127 viz_paint: 0,
10128 start,
10129 in_frame: start,
10130 out_frame: end,
10131 source: 0,
10132 link: Some(link),
10133 eq: None,
10134 color: None,
10135 transform: None,
10136 fit: FitPolicy::default(),
10137 speed: Speed::NORMAL,
10138 };
10139 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
10140 let kinds = [
10141 LaneKind::Video,
10142 LaneKind::Audio,
10143 LaneKind::Video,
10144 LaneKind::Audio,
10145 ];
10146 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
10147 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
10148 };
10149 let take = || vec![one(0, 4, 7)];
10150 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
10151 // The same take on V1 + A2 only, the lanes between it empty: legal, the
10152 // way a lifted half is legal.
10153 let across = build([take(), Vec::new(), Vec::new(), take()]);
10154 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
10155 // ...and so is a group whose members disagree about their spans: the
10156 // offset between them is the hand's business, not the loader's.
10157 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
10158 assert!(
10159 links_are_consistent(&apart).is_ok(),
10160 "[0, 4) on V1 and [2, 6) on A2 are one group"
10161 );
10162 // One id twice in one lane is still that lane's error, by name.
10163 let twice = build([
10164 Vec::new(),
10165 Vec::new(),
10166 vec![one(0, 4, 7), one(4, 8, 7)],
10167 Vec::new(),
10168 ]);
10169 assert_eq!(
10170 links_are_consistent(&twice).unwrap_err().to_string(),
10171 "link 7 names two clips in the V2 lane"
10172 );
10173 }
10174
10175 /// Every lane a save writes comes out, in display order and with its kind --
10176 /// an empty one included, since it is state a front-end shows -- and a
10177 /// two-lane project still writes exactly the parts it always did.
10178 #[test]
10179 fn a_save_writes_every_lane_it_has() {
10180 let mut p = three();
10181 let before = p.without_orphan_sources();
10182 assert_eq!(before.1.len(), 2, "V1 and A1");
10183 let v2 = p.add_lane(LaneKind::Video);
10184 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
10185 let a2 = p.add_lane(LaneKind::Audio);
10186 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
10187 assert_eq!(
10188 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
10189 [
10190 LaneKind::Video,
10191 LaneKind::Audio,
10192 LaneKind::Video,
10193 LaneKind::Audio
10194 ],
10195 "display order, not video-then-audio"
10196 );
10197 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
10198 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
10199 // ...and all four load again as the same four.
10200 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
10201 assert_eq!(back.lanes(), p.lanes());
10202 assert_eq!(back.lane(a2), p.lane(a2));
10203
10204 // Taking the lanes back leaves exactly what a two-lane save wrote.
10205 for _ in 0..3 {
10206 assert!(p.undo());
10207 }
10208 assert_eq!(
10209 p.without_orphan_sources(),
10210 before,
10211 "byte for byte the same parts a two-lane save always wrote"
10212 );
10213 }
10214
10215 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
10216 /// three lanes and grows more: every lane's own order and the one
10217 /// span-per-id rule after every op, *and* the reload the v4 format restored
10218 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
10219 /// project of any number of lanes.
10220 #[test]
10221 fn random_edit_sequences_keep_many_lanes_consistent() {
10222 for seed in 0..2000u64 {
10223 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
10224 let mut next = move |n: u32| {
10225 rng ^= rng << 13;
10226 rng ^= rng >> 7;
10227 rng ^= rng << 17;
10228 (rng >> 33) as u32 % n
10229 };
10230 let mut p = Project::single(FILE, 40);
10231 let v2 = p.add_lane(LaneKind::Video);
10232 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
10233 let lanes = [Lane::V1, Lane::A1, v2];
10234 for step in 0..24 {
10235 let frame = next(44);
10236 let copied = *p
10237 .lane(lanes[next(3) as usize])
10238 .get(next(4) as usize)
10239 .unwrap_or(&clip(0, 0, 5, 0));
10240 let lane = lanes[next(3) as usize];
10241 let idx = next(4) as usize;
10242 let _ = match next(14) {
10243 // The drag, in the mix: a clip dragged along its own lane
10244 // and onto another one, at a frame the pointer picked --
10245 // which is where the group rule and the sorted+disjoint one
10246 // meet, since every half travels the same distance.
10247 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
10248 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
10249 11 => p.set_eq(lane, idx, None),
10250 // A rate, which on many lanes is the group rule as well:
10251 // every clip carrying the link moves together or none of
10252 // them does, and `invariants_hold` is what says so.
10253 12 => p
10254 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
10255 .is_ok(),
10256 0 => p.split(frame),
10257 1 => p.regroup(frame),
10258 2 => p.lift(lane, idx),
10259 3 => p.place(lane, frame, copied),
10260 4 => p.paste(frame, copied),
10261 5 => p.ripple_delete(frame, next(9)),
10262 6 => p.delete(idx),
10263 7 => p.undo(),
10264 8 => {
10265 p.add_lane(if next(2) == 0 {
10266 LaneKind::Video
10267 } else {
10268 LaneKind::Audio
10269 });
10270 true
10271 }
10272 _ => p.append_clip(0, 1 + next(9)),
10273 };
10274 invariants_hold(&p, &format!("seed {seed}, step {step}"));
10275 reloads(&p, &format!("seed {seed}, step {step}"));
10276 }
10277 }
10278 }
10279
10280 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
10281 /// there, `V1` shows again on either side of it, and a frame no video lane
10282 /// covers is a gap however many lanes there are.
10283 #[test]
10284 fn the_composite_is_the_topmost_lane_with_a_clip() {
10285 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10286 let lanes = vec![
10287 // V1: the whole 30 frames of source 0.
10288 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10289 // V2: source 1 over the middle third.
10290 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
10291 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10292 ];
10293 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10294 assert_eq!(
10295 p.composite_spans_from(0),
10296 vec![
10297 Span {
10298 start: 0,
10299 len: 10,
10300 from: Some((0, 0)),
10301 speed: Speed::NORMAL
10302 },
10303 Span {
10304 start: 10,
10305 len: 10,
10306 from: Some((1, 5)),
10307 speed: Speed::NORMAL
10308 },
10309 Span {
10310 start: 20,
10311 len: 10,
10312 from: Some((0, 20)),
10313 speed: Speed::NORMAL
10314 },
10315 ],
10316 "V2 takes over for its own span and hands V1 back"
10317 );
10318 // A mid-span ask resolves the same way, which is what a seek does.
10319 assert_eq!(
10320 p.composite_span_at(15),
10321 Some(Span {
10322 start: 15,
10323 len: 5,
10324 from: Some((1, 10)),
10325 speed: Speed::NORMAL
10326 })
10327 );
10328 assert_eq!(p.composite_span_at(30), None, "past the end");
10329
10330 // A hole in V1 under V2's clip: black between the two, and black after
10331 // both run out (the audio lane is still holding the timeline open).
10332 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10333 let holed = vec![
10334 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
10335 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
10336 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10337 ];
10338 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
10339 assert_eq!(
10340 p.composite_spans_from(0),
10341 vec![
10342 Span {
10343 start: 0,
10344 len: 5,
10345 from: Some((0, 0)),
10346 speed: Speed::NORMAL
10347 },
10348 Span {
10349 start: 5,
10350 len: 5,
10351 from: None,
10352 speed: Speed::NORMAL
10353 },
10354 Span {
10355 start: 10,
10356 len: 10,
10357 from: Some((1, 0)),
10358 speed: Speed::NORMAL
10359 },
10360 Span {
10361 start: 20,
10362 len: 10,
10363 from: None,
10364 speed: Speed::NORMAL
10365 },
10366 ]
10367 );
10368
10369 // One video lane: the composite *is* that lane, span for span -- the
10370 // promise every existing two-lane project rests on.
10371 let p = Project::single(FILE, 30);
10372 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
10373 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
10374 }
10375
10376 /// Every audio lane holding something gets a play list, and only those.
10377 #[test]
10378 fn audio_segments_cover_every_lane_that_holds_something() {
10379 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
10380 let lanes = vec![
10381 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10382 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
10383 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
10384 (LaneKind::Audio, Vec::new()),
10385 ];
10386 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
10387 let lists = p.audio_segments_from(0, FPS);
10388 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
10389 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
10390 // A2 is a gap up to frame 15, then the whole of source 1.
10391 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
10392
10393 // No audio lane holds anything: one all-gap list, so such a timeline
10394 // still plays silence against a master clock.
10395 let p = Project::from_parts(
10396 vec![Source::new(FILE, 0)],
10397 vec![
10398 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
10399 (LaneKind::Audio, Vec::new()),
10400 ],
10401 vec![],
10402 vec![],
10403 Vec::new(),
10404 )
10405 .expect("valid parts");
10406 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
10407 }
10408}