forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5984e27Tahinli3 months ago583 commits

project.rs9376 lines, 409.3 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119);
120
121impl Speed {
122 /// Real time -- what every clip is until something says otherwise, and the
123 /// value every path in this engine short-circuits on.
124 pub const NORMAL: Speed = Speed(1000);
125 pub const MIN: Speed = Speed(250);
126 pub const MAX: Speed = Speed(4000);
127
128 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
129 /// unrepresentable rather than merely refused: nothing downstream divides
130 /// by a speed that could be nothing.
131 pub fn from_permille(permille: u16) -> Self {
132 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
133 }
134
135 pub fn permille(self) -> u16 {
136 self.0
137 }
138
139 pub fn is_normal(self) -> bool {
140 self == Self::NORMAL
141 }
142
143 /// As a multiplier, for the sound worker and for a label.
144 pub fn as_f64(self) -> f64 {
145 f64::from(self.0) / 1000.
146 }
147
148 /// How many *timeline* frames `source` source frames occupy at this rate --
149 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
150 /// clip that occupied no frames would be an empty placement, which the lane
151 /// invariant forbids and which nothing could ever click on again.
152 pub fn frames(self, source: u32) -> u32 {
153 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
154 n.clamp(1, u64::from(u32::MAX)) as u32
155 }
156
157 /// The mapping itself: which source frame of a clip the `offset`th timeline
158 /// frame of it plays. Floored, so the first timeline frame is the clip's own
159 /// in-point at every rate.
160 pub fn source_at(self, offset: u32) -> u32 {
161 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
162 }
163
164 /// Its inverse, for a decoder's frames on their way back out: which timeline
165 /// frame of the clip the `offset`th *source* frame of it lands on.
166 ///
167 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
168 /// decoded frame with this and shows the newest whose stamp has come due, so
169 /// what is on screen at timeline offset `d` is the last source frame with
170 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
171 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
172 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
173 /// the two the same way would put the preview a frame off the export at some
174 /// speeds and a whole held frame off at slow ones -- drift that no test of
175 /// either side alone would catch.
176 pub fn timeline_at(self, offset: u32) -> u32 {
177 (u64::from(offset) * 1000)
178 .div_ceil(u64::from(self.0))
179 .min(u64::from(u32::MAX)) as u32
180 }
181
182 /// The longest source range that still *fits* in `frames` timeline frames at
183 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
184 /// any room narrower than the four timeline frames one source frame occupies.
185 ///
186 /// What a trim commits and what a hole-punch leaves behind: rounding could
187 /// otherwise hand back a range wider than the room, and a clip that outgrew
188 /// its room would overlap its neighbour -- the one thing a lane may never do.
189 /// `None` is not an error, it is "no remainder": the caller drops that piece
190 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
191 /// is `frames` itself, so nothing about an unspeeded edit changes.
192 pub fn fit(self, frames: u32) -> Option<u32> {
193 if frames == 0 || self.frames(1) > frames {
194 return None;
195 }
196 let mut src = self.source_at(frames).max(1);
197 // At most a step or two: `frames` is monotone in `src` and the rounding
198 // above can only overshoot by one source frame's worth.
199 while src > 1 && self.frames(src) > frames {
200 src -= 1;
201 }
202 Some(src)
203 }
204
205 /// How many timeline frames `source` source frames of head (or tail) are
206 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
207 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
208 /// empty, but the room in front of one may well be.
209 pub fn room(self, source: u32) -> u32 {
210 match source {
211 0 => 0,
212 n => self.frames(n),
213 }
214 }
215
216 /// How many timeline frames from `offset` on show the **same** source frame:
217 /// one at real time and faster, more when the clip is slowed. What an export
218 /// encodes without decoding the same picture twice, and the count that makes
219 /// its frame walk exactly as long as the span.
220 pub fn repeats(self, offset: u32, len: u32) -> u32 {
221 let want = self.source_at(offset);
222 (offset..len)
223 .take_while(|&t| self.source_at(t) == want)
224 .count() as u32
225 }
226
227 /// Where in the source a cut `offset` timeline frames into a clip of `len`
228 /// source frames falls -- and `None` when this rate cannot address that
229 /// frame at all.
230 ///
231 /// At half speed a clip of ten source frames is twenty timeline frames long
232 /// and every source frame is on screen twice, so a cut between the two
233 /// showings of one frame is not a cut in the *file*: taking it would leave
234 /// two halves whose lengths no longer add up to the clip that was cut --
235 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
236 /// the model stays exact and the front-end can say why. At real time every
237 /// interior frame answers, which is the path a project without speeds is on.
238 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
239 let src = self.source_at(offset);
240 (src > 0
241 && src < len
242 && self.frames(src) == offset
243 && self.frames(len - src) == self.frames(len) - offset)
244 .then_some(src)
245 }
246}
247
248impl Default for Speed {
249 fn default() -> Self {
250 Self::NORMAL
251 }
252}
253
254impl std::fmt::Display for Speed {
255 /// `2.00x` -- what a card prints and what a clip box is marked with.
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{:.2}x", self.as_f64())
258 }
259}
260
261/// What a file's own frame rate is against the timeline's, as an exact
262/// rational: how many frames of the *file* one frame of the timeline is worth.
263///
264/// Every frame number in this module counts **timeline** frames -- a clip's
265/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
266/// timeline is as many frames long as the seconds it lasts, and every edit
267/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
268/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
269/// opens a worker with it and [`crate::export`] pulls pictures through it. The
270/// file's own numbering exists nowhere else.
271///
272/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
273/// export encodes at a timeline frame has to be the frame playback is holding
274/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
275/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
276///
277/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
278/// stays `800/1001` however far the timeline runs, where a rate rounded to
279/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
280/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
281///
282/// [`PlaybackSession`]: crate::PlaybackSession
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
284pub struct Rate {
285 /// Frames of the file...
286 source: u32,
287 /// ...per this many frames of the timeline it plays on. Never zero.
288 timeline: u32,
289}
290
291impl Rate {
292 /// A file shot at the timeline's own rate: every conversion below is the
293 /// identity, which is the path a single-rate project is on.
294 pub const REAL_TIME: Self = Self {
295 source: 1,
296 timeline: 1,
297 };
298
299 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
300 /// exactly.
301 ///
302 /// Both rates come out of a container as a division, so neither is ever the
303 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
304 /// already knows how to name one exactly -- it is the same pair the muxer
305 /// counts an export's frames in -- and this is that pair divided by that
306 /// pair, reduced. A rate no timescale can name is an `Err` in that
307 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
308 /// where a file carrying one is refused by name, beside the codec.
309 ///
310 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
311 /// timeline that had ever opened in this editor before mixed rates.
312 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
313 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
314 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
315 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
316 let num = u64::from(src_scale) * u64::from(tl_ticks);
317 let den = u64::from(src_ticks) * u64::from(tl_scale);
318 Ok(Self::reduced(num, den))
319 }
320
321 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
322 fn reduced(num: u64, den: u64) -> Self {
323 let g = gcd(num, den);
324 let (mut num, mut den) = (num / g, den / g);
325 // A ratio no pair of real frame rates produces, but the fields are `u32`
326 // so that every multiplication below fits a `u64` at any frame count.
327 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
328 (num, den) = (num.div_ceil(2), den.div_ceil(2));
329 }
330 Self {
331 source: num.max(1) as u32,
332 timeline: den.max(1) as u32,
333 }
334 }
335
336 /// The same file against a timeline that has itself been retimed: `self` is
337 /// its frames per frame of the old timeline and `k` is old frames per new
338 /// one, so this is its frames per frame of the *new* one -- exactly, without
339 /// going back through an `f64` fps that names neither rate
340 /// ([`crate::PlaybackSession::set_frame_rate`]).
341 pub fn then(self, k: Rate) -> Self {
342 Self::reduced(
343 u64::from(self.source) * u64::from(k.source),
344 u64::from(self.timeline) * u64::from(k.timeline),
345 )
346 }
347
348 pub fn is_real_time(self) -> bool {
349 self.source == self.timeline
350 }
351
352 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
353 /// is, given the timeline's, for a library row that names it.
354 pub fn as_f64(self) -> f64 {
355 f64::from(self.source) / f64::from(self.timeline)
356 }
357
358 /// Which frame of the file the `frame`th timeline-rate frame of it is:
359 /// floored, [`Speed::source_at`]'s half of the pair.
360 pub fn source_at(self, frame: u32) -> u32 {
361 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
362 .min(u64::from(u32::MAX)) as u32
363 }
364
365 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
366 /// timeline-rate frame that shows source frame `source_frame` -- which is
367 /// the stamp playback puts on a decoded picture, and, applied to a file's
368 /// frame *count*, how long that file is in timeline frames.
369 pub fn timeline_at(self, source_frame: u32) -> u32 {
370 (u64::from(source_frame) * u64::from(self.timeline))
371 .div_ceil(u64::from(self.source))
372 .min(u64::from(u32::MAX)) as u32
373 }
374}
375
376/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
377/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
378fn gcd(a: u64, b: u64) -> u64 {
379 match b {
380 0 => a.max(1),
381 b => gcd(b, a % b),
382 }
383}
384
385/// A half-open `[in_frame, out_frame)` range of frames of source
386/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
387/// Never empty.
388///
389/// Counted at the **timeline's** frame rate, not the file's: a source shot at
390/// another rate is converted at the decoder's door ([`Rate`]), so every edit
391/// here is frames of one clock.
392#[derive(Clone, Copy, PartialEq, Eq, Debug)]
393pub struct Clip {
394 /// Timeline frame the clip's first frame is shown at. Meaningless on a
395 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
396 /// with where the caller asked for.
397 pub start: u32,
398 pub in_frame: u32,
399 pub out_frame: u32,
400 /// Index into [`Project::sources`].
401 pub source: usize,
402 /// Group id: clips sharing one were split from the same take. `None` for a
403 /// clip that belongs to no group.
404 pub link: Option<u32>,
405 /// Index into the project's equalizer table
406 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
407 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
408 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
409 /// plain assignment. The table is append-only within a session, so an index
410 /// on a clipboard clip or inside an undo snapshot can never dangle.
411 pub eq: Option<u16>,
412 /// Index into the project's colour table
413 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
414 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
415 /// promises: `Copy`, append-only within a session, never dangling.
416 pub color: Option<u16>,
417 /// Index into the project's transform table
418 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
419 /// clip that plays at its fit policy's own placement. An index for
420 /// [`Clip::color`]'s reason and with the same promises.
421 pub transform: Option<u16>,
422 /// How this clip's picture meets a project canvas of another shape
423 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
424 /// two above: it is one byte with no parameters, so there is nothing for a
425 /// table to share, and a clip that is the project's own size never consults
426 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
427 /// where the aspect does not agree.
428 pub fit: FitPolicy,
429 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
430 /// eq and colour indexes: it is two bytes with nothing to share, and a table
431 /// would put a level of indirection between the mapping and the one number
432 /// every frame of it is divided by.
433 ///
434 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
435 /// the clip plays, so a trim and a split still address the file. What it
436 /// changes is how many *timeline* frames that range is spread over
437 /// ([`Clip::frames`]).
438 pub speed: Speed,
439 /// Timeline frames of ramp-up from silence at the clip's own start, inline
440 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
441 /// number with nothing to share, and every consumer (mixer, exporter) wants
442 /// it sitting right next to the frame range it shapes. Clamped to the
443 /// clip's own length by the setter -- never wider than the clip is long.
444 pub fade_in: u32,
445 /// Timeline frames of ramp-down to silence at the clip's own end. Same
446 /// promises as [`Clip::fade_in`].
447 pub fade_out: u32,
448 /// Timeline frames of cross-dissolve into the clip immediately after this
449 /// one on the same video lane, at this clip's own end -- `0` for a hard
450 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
451 /// reason, and clamped the same way by its setter
452 /// ([`Project::set_transition_out`]): never wider than this clip's own
453 /// length, nor than the successor it dissolves into. Meaningless -- and
454 /// left as whatever it was -- the moment the next clip stops abutting
455 /// this one; a reader that cares checks adjacency itself rather than
456 /// trusting this field alone, exactly as a stored fade is trusted only
457 /// because a clip's own length is checked beside it.
458 pub transition_out: u32,
459}
460
461impl Clip {
462 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
463 /// reads out of its file -- not how long it is on the timeline, which is
464 /// [`Clip::frames`] and differs the moment it is speeded.
465 pub fn len(&self) -> u32 {
466 self.out_frame - self.in_frame
467 }
468
469 /// Timeline frames it occupies: its source range at its own speed, never
470 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
471 /// what it overlaps, how wide its box is -- is asked of this and not of
472 /// [`Clip::len`].
473 pub fn frames(&self) -> u32 {
474 self.speed.frames(self.len())
475 }
476
477 /// One past the last timeline frame it covers.
478 pub fn end(&self) -> u32 {
479 self.start + self.frames()
480 }
481}
482
483/// A file the timeline plays from, and *which* of its audio streams it plays:
484/// a file carrying one track per language is several sources, one per stream,
485/// sharing a path. Two entries differing only in the stream are two sources --
486/// they are what a clip names, and a clip plays exactly one stream.
487///
488/// The path is always canonical ([`Source::new`]), so the same file reached by
489/// two paths is one source.
490#[derive(Clone, Debug, PartialEq, Eq)]
491pub struct Source {
492 pub path: PathBuf,
493 /// Position among the file's audio tracks in file order, the numbering
494 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
495 /// single track, and for a silent one.
496 pub audio_stream: usize,
497}
498
499impl Source {
500 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
501 Self {
502 path: canonical(path.as_ref()),
503 audio_stream,
504 }
505 }
506}
507
508/// What a lane carries, which is what a *gap* in it means: black frames on a
509/// video lane, silence on an audio one, nothing over the picture on a subtitle
510/// one.
511#[derive(Clone, Copy, PartialEq, Eq, Debug)]
512pub enum LaneKind {
513 Video,
514 Audio,
515 /// Words over the picture, placed and trimmed like everything else
516 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
517 /// so a caption is dragged, cut, rippled and undone by the machinery every
518 /// other clip already goes through.
519 ///
520 /// It carries no [`Clip`] at all, and that is what keeps the media paths
521 /// free of it: [`Project::lane`] hands back an empty slice, so every
522 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
523 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
524 /// check it already had, [`Project::composite_span_at`] and
525 /// [`Project::audio_lanes`] never look at it, and the three doors that
526 /// could still put a picture on one -- [`Project::from_parts`],
527 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
528 Subtitle,
529}
530
531/// Which lane an operation acts on: a kind plus a 0-based position among the
532/// lanes of that kind, so [`Lane::V1`] is the first video lane and
533/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
534///
535/// A handle, not the lane itself. It stays meaningful while lanes are added,
536/// and one naming a lane that is not there reads as an empty lane and refuses
537/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
538/// bounds check of its own.
539#[derive(Clone, Copy, PartialEq, Eq, Debug)]
540pub struct Lane {
541 pub kind: LaneKind,
542 pub ord: usize,
543}
544
545impl Lane {
546 /// The first video lane: what a decoder plays and what an export renders.
547 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
548 /// The first audio lane: what the audio worker plays.
549 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
550 /// The first subtitle lane -- the one a project has only once something
551 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
552 /// alone.
553 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
554
555 pub const fn new(kind: LaneKind, ord: usize) -> Self {
556 Self { kind, ord }
557 }
558
559 /// `V1`, `A2`: how a lane is written in a header column and named in an
560 /// error about it.
561 pub fn label(self) -> String {
562 let kind = match self.kind {
563 LaneKind::Video => 'V',
564 LaneKind::Audio => 'A',
565 LaneKind::Subtitle => 'S',
566 };
567 format!("{kind}{}", self.ord + 1)
568 }
569}
570
571/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
572/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
573/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
574/// frames. Never empty at either end.
575///
576/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
577/// actually has, and placed by the same one number: the window is in the
578/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
579/// placement is in timeline frames like everything else on a lane. So the lane
580/// invariant is the lane's ([`subs_sorted_disjoint`] is
581/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
582/// else, and only the two calls that change a *duration* -- a trim, and the
583/// mapping out -- ever need the timeline's rate.
584///
585/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
586/// paste and an undo snapshot are a plain assignment and can never dangle.
587#[derive(Clone, Copy, PartialEq, Eq, Debug)]
588pub struct SubClip {
589 /// Timeline frame its first frame is shown at.
590 pub start: u32,
591 /// How many timeline frames it covers; `>= 1`. Held rather than derived
592 /// from the window because a [`Project`] has no frame rate -- the rate
593 /// enters at the door of the two calls that need it -- and every placement
594 /// question (where it ends, what it overlaps) is asked in frames.
595 pub frames: u32,
596 /// Index into [`Project::subtitles`]: *which* track's words these are.
597 pub track: usize,
598 /// The half-open window of that track it shows, in microseconds from the
599 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
600 /// timed in, so no conversion stands between a cue and the window that
601 /// keeps it.
602 pub in_us: i64,
603 pub out_us: i64,
604 /// Group id: `Some` exactly when a hand put this caption in a group with
605 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
606 /// no group, and what a cut cuts apart loses the one it had
607 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
608 /// clip is what makes the caption move, trim and delete with it.
609 pub link: Option<u32>,
610}
611
612impl SubClip {
613 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
614 /// what every overlap question is asked of.
615 pub fn end(&self) -> u32 {
616 self.start + self.frames
617 }
618
619 /// How much of its track it shows, in microseconds; `>= 1` by the
620 /// never-empty invariant.
621 pub fn window_us(&self) -> i64 {
622 self.out_us - self.in_us
623 }
624
625 /// Where in its window the timeline frame `frame` falls, in microseconds --
626 /// the cut a split, a ripple and a trim all land on.
627 ///
628 /// By proportion and not by the timeline's rate: the window and the frame
629 /// count measure the same stretch of time, so the fraction of the frames
630 /// before `frame` is the fraction of the microseconds before it. That is
631 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
632 /// without either of them learning an fps.
633 fn window_at(&self, frame: u32) -> i64 {
634 let into = i64::from(frame.saturating_sub(self.start));
635 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
636 }
637}
638
639/// One lane: what it is and what it holds. A struct rather than a bare
640/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
641/// compositing mode, a name -- and it belongs next to the clips it applies to.
642#[derive(Clone, Debug)]
643struct LaneData {
644 kind: LaneKind,
645 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
646 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
647 /// ever seeing a subtitle: they all read this list.
648 clips: Vec<Clip>,
649 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
650 /// empty on a video or audio one. Beside the clips rather than an enum over
651 /// them so that everything a lane *is* -- its place in the stack, its
652 /// label, its undo snapshot, its removal -- stays one code path for all
653 /// three kinds.
654 subs: Vec<SubClip>,
655 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
656 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
657 /// makes it a different thing from a clip's equalizer: it moves everything
658 /// on the track by the same amount, cuts included. Meaningless on a video
659 /// lane, where it is kept at 0 and asked by nothing.
660 gain_db: f32,
661}
662
663impl LaneData {
664 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
665 Self {
666 kind,
667 clips,
668 subs: Vec::new(),
669 gain_db: 0.0,
670 }
671 }
672
673 /// The two lanes a project starts with: `V1` then `A1`, in display order.
674 /// One place, because a freshly opened file is exactly this pair.
675 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
676 vec![
677 LaneData::new(LaneKind::Video, video),
678 LaneData::new(LaneKind::Audio, audio),
679 ]
680 }
681}
682
683/// The placements one group id names, split by the two lists a lane holds:
684/// what a drag, a trim and a delete each have to walk, now that a group may
685/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
686/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
687/// -- so the pairs are `(lane storage index, index into that lane's list)`.
688#[derive(Default)]
689struct Members {
690 clips: Vec<(usize, usize)>,
691 subs: Vec<(usize, usize)>,
692}
693
694impl Members {
695 /// Whether the group is the one placement and no more: what a lift leaves
696 /// behind, and what every whole-group question answers "not one" for.
697 fn alone(&self) -> bool {
698 self.clips.len() + self.subs.len() < 2
699 }
700}
701
702/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
703#[derive(Clone, Copy, PartialEq, Eq, Debug)]
704pub enum Edge {
705 /// Its first timeline frame; moving it changes where in the source the clip
706 /// starts reading, so the picture behind the edge slides with it.
707 Start,
708 /// One past its last timeline frame; moving it only says how much of the
709 /// source to keep.
710 End,
711}
712
713/// What a lane holds over one stretch of the timeline: either a placed clip or
714/// a gap. Returned already trimmed to the position it was asked about, so a
715/// caller can hand `len` straight to a decoder (or to a black-frame generator).
716#[derive(Clone, Copy, PartialEq, Eq, Debug)]
717pub struct Span {
718 /// Timeline frame the span starts at.
719 pub start: u32,
720 /// Frames it covers; `>= 1`.
721 pub len: u32,
722 /// `(source index, first source frame)`, or `None` for a gap -- which the
723 /// engine renders as black frames and as silence.
724 pub from: Option<(usize, u32)>,
725 /// The rate the clip this came off plays at ([`Clip::speed`]);
726 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
727 /// timeline frames whatever it says -- the speed is how many *source* frames
728 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
729 /// come back to the timeline.
730 pub speed: Speed,
731}
732
733impl Span {
734 /// One past the last timeline frame it covers.
735 pub fn end(&self) -> u32 {
736 self.start + self.len
737 }
738
739 /// How many source frames it reads: what a decoder is asked for and how wide
740 /// an audio window is. `len` at real time, and the one arithmetic both the
741 /// picture and the sound go through, so they cannot disagree about where a
742 /// speeded clip ends.
743 pub fn source_len(&self) -> u32 {
744 match self.from {
745 // The last timeline frame's own source frame is the last one needed
746 // -- never one more, which at a slow rate would read a frame the
747 // next clip owns and at a fast one would decode a picture nothing
748 // shows.
749 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
750 None => self.len,
751 }
752 }
753
754 /// Where a source frame of this span lands on the timeline: the stamp
755 /// playback puts on a decoded frame, through the ceil half of the pair
756 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
757 /// frame, so a frame before it stamps at the span's start.
758 pub fn timeline_at(&self, source_frame: u32) -> u32 {
759 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
760 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
761 }
762}
763
764/// What one speeded audio segment asks of the worker: how many source frames to
765/// consume per output frame, and how many seconds of timeline it has to fill.
766/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
767/// resampling at all.
768#[derive(Clone, Copy, PartialEq, Debug)]
769pub struct Stretch {
770 /// Source frames per output frame -- the speed as a multiplier.
771 pub step: f64,
772 /// What the segment owes the timeline, which is what it is padded or
773 /// trimmed to.
774 pub timeline_secs: f64,
775}
776
777/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
778/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
779/// against where in the *clip* -- not the segment, which may start mid-clip
780/// on a seek -- this segment's first frame lands.
781#[derive(Clone, Copy, PartialEq, Eq, Debug)]
782pub struct Fade {
783 /// How many of the clip's own frames already played before this
784 /// segment's first frame: `0` unless playback started mid-clip.
785 pub elapsed: u32,
786 /// The clip's [`Clip::fade_in`].
787 pub fade_in: u32,
788 /// The clip's [`Clip::fade_out`].
789 pub fade_out: u32,
790 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
791 /// which this segment may only cover the tail.
792 pub total: u32,
793}
794
795impl Fade {
796 /// The gain at clip-relative frame `pos`, an equal-power curve on each
797 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
798 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
799 /// ramp, so a fade lands on silence at its very first (or very last)
800 /// frame and reaches unity smoothly rather than at a constant slope --
801 /// the same curve [`Project::crossfade`] relies on to keep two clips'
802 /// sum around one level through the join. Both ramps multiply where a
803 /// clip is short enough for them to overlap.
804 fn gain_at(self, pos: u32) -> f32 {
805 let mut g = 1.0f32;
806 if self.fade_in > 0 && pos < self.fade_in {
807 let t = pos as f32 / self.fade_in as f32;
808 g *= (t * std::f32::consts::FRAC_PI_2).sin();
809 }
810 if self.fade_out > 0 {
811 let out_start = self.total.saturating_sub(self.fade_out);
812 if pos >= out_start {
813 let remaining = self.total.saturating_sub(pos);
814 let t = remaining as f32 / self.fade_out as f32;
815 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
816 }
817 }
818 g
819 }
820
821 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
822 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
823 pub fn apply(self, frames: &mut [f32], channels: usize) {
824 for (i, block) in frames.chunks_mut(channels).enumerate() {
825 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
826 for s in block {
827 *s *= g;
828 }
829 }
830 }
831}
832
833/// What a save writes and a load takes back: the sources, every lane in
834/// display order with its kind, and the equalizer and colour tables their clips
835/// index into -- [`Project::without_orphan_sources`] out,
836/// [`Project::from_parts`] in.
837pub type Parts = (
838 Vec<Source>,
839 Vec<(LaneKind, Vec<Clip>)>,
840 Vec<EqParams>,
841 Vec<ColorParams>,
842 Vec<TransformParams>,
843);
844
845/// How many undo steps a project keeps. One gesture is one step, so 100 is past
846/// any chain a person walks back by hand, and the oldest step is dropped rather
847/// than the history growing without end: a snapshot is the whole lane list, so
848/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
849/// that grows for as long as the session lasts.
850const HISTORY_CAP: usize = 100;
851
852/// The edit list plus its undo history.
853#[derive(Clone, Debug)]
854pub struct Project {
855 /// Append-only: never popped, never reordered. See the module docs.
856 sources: Vec<Source>,
857 /// In display order, which is the order [`Lane::ord`] counts in: the nth
858 /// lane of a kind here is that kind's `ord` n. Never empty.
859 lanes: Vec<LaneData>,
860 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
861 eq: Vec<EqParams>,
862 /// The same, for [`Clip::color`].
863 color: Vec<ColorParams>,
864 /// The same, for [`Clip::transform`].
865 transform: Vec<TransformParams>,
866 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
867 /// whole lane list, so adding a lane undoes as well. Bounded by
868 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
869 history: Vec<Vec<LaneData>>,
870 /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by
871 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
872 /// the undone steps came from. Not saved to `.edith`, matching `history`.
873 redo: Vec<Vec<LaneData>>,
874 /// Never rolled back by an undo: an id retired by an undone split must not
875 /// come back and group two clips that were never together.
876 next_link: u32,
877 /// The subtitle tracks this timeline shows, in the order they were added.
878 /// Not in the lane list and not in the history snapshots, for the reason
879 /// the limiter is not: which subtitles a project carries is a setting on
880 /// it, and it is saved as a *reference* to the file the cues came out of
881 /// ([`crate::subtitle`]).
882 subtitles: Vec<SubtitleTrack>,
883 /// The master limiter every lane's sound is summed *through*
884 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
885 /// is what the history snapshots hold: it is a setting on the mix, like the
886 /// project's resolution is a setting on the picture, and neither is an undo
887 /// step.
888 limiter: Limiter,
889 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
890 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
891 /// the resolution, and not in the lane snapshots for the same reason.
892 tone: crate::tonemap::Preset,
893}
894
895impl Project {
896 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
897 /// grouped -- the state of a freshly opened video, where the timeline is the
898 /// source. `frame_count` of 0 would break the never-empty invariant, so it
899 /// is clamped to one frame.
900 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
901 let clip = Clip {
902 fade_in: 0,
903 fade_out: 0,
904 transition_out: 0,
905 start: 0,
906 in_frame: 0,
907 out_frame: frame_count.max(1),
908 source: 0,
909 link: Some(0),
910 eq: None,
911 color: None,
912 transform: None,
913 fit: FitPolicy::default(),
914 speed: Speed::NORMAL,
915 };
916 Self {
917 // A file is opened on its first audio stream: nothing has picked
918 // one yet, and every file with audio at all has that one.
919 sources: vec![Source::new(path, 0)],
920 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
921 eq: Vec::new(),
922 color: Vec::new(),
923 transform: Vec::new(),
924 history: Vec::new(),
925 redo: Vec::new(),
926 next_link: 1,
927 subtitles: Vec::new(),
928 limiter: Limiter::default(),
929 tone: crate::tonemap::Preset::default(),
930 }
931 }
932
933 /// A project rebuilt from a saved edit list -- the load half of
934 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
935 /// an `ord` is a lane's position among the lanes of that kind, exactly as
936 /// [`Project::lanes`] hands them back. History is *not* saved, so
937 /// [`Project::undo`] is `false` until the first edit of the new session.
938 /// This is the one door untrusted parts come in through, so every invariant
939 /// every other constructor keeps is checked here, by name and in release:
940 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
941 /// or a colour) that is not there, a clip whose end overflows, a lane that is
942 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
943 /// below.
944 ///
945 /// A project whose lanes are all *empty* is not among them: an emptied
946 /// timeline is a project like any other -- it plays black and silent, it
947 /// saves, and it loads back. What a project cannot be is laneless, because
948 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
949 /// handle indexes into.
950 pub fn from_parts(
951 sources: Vec<Source>,
952 lanes: Vec<(LaneKind, Vec<Clip>)>,
953 eq: Vec<EqParams>,
954 color: Vec<ColorParams>,
955 transform: Vec<TransformParams>,
956 ) -> crate::Result<Self> {
957 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
958 return Err(format!("eq {bad} holds a band that is not a finite number").into());
959 }
960 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
961 return Err(format!("color {bad} holds a value that is not a finite number").into());
962 }
963 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
964 return Err(format!("transform {bad} holds a value that is not a finite number").into());
965 }
966 if lanes.is_empty() {
967 return Err("no lanes at all: that is not a project".into());
968 }
969 let lanes: Vec<LaneData> = lanes
970 .into_iter()
971 .map(|(kind, clips)| LaneData::new(kind, clips))
972 .collect();
973 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
974 let name = lane.label();
975 // A subtitle lane carries words and never a picture
976 // ([`LaneKind::Subtitle`]); a file that puts one there names a
977 // source on a lane that has nothing to play it with, and every
978 // media path below would then read a clip off a lane it does not
979 // know about.
980 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
981 return Err(format!(
982 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
983 data.clips.len()
984 )
985 .into());
986 }
987 for c in &data.clips {
988 if c.out_frame <= c.in_frame {
989 return Err(format!(
990 "{name} clip at {} plays the empty range [{}, {})",
991 c.start, c.in_frame, c.out_frame
992 )
993 .into());
994 }
995 if c.source >= sources.len() {
996 return Err(format!(
997 "{name} clip at {} names source {} of {}",
998 c.start,
999 c.source,
1000 sources.len()
1001 )
1002 .into());
1003 }
1004 if c.start.checked_add(c.frames()).is_none() {
1005 return Err(format!(
1006 "{name} clip at {} runs past the last frame there is",
1007 c.start
1008 )
1009 .into());
1010 }
1011 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1012 return Err(format!(
1013 "{name} clip at {} names eq {} of {}",
1014 c.start,
1015 c.eq.unwrap_or_default(),
1016 eq.len()
1017 )
1018 .into());
1019 }
1020 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1021 return Err(format!(
1022 "{name} clip at {} names color {} of {}",
1023 c.start,
1024 c.color.unwrap_or_default(),
1025 color.len()
1026 )
1027 .into());
1028 }
1029 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
1030 return Err(format!(
1031 "{name} clip at {} names transform {} of {}",
1032 c.start,
1033 c.transform.unwrap_or_default(),
1034 transform.len()
1035 )
1036 .into());
1037 }
1038 }
1039 if !sorted_disjoint(&data.clips) {
1040 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1041 }
1042 }
1043 links_are_consistent(&lanes)?;
1044 // The counter sits past every id the file names, on either of a lane's
1045 // lists: a v16 caption may carry the highest link there is, and a
1046 // re-issued id would silently group it with the next placement that
1047 // asks for one -- the loader refusing a save the editor just wrote.
1048 let next_link = lanes
1049 .iter()
1050 .flat_map(|l| {
1051 let clips = l.clips.iter().filter_map(|c| c.link);
1052 let subs = l.subs.iter().filter_map(|s| s.link);
1053 clips.chain(subs)
1054 })
1055 .max()
1056 // Saturating so a crafted file cannot make the counter wrap: at the
1057 // ceiling ids stop being fresh, which loses grouping, not memory.
1058 .map_or(0, |m| m.saturating_add(1));
1059 Ok(Self {
1060 sources: sources
1061 .iter()
1062 .map(|s| Source::new(&s.path, s.audio_stream))
1063 .collect(),
1064 lanes,
1065 eq,
1066 color,
1067 transform,
1068 history: Vec::new(),
1069 redo: Vec::new(),
1070 next_link,
1071 subtitles: Vec::new(),
1072 limiter: Limiter::default(),
1073 tone: crate::tonemap::Preset::default(),
1074 })
1075 }
1076
1077 /// The first video lane -- what an export renders and what a single-lane
1078 /// caller still means by "the clips".
1079 pub fn clips(&self) -> &[Clip] {
1080 self.lane(Lane::V1)
1081 }
1082
1083 /// The clips of `lane`, or nothing at all for a lane that is not there.
1084 pub fn lane(&self, lane: Lane) -> &[Clip] {
1085 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1086 }
1087
1088 /// Every lane's handle, in display order -- what a walk over "all lanes"
1089 /// iterates, and what a front-end lays out top to bottom.
1090 pub fn lanes(&self) -> Vec<Lane> {
1091 handles(&self.lanes)
1092 }
1093
1094 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1095 /// for every `ord` below it, and none at or above it.
1096 pub fn lane_count(&self, kind: LaneKind) -> usize {
1097 self.lanes.iter().filter(|l| l.kind == kind).count()
1098 }
1099
1100 /// Appends an empty lane of `kind` and hands back its handle. One undo
1101 /// step, because the lane list is state a front-end shows: an added lane
1102 /// that could not be taken back would be the one edit with no way out.
1103 /// Nothing plays differently until something is placed on it.
1104 ///
1105 /// An empty lane is a lane like any other -- so is a whole project of them
1106 /// ([`Project::from_parts`]); nothing plays until something is placed.
1107 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1108 self.snapshot();
1109 self.lanes.push(LaneData::new(kind, Vec::new()));
1110 Lane::new(kind, self.lane_count(kind) - 1)
1111 }
1112
1113 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1114 /// one undo step like it, which restores the lane where it stood.
1115 ///
1116 /// Refused, changing nothing, while the lane holds anything: the refusal
1117 /// names the clips (file and first frame), because a track removal that
1118 /// deleted takes with it would be the one edit nobody sees coming. Refused
1119 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1120 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1121 /// kind and *skips* a kind that is not there), so a project without one
1122 /// would swallow half of every file dropped on it, silently.
1123 ///
1124 /// The lanes below it move up one `ord`, so a handle a caller was holding
1125 /// (a selection, an open card) names the lane after it from here on -- the
1126 /// one thing a front-end owes this call.
1127 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1128 let Some(i) = self.index(lane) else {
1129 return Err(format!("there is no {} to remove", lane.label()).into());
1130 };
1131 // A subtitle lane is not in that rule: nothing lands on one by itself
1132 // -- a project starts without any and one is added when a caption is --
1133 // so the last of them comes off like any other empty track.
1134 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1135 return Err(format!(
1136 "{} is the only {} track: every import lands on it",
1137 lane.label(),
1138 match lane.kind {
1139 LaneKind::Video => "video",
1140 LaneKind::Audio => "audio",
1141 // Unreachable while the guard above lets the last subtitle
1142 // lane go, and its own word here so the sentence stays true
1143 // if that rule is ever relaxed.
1144 LaneKind::Subtitle => "subtitle",
1145 }
1146 )
1147 .into());
1148 }
1149 if !self.lanes[i].subs.is_empty() {
1150 // Three names and a count, exactly as the clips below get: the way
1151 // out of the refusal is the drag, so the words say so.
1152 let named: Vec<String> = self.lanes[i]
1153 .subs
1154 .iter()
1155 .take(3)
1156 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1157 .collect();
1158 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1159 0 => String::new(),
1160 n => format!(" and {n} more"),
1161 };
1162 return Err(format!(
1163 "{} still holds {}{rest}: delete those captions (or drag them to \
1164 another track) first",
1165 lane.label(),
1166 named.join(", ")
1167 )
1168 .into());
1169 }
1170 let clips = &self.lanes[i].clips;
1171 if !clips.is_empty() {
1172 // Three names and a count: a lane can hold forty clips and a
1173 // refusal nobody reads to the end says nothing at all.
1174 let named: Vec<String> = clips
1175 .iter()
1176 .take(3)
1177 .map(|c| {
1178 let name = self.sources.get(c.source).map_or_else(
1179 || format!("source {}", c.source),
1180 |s| s.path.display().to_string(),
1181 );
1182 format!("{name} at frame {}", c.start)
1183 })
1184 .collect();
1185 let rest = match clips.len().saturating_sub(named.len()) {
1186 0 => String::new(),
1187 n => format!(" and {n} more"),
1188 };
1189 return Err(format!(
1190 "{} still holds {}{rest}: delete those clips (or drag them to \
1191 another track) first",
1192 lane.label(),
1193 named.join(", ")
1194 )
1195 .into());
1196 }
1197 self.snapshot();
1198 self.lanes.remove(i);
1199 Ok(())
1200 }
1201
1202 /// Moves `lane` to display position `to` -- an index into
1203 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1204 /// the handle it answers to from now on. `None`, changing nothing and
1205 /// snapshotting nothing, for a lane that is not there, a position that is
1206 /// not, and a lane already standing in it.
1207 ///
1208 /// The whole track travels: its clips, its gain, its kind. Nothing is
1209 /// remapped, so no take changes lane and no group is broken -- this is the
1210 /// *order* of the lanes and nothing else, which is why one call is one undo
1211 /// step like an add or a removal.
1212 ///
1213 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1214 /// last video lane covering a frame, so moving one video lane past another
1215 /// changes which picture wins, in the preview and in an export alike. The
1216 /// audio lanes are summed and their sum does not care about order, so an
1217 /// audio track moved among the video ones is a rearrangement of the screen
1218 /// alone.
1219 ///
1220 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1221 /// position among the lanes of that kind), so a lane that crosses one of
1222 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1223 /// `V1`, clips and all -- while one that crosses only lanes of the other
1224 /// kind keeps its name. That is the returned handle: unchanged means every
1225 /// handle a caller holds still names the track it named before.
1226 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1227 let i = self.index(lane)?;
1228 if to >= self.lanes.len() || to == i {
1229 return None;
1230 }
1231 self.snapshot();
1232 let data = self.lanes.remove(i);
1233 self.lanes.insert(to, data);
1234 Some(handles(&self.lanes)[to])
1235 }
1236
1237 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1238 /// not there. The one place a handle becomes a position.
1239 fn index(&self, lane: Lane) -> Option<usize> {
1240 self.lanes
1241 .iter()
1242 .enumerate()
1243 .filter(|(_, l)| l.kind == lane.kind)
1244 .map(|(i, _)| i)
1245 .nth(lane.ord)
1246 }
1247
1248 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1249 let i = self.index(lane)?;
1250 Some(&mut self.lanes[i].clips)
1251 }
1252
1253 /// The files the clips index into, in import order; index 0 is the file the
1254 /// project was opened with.
1255 pub fn sources(&self) -> &[Source] {
1256 &self.sources
1257 }
1258
1259 /// The same list in the `(path, stream)` shape the audio engine indexes
1260 /// into -- [`crate::AudioSession::open_multi_streams`] and
1261 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1262 /// was placed with is the stream that plays *and* the stream that exports.
1263 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1264 self.sources
1265 .iter()
1266 .map(|s| (s.path.clone(), s.audio_stream))
1267 .collect()
1268 }
1269
1270 /// Index for `path` played on `audio_stream`, appending it if it is new.
1271 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1272 /// by two paths imports once and two streams of one file are two sources.
1273 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1274 /// no history: a source entry alone changes nothing playable.
1275 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1276 let source = Source::new(path, audio_stream);
1277 match self.sources.iter().position(|s| *s == source) {
1278 Some(idx) => idx,
1279 None => {
1280 self.sources.push(source);
1281 self.sources.len() - 1
1282 }
1283 }
1284 }
1285
1286 /// Append a whole-file clip of `source` to the end of every *media* lane,
1287 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1288 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1289 /// come in through [`Project::add_subtitles`], which is the palette.
1290 ///
1291 /// One history snapshot, so an import is one undo step, and undoing it
1292 /// leaves the (harmless) source entry behind, because indexes are forever.
1293 /// Refused for an unknown source index.
1294 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1295 if source >= self.sources.len() {
1296 return false;
1297 }
1298 self.snapshot();
1299 let start = self.timeline_frames();
1300 let clip = Clip {
1301 fade_in: 0,
1302 fade_out: 0,
1303 transition_out: 0,
1304 start,
1305 in_frame: 0,
1306 out_frame: frame_count.max(1),
1307 source,
1308 link: Some(self.new_link()),
1309 eq: None,
1310 color: None,
1311 transform: None,
1312 fit: FitPolicy::default(),
1313 speed: Speed::NORMAL,
1314 };
1315 for data in self
1316 .lanes
1317 .iter_mut()
1318 .filter(|l| l.kind != LaneKind::Subtitle)
1319 {
1320 data.clips.push(clip);
1321 }
1322 true
1323 }
1324
1325 /// Drops a source entry -- the file a library row *is* -- and renumbers
1326 /// every clip that indexed past it, which is why this is more than a
1327 /// `Vec::remove`.
1328 ///
1329 /// Refused, changing nothing, while any clip still plays from it: the
1330 /// refusal names the lanes and how many clips each holds, so a caller can
1331 /// say what has to be deleted first. The *last* entry goes like any other
1332 /// -- a project may name no file at all, which is an empty library over an
1333 /// empty timeline (nothing can play, since a clip would have refused the
1334 /// removal). What a front-end does with that is its own decision: `edith`'s
1335 /// window goes back to the empty state it launches in, and
1336 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1337 /// refuses to write a project that names nothing, because no such file
1338 /// could be opened again.
1339 ///
1340 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1341 /// source index of its own -- a clipboard, which is the one thing outside
1342 /// this type that does -- has to fix it up or drop it, or a paste plays a
1343 /// different file. [`PlaybackSession::remove_source`] hands back the index
1344 /// that went for exactly that.
1345 ///
1346 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1347 /// snapshot older than the removal can name the very source being removed
1348 /// (delete a file's clips, then remove the file) and restoring it would
1349 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1350 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1351 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1352 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1353 /// exists) currently rules out.
1354 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1355 let Some(source) = self.sources.get(idx) else {
1356 return Err(format!("there is no source {idx} to remove").into());
1357 };
1358 let name = source.path.display().to_string();
1359 let used: Vec<String> = handles(&self.lanes)
1360 .into_iter()
1361 .zip(&self.lanes)
1362 .filter_map(
1363 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1364 0 => None,
1365 1 => Some(format!("{} (1 clip)", lane.label())),
1366 n => Some(format!("{} ({n} clips)", lane.label())),
1367 },
1368 )
1369 .collect();
1370 if !used.is_empty() {
1371 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1372 }
1373 self.sources.remove(idx);
1374 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1375 if c.source > idx {
1376 c.source -= 1;
1377 }
1378 }
1379 self.history.clear();
1380 Ok(())
1381 }
1382
1383 /// The sources a clip actually names, with the clips reindexed onto them
1384 /// -- what a save writes. Indexes are forever *inside* a session (see
1385 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1386 /// entry behind; writing that orphan to a project file would let a file
1387 /// nothing plays refuse a future load. New indexes are assigned in order of
1388 /// first use -- lane by lane, in display order -- so the same project always
1389 /// emits the same bytes.
1390 ///
1391 /// Every lane comes out, in display order and with its kind: that is what a
1392 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1393 /// takes back.
1394 ///
1395 /// The equalizer and colour tables are pruned the same way and for the same
1396 /// reason: an undone [`set_eq`](Project::set_eq) or
1397 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1398 /// and this is the one moment they can go -- the indexes that survive it are
1399 /// only the ones a clip names.
1400 ///
1401 /// One exception, and it is the emptied timeline's: a project no clip plays
1402 /// from still keeps its first source, if it has one. A file is what a
1403 /// reopened project scaffolds itself from -- the frame rate is written
1404 /// nowhere else -- so a save that pruned the last of them would write a
1405 /// project that cannot be loaded back at all.
1406 ///
1407 /// What comes out is *not* ordered by anything a reader may assume: first
1408 /// use, lane by lane, means the entry at index 0 can be a still or a song
1409 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1410 /// picks its rate and its audio reference by what a source *is*, never by
1411 /// where it sits.
1412 pub fn without_orphan_sources(&self) -> Parts {
1413 let mut moved = vec![None; self.sources.len()];
1414 let mut sources = Vec::new();
1415 let mut moved_eq = vec![None; self.eq.len()];
1416 let mut eq = Vec::new();
1417 let mut moved_color = vec![None; self.color.len()];
1418 let mut color = Vec::new();
1419 let mut moved_transform = vec![None; self.transform.len()];
1420 let mut transform = Vec::new();
1421 let mut lanes = self.lanes.clone();
1422 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1423 let old = c.source;
1424 c.source = match moved[old] {
1425 Some(new) => new,
1426 None => {
1427 sources.push(self.sources[old].clone());
1428 moved[old] = Some(sources.len() - 1);
1429 sources.len() - 1
1430 }
1431 };
1432 if let Some(old) = c.eq.map(usize::from) {
1433 c.eq = Some(match moved_eq[old] {
1434 Some(new) => new,
1435 None => {
1436 eq.push(self.eq[old].clone());
1437 let new = (eq.len() - 1) as u16;
1438 moved_eq[old] = Some(new);
1439 new
1440 }
1441 });
1442 }
1443 if let Some(old) = c.color.map(usize::from) {
1444 c.color = Some(match moved_color[old] {
1445 Some(new) => new,
1446 None => {
1447 color.push(self.color[old]);
1448 let new = (color.len() - 1) as u16;
1449 moved_color[old] = Some(new);
1450 new
1451 }
1452 });
1453 }
1454 if let Some(old) = c.transform.map(usize::from) {
1455 c.transform = Some(match moved_transform[old] {
1456 Some(new) => new,
1457 None => {
1458 transform.push(self.transform[old]);
1459 let new = (transform.len() - 1) as u16;
1460 moved_transform[old] = Some(new);
1461 new
1462 }
1463 });
1464 }
1465 }
1466 if sources.is_empty() {
1467 sources.extend(self.sources.first().cloned());
1468 }
1469 (
1470 sources,
1471 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1472 // comes out for one is an empty list, and its *place* in the display
1473 // order is what a save writes it for. What is on it travels beside
1474 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1475 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1476 eq,
1477 color,
1478 transform,
1479 )
1480 }
1481
1482 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1483 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1484 /// track moves by it, which is what makes it a different control from a
1485 /// clip's equalizer (one frequency range of one take) and from the master
1486 /// volume (what this machine monitors at, which no file carries).
1487 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1488 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1489 }
1490
1491 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1492 /// One undo step like every other edit -- it is in the lane list, so an
1493 /// undo restores it with the rest. `false`, and no history, for a lane that
1494 /// is not there, for a value that is not finite, and for one already set.
1495 ///
1496 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1497 /// a value nobody reads: words have no loudness, so a slider that appeared
1498 /// to move one would be a control with no effect. (A video lane's gain is
1499 /// meaningless in the same way but is kept settable: it is the pair `A1`
1500 /// carries for a take, and mixing reads it off the audio lane alone.)
1501 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1502 let Some(i) = self.index(lane) else {
1503 return false;
1504 };
1505 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1506 return false;
1507 }
1508 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1509 if self.lanes[i].gain_db == db {
1510 return false;
1511 }
1512 self.snapshot();
1513 self.lanes[i].gain_db = db;
1514 true
1515 }
1516
1517 /// Every lane's volume in dB, in display order -- what a save writes,
1518 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1519 ///
1520 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1521 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1522 /// one): a save zips the two lists, so a lane that is in one and not the
1523 /// other would hand every track below it the volume of the track above.
1524 pub fn lane_gains(&self) -> Vec<f32> {
1525 self.lanes.iter().map(|l| l.gain_db).collect()
1526 }
1527
1528 /// What is placed on every lane, in display order and in step with
1529 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1530 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1531 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1532 ///
1533 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1534 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1535 /// clip's source there is no orphan to prune and no index to move.
1536 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1537 self.lanes.iter().map(|l| l.subs.clone()).collect()
1538 }
1539
1540 /// The placements a *load* puts back, one list per lane in display order --
1541 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1542 /// same reason. Called *after*
1543 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1544 /// names.
1545 ///
1546 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1547 /// like it, by name and in release, because it is the same untrusted file:
1548 /// a placement on a lane that is not a subtitle lane, an empty span or an
1549 /// empty window, a track the palette does not have, a span running past the
1550 /// last frame there is, and a lane that is out of order or overlaps itself
1551 /// ([`place_sub`] refuses every one of those on the live timeline).
1552 ///
1553 /// [`place_sub`]: Project::place_sub
1554 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1555 let names = handles(&self.lanes);
1556 let palette = self.subtitles.len();
1557 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1558 let name = lane.label();
1559 if list.is_empty() {
1560 continue;
1561 }
1562 if data.kind != LaneKind::Subtitle {
1563 return Err(format!(
1564 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1565 subtitle track",
1566 list.len()
1567 )
1568 .into());
1569 }
1570 for s in &list {
1571 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1572 return Err(format!(
1573 "{name} caption at {} is empty: {} frames of [{}, {})",
1574 s.start, s.frames, s.in_us, s.out_us
1575 )
1576 .into());
1577 }
1578 if s.track >= palette {
1579 return Err(format!(
1580 "{name} caption at {} names subtitle track {} of {palette}",
1581 s.start, s.track
1582 )
1583 .into());
1584 }
1585 if s.start.checked_add(s.frames).is_none() {
1586 return Err(format!(
1587 "{name} caption at {} runs past the last frame there is",
1588 s.start
1589 )
1590 .into());
1591 }
1592 }
1593 if !subs_sorted_disjoint(&list) {
1594 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1595 }
1596 data.subs = list;
1597 // The counter also has to clear the ids these captions carry: this
1598 // is the door a load's placements come through, *after*
1599 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1600 // a hand-grouped caption may carry the highest id in the file.
1601 self.next_link = self.next_link.max(
1602 data.subs
1603 .iter()
1604 .filter_map(|s| s.link)
1605 .max()
1606 .map_or(0, |m| m.saturating_add(1)),
1607 );
1608 }
1609 Ok(self)
1610 }
1611
1612 /// The mix settings a *load* puts back: lane volumes in display order (a
1613 /// short list leaves the rest at unity) and the master limiter, both
1614 /// clamped as their setters clamp them.
1615 ///
1616 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1617 /// setters push an undo step, and a project that arrives one undo away from
1618 /// a state it was never in is a project whose first ctrl+z is a surprise.
1619 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1620 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1621 if db.is_finite() {
1622 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1623 }
1624 }
1625 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1626 self
1627 }
1628
1629 /// The HDR rendition a *load* puts back -- the same door
1630 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1631 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1632 self.tone = preset;
1633 self
1634 }
1635
1636 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1637 /// project setting, not a clip's: one picture, one look
1638 /// ([`crate::tonemap::Preset`]).
1639 pub fn tone(&self) -> crate::tonemap::Preset {
1640 self.tone
1641 }
1642
1643 /// Sets it. `false` for the one already in force, which is what keeps a
1644 /// re-pick of the current rendition from costing a reseek.
1645 ///
1646 /// corner-cut: not an undo step, for the reason the limiter and the project
1647 /// resolution are not -- it is not in the lane list the history snapshots.
1648 /// Upgrade path is the same one: a history entry holding the project's own
1649 /// settings beside the lanes.
1650 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1651 if self.tone == preset {
1652 return false;
1653 }
1654 self.tone = preset;
1655 true
1656 }
1657
1658 /// The subtitle tracks a *load* puts back, in the order they were saved --
1659 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1660 /// the same reason.
1661 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1662 self.subtitles = tracks;
1663 self
1664 }
1665
1666 /// What this timeline shows over the picture, in the order they were added:
1667 /// what a front-end lists and what a save writes.
1668 pub fn subtitles(&self) -> &[SubtitleTrack] {
1669 &self.subtitles
1670 }
1671
1672 /// Adds a track, unless the very same one -- same file, same track number
1673 /// inside it -- is already on the list. `false` for that repeat: importing
1674 /// the same `.srt` twice is one subtitle track, not two identical ones.
1675 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1676 if self
1677 .subtitles
1678 .iter()
1679 .any(|t| t.path == track.path && t.track == track.track)
1680 {
1681 return false;
1682 }
1683 self.subtitles.push(track.clone());
1684 true
1685 }
1686
1687 /// Takes the track at `idx` off the list -- what a row's own remove goes
1688 /// through, so whatever an import added can be taken back out. Refused by
1689 /// name for a row this project does not have, rather than a silent no-op:
1690 /// a front-end holding a stale index has picked the wrong row and needs to
1691 /// hear it.
1692 ///
1693 /// Every index past `idx` moves down by one, as [`remove_source`](
1694 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1695 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1696 /// it, or it names a different track afterwards. The placements on the
1697 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1698 /// index into this very list, so every one past `idx` is walked down with
1699 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1700 /// for its clips, for its reason.
1701 ///
1702 /// Refused, changing nothing, while anything placed on a subtitle lane
1703 /// plays *this* row: the placement would have to be deleted or retargeted,
1704 /// and either one is an edit nobody asked for. The refusal names the lane
1705 /// and the frame it is at, up to three of them --
1706 /// [`remove_source`](Project::remove_source) refuses the same way for the
1707 /// same silent corruption.
1708 ///
1709 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1710 /// history snapshots hold the lane list and subtitles are not on it
1711 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1712 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1713 /// door, which reads the subtitles of a file and nothing else -- and not a
1714 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1715 /// entry holding the project's own settings beside the lanes. The history
1716 /// is *cleared* rather than kept, as a source removal clears it: the
1717 /// snapshots hold the indexes as they were before the reindex, so an undo
1718 /// into one would put every placement past `idx` on the wrong track.
1719 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1720 if idx >= self.subtitles.len() {
1721 return Err(format!("there is no subtitle track {idx} to remove").into());
1722 }
1723 let placed: Vec<String> = handles(&self.lanes)
1724 .into_iter()
1725 .zip(&self.lanes)
1726 .flat_map(|(lane, data)| {
1727 data.subs
1728 .iter()
1729 .filter(move |s| s.track == idx)
1730 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1731 })
1732 .take(3)
1733 .collect();
1734 if !placed.is_empty() {
1735 return Err(format!(
1736 "{} is on the timeline ({}): delete those clips first",
1737 self.track_name(idx),
1738 placed.join(", ")
1739 )
1740 .into());
1741 }
1742 self.subtitles.remove(idx);
1743 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1744 if s.track > idx {
1745 s.track -= 1;
1746 }
1747 }
1748 self.history.clear();
1749 Ok(())
1750 }
1751
1752 /// What a refusal calls a palette row: the name the panel shows, and the
1753 /// index alone for a row that is not there.
1754 fn track_name(&self, track: usize) -> String {
1755 self.subtitles
1756 .get(track)
1757 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1758 }
1759
1760 /// The subtitle lanes in display order -- what a front-end lays out and
1761 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1762 /// [`audio_lanes`](Project::audio_lanes).
1763 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1764 self.lanes()
1765 .into_iter()
1766 .filter(|l| l.kind == LaneKind::Subtitle)
1767 .collect()
1768 }
1769
1770 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1771 /// for a subtitle track, and empty for every other lane and for one that is
1772 /// not there.
1773 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1774 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1775 }
1776
1777 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1778 /// twin, with one deliberate difference: it **refuses** an overlap instead
1779 /// of overwriting what it lands on.
1780 ///
1781 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1782 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1783 /// carries is a *window of a track* and where the hand let go, and the
1784 /// second of those is the argument. So a caller builds the placement once
1785 /// (from the palette row it dragged) and drops it at as many frames as it
1786 /// likes without rewriting the field each time.
1787 ///
1788 /// A picture placed over a picture hides it and the hidden one is still
1789 /// there to drag back out; two captions in one frame are two lines nobody
1790 /// asked to stack, and the words that lost are gone from the screen with
1791 /// nothing to show for it. So the refusal names the placement in the way,
1792 /// and the caller picks another frame or another lane -- which is what a
1793 /// second subtitle lane is for.
1794 ///
1795 /// One undo step on success, and none on any refusal: an empty window or an
1796 /// empty span, a track the palette does not have
1797 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1798 /// subtitle lane, a span that would run past the last frame there is, and
1799 /// the overlap above.
1800 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1801 if lane.kind != LaneKind::Subtitle {
1802 return Err(format!(
1803 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1804 the others",
1805 lane.label()
1806 )
1807 .into());
1808 }
1809 let Some(i) = self.index(lane) else {
1810 return Err(format!("there is no {} to place on", lane.label()).into());
1811 };
1812 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1813 return Err(format!(
1814 "that placement is empty: {} frames of [{}, {})",
1815 sub.frames, sub.in_us, sub.out_us
1816 )
1817 .into());
1818 }
1819 if sub.track >= self.subtitles.len() {
1820 return Err(format!(
1821 "it names subtitle track {} of {}",
1822 sub.track,
1823 self.subtitles.len()
1824 )
1825 .into());
1826 }
1827 // The placement belongs to no group, for [`place`]'s reason: a caption
1828 // dragged out of the palette arrives alone, and grouping it with what
1829 // is under it is a hand's decision ([`Project::group_all`]).
1830 let sub = SubClip {
1831 start: at,
1832 link: None,
1833 ..sub
1834 };
1835 if at.checked_add(sub.frames).is_none() {
1836 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1837 }
1838 if let Some(other) = self.lanes[i]
1839 .subs
1840 .iter()
1841 .find(|o| o.end() > sub.start && o.start < sub.end())
1842 {
1843 return Err(format!(
1844 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1845 on another subtitle track",
1846 lane.label(),
1847 other.start,
1848 other.start,
1849 other.end()
1850 )
1851 .into());
1852 }
1853 self.snapshot();
1854 let subs = &mut self.lanes[i].subs;
1855 let idx = subs.partition_point(|o| o.start < sub.start);
1856 subs.insert(idx, sub);
1857 debug_assert!(subs_sorted_disjoint(subs));
1858 Ok(())
1859 }
1860
1861 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1862 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1863 /// refused an overlap where that one clamps to it, for
1864 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1865 /// still and no picture under it that a landing would hide, so "as far as
1866 /// it goes" would silently be a frame nobody named.
1867 ///
1868 /// A caption *in* a group drags the group: one delta for every member --
1869 /// its clips and its other captions -- clamped to the room each of them
1870 /// has, exactly as a clip's drag always has. That is the point of putting
1871 /// a caption in a group: the words go where the picture goes.
1872 ///
1873 /// The window travels untouched: a caption dragged later says the same
1874 /// words later, exactly as a clip dragged later plays the same pictures
1875 /// later.
1876 ///
1877 /// One undo step on success; nothing changed and no step on a refusal --
1878 /// an index that is not there, a lane that is not a subtitle lane or is not
1879 /// there, and (for a caption in no group) an overlap. A drop that changes
1880 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1881 /// up and put it back has done nothing wrong, and a front-end showing every
1882 /// `Err` would say so.
1883 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1884 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1885 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1886 };
1887 if to.kind != LaneKind::Subtitle {
1888 return Err(format!(
1889 "{} is not a subtitle track: a caption cannot play on it",
1890 to.label()
1891 )
1892 .into());
1893 }
1894 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1895 return Err(format!("there is no {} to move onto", to.label()).into());
1896 };
1897 if (here, start) == (dest, sub.start) {
1898 // A pick-up-put-back: the drag ended where it began, which is not a
1899 // mistake to name -- `Ok`, and no undo step, because nothing
1900 // changed. A refusal here would toast a hand that did nothing.
1901 return Ok(());
1902 }
1903 if start.checked_add(sub.frames).is_none() {
1904 return Err(
1905 format!("a placement at frame {start} runs past the last frame there is").into(),
1906 );
1907 }
1908 // A grouped caption carries its group, clamped to the room the whole
1909 // group has rather than refused ([`Project::move_room]) -- one drag, one
1910 // delta, one undo step.
1911 let members = self.group_of(from, idx).expect("the subtitle was found");
1912 if !members.alone() {
1913 if members
1914 .subs
1915 .iter()
1916 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1917 {
1918 return Err(format!(
1919 "a group is one caption per track: {} already carries this group",
1920 to.label()
1921 )
1922 .into());
1923 }
1924 let want = i64::from(start) - i64::from(sub.start);
1925 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1926 return Err(format!(
1927 "another placement already covers those frames on {}",
1928 to.label()
1929 )
1930 .into());
1931 };
1932 let delta = want.clamp(lo, hi);
1933 self.snapshot();
1934 for &(l, i) in &members.clips {
1935 let c = &mut self.lanes[l].clips[i];
1936 c.start = (i64::from(c.start) + delta) as u32;
1937 }
1938 for &(l, i) in &members.subs {
1939 let s = &mut self.lanes[l].subs[i];
1940 s.start = (i64::from(s.start) + delta) as u32;
1941 }
1942 let moved = self.lanes[here].subs.remove(idx);
1943 let subs = &mut self.lanes[dest].subs;
1944 let at = subs.partition_point(|o| o.start < moved.start);
1945 subs.insert(at, moved);
1946 debug_assert!(subs_sorted_disjoint(subs));
1947 debug_assert!(members
1948 .clips
1949 .iter()
1950 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1951 return Ok(());
1952 }
1953 let moved = SubClip { start, ..sub };
1954 if let Some(other) = self.lanes[dest]
1955 .subs
1956 .iter()
1957 .enumerate()
1958 .find(|&(j, o)| {
1959 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1960 })
1961 .map(|(_, o)| *o)
1962 {
1963 return Err(format!(
1964 "the {} subtitle at frame {} already covers [{}, {})",
1965 to.label(),
1966 other.start,
1967 other.start,
1968 other.end()
1969 )
1970 .into());
1971 }
1972 self.snapshot();
1973 self.lanes[here].subs.remove(idx);
1974 let subs = &mut self.lanes[dest].subs;
1975 let at = subs.partition_point(|o| o.start < moved.start);
1976 subs.insert(at, moved);
1977 debug_assert!(subs_sorted_disjoint(subs));
1978 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
1979 Ok(())
1980 }
1981
1982 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
1983 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
1984 /// pulling an edge past what is legal means "as far as it goes".
1985 ///
1986 /// The window follows the edge, in the seconds the frames are worth at
1987 /// `fps`: a head pulled in starts the caption later *in its track* (the
1988 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
1989 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
1990 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
1991 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
1992 /// needed here and nowhere else in this file, because a trim is the only
1993 /// edit that changes a *duration*.
1994 ///
1995 /// The walls: one frame always survives, an edge never crosses the
1996 /// neighbouring subtitle on its own lane, a head never walks back past the
1997 /// track's own start (`in_us` of 0), and a tail never runs past the last
1998 /// cue the track has -- which is the source length a media trim needs a
1999 /// caller's table for, and which this one can simply read.
2000 ///
2001 /// `Err`, with nothing changed and no undo step, for an index that is not
2002 /// there and an unusable `fps`. An edge that ends up where it already was
2003 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2004 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2005 /// reason: a drag that stops at a wall is not a mistake to report.
2006 pub fn trim_sub(
2007 &mut self,
2008 lane: Lane,
2009 idx: usize,
2010 edge: Edge,
2011 to: u32,
2012 fps: f64,
2013 ) -> crate::Result<()> {
2014 if !(fps.is_finite() && fps > 0.0) {
2015 return Err(format!("{fps} is not a frame rate to trim against").into());
2016 }
2017 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2018 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2019 };
2020 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2021 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2022 };
2023 let to = to.clamp(lo, hi);
2024 let at = match edge {
2025 Edge::Start => sub.start,
2026 Edge::End => sub.end(),
2027 };
2028 if to == at {
2029 // The edge is where it was asked to go -- either the hand did not
2030 // move it, or the clamp above stopped it at a wall it was already
2031 // standing against. Both are a drag that changed nothing: `Ok`, no
2032 // undo step, and no toast for a box that simply stopped moving.
2033 return Ok(());
2034 }
2035 self.snapshot();
2036 let members = self.group_of(lane, idx).expect("the subtitle was found");
2037 let i = self.index(lane).expect("the subtitle was found on it");
2038 let s = &mut self.lanes[i].subs[idx];
2039 match edge {
2040 // The words that stay are the words that were there, so the window
2041 // moves with the head -- a trim, not a slip.
2042 Edge::Start => {
2043 // Clamped to a window that is still a window: the walls above
2044 // are frames and the rounding between the two clocks is not
2045 // exact, and neither is a caller's hand-built placement.
2046 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2047 .clamp(0, s.out_us - 1);
2048 s.frames = s.end() - to;
2049 s.start = to;
2050 }
2051 Edge::End => {
2052 s.out_us =
2053 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2054 s.frames = to - s.start;
2055 }
2056 }
2057 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2058 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2059 // A caption in a group drags its group's edge with it, exactly as a
2060 // clip's trim does: one delta, each member clamped to its own room.
2061 // No source table to grow by, which only tightens how far a member may
2062 // follow -- never whether it may.
2063 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
2064 Ok(())
2065 }
2066
2067 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2068 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2069 /// drawing the box during a drag asks. `None` for an index that is not
2070 /// there.
2071 pub fn trim_sub_room(
2072 &self,
2073 lane: Lane,
2074 idx: usize,
2075 edge: Edge,
2076 fps: f64,
2077 ) -> Option<(u32, u32)> {
2078 let subs = self.sub_lane(lane);
2079 let s = *subs.get(idx)?;
2080 // How many timeline frames a stretch of the track is worth, which is
2081 // what turns its two walls -- its own start, and its last cue -- into
2082 // frames. A rate that is not a rate leaves the window where it is.
2083 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2084 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
2085 false => 0,
2086 };
2087 Some(match edge {
2088 Edge::Start => (
2089 s.start
2090 .saturating_sub(frames_of(s.in_us))
2091 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2092 s.end() - 1,
2093 ),
2094 Edge::End => {
2095 // Out to the end of the track it reads, and never over the
2096 // subtitle behind it. A track the palette no longer has (or one
2097 // with no cues at all) may not grow, exactly as a source with no
2098 // entry in a media trim's table may not.
2099 let track_end = self
2100 .subtitles
2101 .get(s.track)
2102 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2103 .unwrap_or(s.out_us);
2104 (
2105 s.start + 1,
2106 s.start
2107 .saturating_add(frames_of(track_end - s.in_us).max(1))
2108 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2109 )
2110 }
2111 })
2112 }
2113
2114 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2115 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2116 /// `false` for an index that is not there (which a lane that is not a
2117 /// subtitle lane always is).
2118 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2119 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2120 return false;
2121 };
2122 self.snapshot();
2123 self.lanes[i].subs.remove(idx);
2124 true
2125 }
2126
2127 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2128 /// window of its track, clipped to that window and shifted to where the
2129 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2130 /// carried through the picture's spans -- this is its twin for a track that
2131 /// is placed on a lane of its own, and it is what a preview draws and what
2132 /// an export of the lane would write.
2133 ///
2134 /// Cut, not stretched: a cue half inside the window keeps the half that is
2135 /// inside, and a cue wholly outside it is gone -- the same rule the media
2136 /// spans follow. `fps` is the timeline's rate, needed here because a
2137 /// placement's *position* is in frames while its words are in microseconds.
2138 ///
2139 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2140 /// of their cues, no file opened), which is how a front-end asks it.
2141 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2142 if !(fps.is_finite() && fps > 0.0) {
2143 return Vec::new();
2144 }
2145 let mut out = Vec::new();
2146 for s in self.sub_lane(lane) {
2147 let Some(track) = self.subtitles.get(s.track) else {
2148 // A placement whose track was taken off the palette
2149 // ([`Project::remove_subtitles`]) shows nothing rather than
2150 // showing another track's words.
2151 continue;
2152 };
2153 // Where the placement's own first microsecond lands on the
2154 // timeline, and how many microseconds of timeline one microsecond
2155 // of the window is worth: the placement's own proportion, which a
2156 // group's re-rate changes (the frames compress, the window does
2157 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2158 // every cue lands where it always did; at 2x the words cross the
2159 // screen in half the time, cue for cue.
2160 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2161 let onto = |t: i64| {
2162 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2163 };
2164 for cue in &track.cues {
2165 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2166 if b <= a {
2167 continue; // wholly outside the window this placement keeps
2168 }
2169 out.push(SubtitleCue {
2170 start_us: onto(a),
2171 end_us: onto(b),
2172 text: cue.text.clone(),
2173 image: cue.image.clone(),
2174 });
2175 }
2176 }
2177 // The placements come in timeline order, but two lanes' worth (or a
2178 // track whose cues a window reordered) do not.
2179 out.sort_by_key(|cue| cue.start_us);
2180 out
2181 }
2182
2183 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2184 /// lanes is multiplied by on its way into the mix: the same lanes in the
2185 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2186 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2187 /// the bit-exact path.
2188 pub fn audio_gains(&self) -> Vec<f32> {
2189 self.audio_lanes()
2190 .into_iter()
2191 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2192 .collect()
2193 }
2194
2195 /// The master limiter the mix is summed through. A project setting, not a
2196 /// clip's and not a lane's: there is one mix.
2197 pub fn limiter(&self) -> Limiter {
2198 self.limiter
2199 }
2200
2201 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2202 /// for a setting already in force.
2203 ///
2204 /// corner-cut: not an undo step, for the reason the project resolution is not
2205 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2206 /// lane list the history snapshots. Upgrade path is a history entry that
2207 /// holds the mix settings beside the lanes.
2208 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2209 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2210 if self.limiter == limiter {
2211 return false;
2212 }
2213 self.limiter = limiter;
2214 true
2215 }
2216
2217 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2218 /// plays flat (and for an index that is not there) -- what a feeder and an
2219 /// export ask before they build an [`crate::eq::EqState`].
2220 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2221 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2222 }
2223
2224 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2225 /// take them off. One undo step, like every other edit. `false` -- and no
2226 /// history -- for an index that is not there and for params holding a value
2227 /// that is not finite, which is the one thing the file format could not
2228 /// write and read back.
2229 ///
2230 /// Settings equal to ones already in the table share their entry, so a
2231 /// project that puts the same curve on twenty clips writes it once.
2232 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2233 if idx >= self.lane(lane).len() {
2234 return false;
2235 }
2236 let slot = match params {
2237 None => None,
2238 Some(params) => {
2239 if !finite(&params) {
2240 return false;
2241 }
2242 Some(match self.eq.iter().position(|p| *p == params) {
2243 Some(at) => at as u16,
2244 // corner-cut: the table is append-only within a session (see
2245 // the module docs) and `Clip::eq` is a u16, so the 65535th
2246 // *distinct* setting of one session is refused rather than
2247 // silently aliased. Upgrade path if a UI ever drags a slider
2248 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2249 // snapshot the table into the history and compact it here.
2250 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2251 None => {
2252 self.eq.push(params);
2253 (self.eq.len() - 1) as u16
2254 }
2255 })
2256 }
2257 };
2258 self.snapshot();
2259 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2260 true
2261 }
2262
2263 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2264 /// ungraded (and for an index that is not there) -- what the renderer and
2265 /// the export ask before they call [`crate::color::apply_yuv`].
2266 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2267 self.color
2268 .get(usize::from(self.lane(lane).get(idx)?.color?))
2269 }
2270
2271 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2272 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2273 /// (and no history) for an index that is not there or a value that is not
2274 /// finite, and equal settings share a table entry.
2275 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2276 self.write_color(lane, idx, params, true)
2277 }
2278
2279 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2280 /// one pointer drag, whose first write (a plain `set_color`) already took the
2281 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2282 /// not one per pixel -- and undoing it lands where the hand picked it up.
2283 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2284 self.write_color(lane, idx, params, false)
2285 }
2286
2287 fn write_color(
2288 &mut self,
2289 lane: Lane,
2290 idx: usize,
2291 params: Option<ColorParams>,
2292 snapshot: bool,
2293 ) -> bool {
2294 if idx >= self.lane(lane).len() {
2295 return false;
2296 }
2297 let slot = match params {
2298 None => None,
2299 Some(params) => {
2300 if !color_finite(&params) {
2301 return false;
2302 }
2303 Some(match self.color.iter().position(|p| *p == params) {
2304 Some(at) => at as u16,
2305 // corner-cut: the 65535th *distinct* grade of one session is
2306 // refused rather than silently aliased, exactly as `set_eq`
2307 // refuses the 65535th curve; same upgrade path.
2308 None if self.color.len() >= usize::from(u16::MAX) => return false,
2309 None => {
2310 self.color.push(params);
2311 (self.color.len() - 1) as u16
2312 }
2313 })
2314 }
2315 };
2316 if snapshot {
2317 self.snapshot();
2318 }
2319 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2320 true
2321 }
2322
2323 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2324 /// policy's own placement (and for an index that is not there) -- what the
2325 /// renderer and the export ask before they place its picture.
2326 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2327 self.transform
2328 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2329 }
2330
2331 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2332 /// step, `false` (and no history) for an index that is not there or a
2333 /// value that is not finite, and equal settings share a table entry.
2334 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2335 self.write_transform(lane, idx, params, true)
2336 }
2337
2338 /// [`set_transform`](Self::set_transform) without the undo step, for
2339 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2340 /// one drag on a position/scale/rotate/crop control are one undo, not one
2341 /// per pixel.
2342 pub fn set_transform_live(
2343 &mut self,
2344 lane: Lane,
2345 idx: usize,
2346 params: Option<TransformParams>,
2347 ) -> bool {
2348 self.write_transform(lane, idx, params, false)
2349 }
2350
2351 fn write_transform(
2352 &mut self,
2353 lane: Lane,
2354 idx: usize,
2355 params: Option<TransformParams>,
2356 snapshot: bool,
2357 ) -> bool {
2358 if idx >= self.lane(lane).len() {
2359 return false;
2360 }
2361 let slot = match params {
2362 None => None,
2363 Some(params) => {
2364 if !transform_finite(&params) {
2365 return false;
2366 }
2367 Some(match self.transform.iter().position(|p| *p == params) {
2368 Some(at) => at as u16,
2369 // corner-cut: the 65535th *distinct* transform of one
2370 // session is refused rather than silently aliased,
2371 // exactly as `write_color` refuses the 65535th grade;
2372 // same upgrade path.
2373 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2374 None => {
2375 self.transform.push(params);
2376 (self.transform.len() - 1) as u16
2377 }
2378 })
2379 }
2380 };
2381 if snapshot {
2382 self.snapshot();
2383 }
2384 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2385 true
2386 }
2387
2388 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2389 /// index that is not there, which is what every clip starts at anyway.
2390 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2391 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2392 }
2393
2394 /// Sets it, for the clip **and its whole group**: a link is one span on
2395 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2396 /// from its sound would be a group no save could load. One snapshot, so the
2397 /// group's change is one [`Project::undo`].
2398 ///
2399 /// The source range is untouched -- a speed says how many timeline frames
2400 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2401 /// split still address the file afterwards.
2402 ///
2403 /// Refused, changing nothing and costing no undo step, when the clip would
2404 /// grow into the one after it on its own lane: slowing a clip down makes it
2405 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2406 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2407 /// something a user can go and fix. Also for an index that is not there.
2408 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2409 self.write_speed(lane, idx, speed, true)
2410 }
2411
2412 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2413 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2414 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2415 /// not one per rate it passed through -- exactly as
2416 /// [`set_color_live`](Self::set_color_live) is for a slider.
2417 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2418 self.write_speed(lane, idx, speed, false)
2419 }
2420
2421 fn write_speed(
2422 &mut self,
2423 lane: Lane,
2424 idx: usize,
2425 speed: Speed,
2426 snapshot: bool,
2427 ) -> crate::Result<()> {
2428 let Some(members) = self.group_of(lane, idx) else {
2429 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2430 };
2431 let labels = handles(&self.lanes);
2432 // The clip the hand is holding is the group's clock: everything else
2433 // in the group, caption members included, re-times by the ratio its new
2434 // rate gives its own frames. The clips take the rate itself; a caption
2435 // has none, so it takes the *ratio* -- its span on the timeline
2436 // compresses or stretches about the held clip's head, while the words
2437 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2438 // timeline moves, the track does not).
2439 let Some(held) = self.lane(lane).get(idx).copied() else {
2440 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2441 };
2442 // The same per-member piece `speeded_playhead` builds for this op,
2443 // asked here instead of read there -- a caption's length comes from
2444 // the map's own ends (`end - start`), never `round(len * ratio)`
2445 // separately, which is what let the two answers drift apart by a
2446 // frame.
2447 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2448 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2449 let retimed = |s: SubClip| {
2450 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2451 let start = map.apply(s.start);
2452 let end = map.apply(s.end()).max(start.saturating_add(1));
2453 SubClip { start, frames: end - start, ..s }
2454 };
2455 for &(l, i) in &members.clips {
2456 let clips = &self.lanes[l].clips;
2457 let mut moved = clips[i];
2458 moved.speed = speed;
2459 if let Some(next) = clips.get(i + 1)
2460 && moved.end() > next.start
2461 {
2462 let name = labels[l].label();
2463 return Err(format!(
2464 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2465 move it along, or trim this one first",
2466 moved.end(),
2467 next.start
2468 )
2469 .into());
2470 }
2471 }
2472 // ...and the captions, against their own lanes' captions: a stretch
2473 // that runs one into its neighbour is refused for the clip arm's
2474 // reason -- a lane may not overlap itself -- and by name like it.
2475 let subs: Vec<(usize, usize, SubClip)> = members
2476 .subs
2477 .iter()
2478 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2479 .collect();
2480 for &(l, i, moved) in &subs {
2481 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2482 if j != i && moved.start < other.end() && other.start < moved.end() {
2483 return Err(format!(
2484 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2485 starts at {}: move it along, or trim this one first",
2486 labels[l].label(),
2487 self.lanes[l].subs[i].start,
2488 moved.end(),
2489 other.start
2490 )
2491 .into());
2492 }
2493 }
2494 }
2495 if snapshot {
2496 self.snapshot();
2497 }
2498 for (l, i) in members.clips {
2499 self.lanes[l].clips[i].speed = speed;
2500 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2501 }
2502 for (l, i, moved) in subs {
2503 self.lanes[l].subs[i] = moved;
2504 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2505 }
2506 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2507 Ok(())
2508 }
2509
2510 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2511 /// playhead standing at `at` -- read off the geometry **before** the
2512 /// write, because the old ends are gone after it. The question a card
2513 /// asks as its bar moves: the picture under the cursor has to stay the
2514 /// picture under the cursor, or the scene changes with the rate.
2515 ///
2516 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2517 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2518 /// a clip member keeps its own start and re-fits its length at the new
2519 /// rate -- its **old** rate against the new one, which is what the bar's
2520 /// live samples ask about as much as a first press does; a caption
2521 /// member scales about the held clip's start by the held clip's own
2522 /// proportion; and a playhead outside every member's old extent stays
2523 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2524 /// (or the room a stretch takes) absorbs the difference, not the
2525 /// playhead. `None` for an index that is not there.
2526 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2527 let members = self.group_of(lane, idx)?;
2528 let held = self.lane(lane).get(idx).copied()?;
2529 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2530 for &(l, i) in members.clips.iter().chain(&members.subs) {
2531 let (span, map) = match self
2532 .lanes[l]
2533 .clips
2534 .get(i)
2535 .filter(|_| members.clips.contains(&(l, i)))
2536 {
2537 // The clip's own span, re-fitted at its own old rate: one
2538 // piece of the map, anchored where the clip itself is. The
2539 // new length is the same *source* frames at the new rate --
2540 // len divided by it, never multiplied.
2541 Some(c) => (
2542 (c.start, c.start + c.frames()),
2543 TimelineMap::piece(
2544 (c.start, c.start + c.frames()),
2545 (
2546 c.start,
2547 c.start + (c.len() as f64 / new).round() as u32,
2548 ),
2549 ),
2550 ),
2551 // The caption's span, scaled about the held clip's head by
2552 // the held clip's proportion -- the offset the group keeps.
2553 None => {
2554 let s = self.lanes[l].subs.get(i)?;
2555 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2556 (
2557 (s.start, s.end()),
2558 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2559 )
2560 }
2561 };
2562 // The piece owns only its own old span: outside it the playhead
2563 // is another member's question, or nobody's.
2564 if (span.0..span.1).contains(&at) {
2565 return Some(map.apply(at));
2566 }
2567 }
2568 Some(at)
2569 }
2570
2571 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2572 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2573 /// every clip starts at anyway.
2574 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2575 self.lane(lane)
2576 .get(idx)
2577 .map_or(FitPolicy::default(), |c| c.fit)
2578 }
2579
2580 /// Sets it. One undo step like every other edit, and `false` (with no
2581 /// history) for an index that is not there. Unlike an eq or a grade there is
2582 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2583 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2584 if idx >= self.lane(lane).len() {
2585 return false;
2586 }
2587 self.snapshot();
2588 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2589 true
2590 }
2591
2592 /// Timeline frames of ramp-up from silence at the start of the clip at
2593 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2594 /// that has none.
2595 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2596 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2597 }
2598
2599 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2600 /// can shrink a clip's audible middle to nothing but never ask for more
2601 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2602 /// and `false` (no history) for an index that is not there.
2603 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2604 if idx >= self.lane(lane).len() {
2605 return false;
2606 }
2607 self.snapshot();
2608 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2609 clip.fade_in = frames.min(clip.frames());
2610 true
2611 }
2612
2613 /// Timeline frames of ramp-down to silence at the end of the clip at
2614 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2615 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2616 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2617 }
2618
2619 /// Sets it. Same promises as [`Project::set_fade_in`].
2620 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2621 if idx >= self.lane(lane).len() {
2622 return false;
2623 }
2624 self.snapshot();
2625 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2626 clip.fade_out = frames.min(clip.frames());
2627 true
2628 }
2629
2630 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2631 /// into its successor, at its own end. `0` for an index that is not
2632 /// there, same as a clip that has none.
2633 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2634 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2635 }
2636
2637 /// Sets it, clamped to the clip's own length and to how many frames its
2638 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2639 /// visible middle to nothing but never ask for more than the two clips
2640 /// between them have. `false` -- no history -- unless `lane` is video,
2641 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2642 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2643 /// them. One undo step like [`Project::set_fade_out`].
2644 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2645 if lane.kind != LaneKind::Video {
2646 return false;
2647 }
2648 let clips = self.lane(lane);
2649 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2650 return false;
2651 };
2652 if a.end() != b.start {
2653 return false;
2654 }
2655 let cap = a.frames().min(b.frames());
2656 self.snapshot();
2657 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2658 true
2659 }
2660
2661 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2662 /// after it, over `frames` timeline frames: sets `idx`'s
2663 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2664 /// each clamped to its own clip's length. `false` -- no history -- unless
2665 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2666 /// adjacent: the second's [`Clip::start`] is exactly the first's
2667 /// [`Clip::end`], no gap between them.
2668 ///
2669 /// This is the whole mechanism, not a stand-in for one: a *real*
2670 /// cross-fade -- both takes heard at once, blending -- is what two clips
2671 /// **overlapping** on separate lanes already get for free from the
2672 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2673 /// This call only shapes the edges of two clips already sitting
2674 /// end-to-end on *one* lane, so the join between them fades like one did.
2675 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2676 if lane.kind != LaneKind::Audio {
2677 return false;
2678 }
2679 let clips = self.lane(lane);
2680 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2681 return false;
2682 };
2683 if a.end() != b.start {
2684 return false;
2685 }
2686 self.snapshot();
2687 let clips = self.lane_mut(lane).expect("checked above");
2688 clips[idx].fade_out = frames.min(clips[idx].frames());
2689 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2690 true
2691 }
2692
2693 /// Every frame number on every lane rewritten onto a timeline counted at
2694 /// another rate: `k` is old timeline frames per new one, `counts` is how
2695 /// long each source is on the *new* timeline (indexed as
2696 /// [`Project::sources`] is), and the edit survives as the same seconds of
2697 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2698 /// the edit list, and the only thing that touches the frame numbers without
2699 /// being an edit anyone made.
2700 ///
2701 /// Every position -- a clip's start and its end alike -- goes through the
2702 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2703 /// stays a gap, and a take's picture and its sound land on the same frame on
2704 /// their two lanes: no lane can drift against another. A clip is then only
2705 /// ever made to *fit* the room its own start and end mapped to, never to
2706 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2707 /// below is the backstop for the one case that could: a slow clip so short
2708 /// that no source range fits its new room at all).
2709 ///
2710 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2711 /// onto the new grid, so a rate picked, unpicked and picked again is within
2712 /// a frame of where it started rather than back at it. Upgrade path is
2713 /// keeping the edit list at one reference rate and conforming on the way
2714 /// out, which every frame number in this module would then be measured in.
2715 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2716 for lane in &mut self.lanes {
2717 let mut cursor = 0;
2718 for clip in &mut lane.clips {
2719 let start = k.timeline_at(clip.start).max(cursor);
2720 // The room its own end mapped to -- never zero, since a clip is
2721 // never empty even on a grid too coarse to hold it.
2722 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2723 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2724 // Its footage, held inside the file's new length: a clip whose
2725 // out-point was the last frame of its source must not come out
2726 // of this naming a frame past the end -- that is a project that
2727 // would not open again ([`crate::PlaybackSession::open_project`]
2728 // refuses one by name).
2729 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2730 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2731 clip.start = start;
2732 clip.in_frame = in_frame;
2733 clip.out_frame = in_frame + len;
2734 cursor = clip.end();
2735 }
2736 // A subtitle's *window* is in microseconds and a rate change moves
2737 // no seconds, so only where it sits is remapped -- through the same
2738 // [`Rate::timeline_at`] every clip boundary goes through, so a
2739 // caption still starts on the frame its picture does.
2740 let mut cursor = 0;
2741 for sub in &mut lane.subs {
2742 let start = k.timeline_at(sub.start).max(cursor);
2743 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2744 sub.start = start;
2745 cursor = sub.end();
2746 }
2747 }
2748 }
2749
2750 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2751 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2752 ///
2753 /// A subtitle lane counts like any other: a caption placed past the last
2754 /// picture holds the timeline open under it, exactly as an `A2` running
2755 /// past `V1` does, rather than being silently clipped away by the length
2756 /// ([`crate::export::timeline_cues`] clips cues to this).
2757 pub fn timeline_frames(&self) -> u32 {
2758 self.lanes
2759 .iter()
2760 .filter_map(|l| match l.kind {
2761 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2762 _ => l.clips.last().map(Clip::end),
2763 })
2764 .max()
2765 .unwrap_or(0)
2766 }
2767
2768 /// The same, counting the *media* alone: where the last picture or sound
2769 /// runs out, with the captions over them ignored.
2770 ///
2771 /// What an export actually writes ends here -- the picture loop walks the
2772 /// composite spans and the file stops with them -- so this is the length a
2773 /// cue has to be inside of to be written at all (what
2774 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2775 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2776 /// thing is a picture or a sound, which is every timeline that has no
2777 /// caption hanging past the end of both.
2778 pub fn media_frames(&self) -> u32 {
2779 self.lanes
2780 .iter()
2781 .filter(|l| l.kind != LaneKind::Subtitle)
2782 .filter_map(|l| l.clips.last().map(Clip::end))
2783 .max()
2784 .unwrap_or(0)
2785 }
2786
2787 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2788 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2789 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2790 self.lane_spans(Lane::V1)
2791 }
2792
2793 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2794 // Timeline frames, not source ones: a box on a lane is as wide as the
2795 // clip is long *there*, which a speed halves or quadruples.
2796 self.lane(lane)
2797 .iter()
2798 .map(|c| (c.start, c.frames()))
2799 .collect()
2800 }
2801
2802 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2803 /// and past the end -- [`Project::span_at`] is the version that tells those
2804 /// two apart.
2805 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2806 let clips = self.lane(lane);
2807 let idx = at(clips, timeline_frame)?;
2808 Some((idx, source_frame(&clips[idx], timeline_frame)))
2809 }
2810
2811 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2812 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2813 self.map(Lane::V1, timeline_frame)
2814 }
2815
2816 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2817 /// it, or the gap running to the next clip (or to the end of the timeline,
2818 /// which is where a lane shorter than its neighbour keeps showing black).
2819 /// `None` at or past the end of the timeline, which is the only "nothing
2820 /// left" there is.
2821 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2822 let total = self.timeline_frames();
2823 if timeline_frame >= total {
2824 return None;
2825 }
2826 let clips = self.lane(lane);
2827 Some(match at(clips, timeline_frame) {
2828 Some(idx) => Span {
2829 start: timeline_frame,
2830 len: clips[idx].end() - timeline_frame,
2831 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2832 speed: clips[idx].speed,
2833 },
2834 None => Span {
2835 start: timeline_frame,
2836 speed: Speed::NORMAL,
2837 // The next placement, or the end of the timeline: a gap is
2838 // bounded by what comes after it, never by its own bookkeeping.
2839 len: clips
2840 .iter()
2841 .find(|c| c.start > timeline_frame)
2842 .map_or(total, |c| c.start)
2843 - timeline_frame,
2844 from: None,
2845 },
2846 })
2847 }
2848
2849 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2850 /// gaps included -- the whole play list, which is what an export walks.
2851 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2852 let mut out = Vec::new();
2853 let mut t = timeline_frame;
2854 while let Some(span) = self.span_at(lane, t) {
2855 t = span.end();
2856 out.push(span);
2857 }
2858 out
2859 }
2860
2861 /// What the *composite* shows from `timeline_frame` on -- the answer
2862 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2863 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2864 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2865 /// (the usual overlay convention). A frame no video lane covers is a gap,
2866 /// which is black however many lanes are above or below it.
2867 ///
2868 /// No blending, so exactly one lane is visible at a time and the composite
2869 /// is itself a span list -- which is why one decoder plays it, the same one
2870 /// a single-lane timeline uses, rather than N running at once.
2871 ///
2872 /// The span is cut short wherever a *higher* lane's clip starts, because
2873 /// from that frame on a different lane wins; that is what makes walking
2874 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2875 ///
2876 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2877 /// lanes would then be visible in one frame and the caller needs a decoder
2878 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2879 /// (this same walk, per lane) feeding N decoders.
2880 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2881 let total = self.timeline_frames();
2882 if timeline_frame >= total {
2883 return None;
2884 }
2885 let video = self.video_lanes();
2886 // The last covering lane is the winner; only the lanes above it can
2887 // interrupt what it shows.
2888 let winner = video
2889 .iter()
2890 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2891 let (from, speed, until) = match winner {
2892 Some(i) => {
2893 let clips = self.lane(video[i]);
2894 let idx = at(clips, timeline_frame).expect("just found above");
2895 (
2896 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2897 clips[idx].speed,
2898 clips[idx].end(),
2899 )
2900 }
2901 // Nothing covers it: black until something above the floor starts.
2902 None => (None, Speed::NORMAL, total),
2903 };
2904 let takeover = video[winner.map_or(0, |i| i + 1)..]
2905 .iter()
2906 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2907 .map(|c| c.start)
2908 .min();
2909 Some(Span {
2910 start: timeline_frame,
2911 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2912 from,
2913 speed,
2914 })
2915 }
2916
2917 /// The video lanes in display order, topmost last -- the order the composite
2918 /// rule counts in.
2919 fn video_lanes(&self) -> Vec<Lane> {
2920 self.lanes()
2921 .into_iter()
2922 .filter(|l| l.kind == LaneKind::Video)
2923 .collect()
2924 }
2925
2926 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2927 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2928 /// index on that lane. `None` over a gap and past the end. What a front-end
2929 /// asks to act on "the clip on screen" without re-deriving the rule.
2930 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2931 let video = self.video_lanes();
2932 let winner = video
2933 .iter()
2934 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2935 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2936 }
2937
2938 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2939 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2940 /// answers "the clip on screen"; this answers it per lane, which is what
2941 /// walking the lanes for something to select needs.
2942 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2943 at(self.lane(lane), timeline_frame)
2944 }
2945
2946 /// How the composite is graded at `timeline_frame`, so the picture playback
2947 /// converts and the one an export encodes are graded from one answer.
2948 /// `None` over a gap (black is black) and for a clip nobody has graded,
2949 /// which is the byte-identical path everywhere.
2950 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2951 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2952 self.color_of(lane, idx)
2953 }
2954
2955 /// [`composite_color_at`](Self::composite_color_at)'s twin for
2956 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
2957 /// policy's own placement.
2958 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
2959 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2960 self.transform_of(lane, idx)
2961 }
2962
2963 /// How the composite meets the project canvas at `timeline_frame`, so the
2964 /// picture playback composes and the one an export encodes are placed from
2965 /// one answer. `Fit` over a gap, where black is already the canvas.
2966 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
2967 self.composite_clip_at(timeline_frame)
2968 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
2969 }
2970
2971 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
2972 /// viewer sees from `timeline_frame` to the end, in order. What an export
2973 /// encodes and what playback walks at a clip boundary.
2974 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
2975 let mut out = Vec::new();
2976 let mut t = timeline_frame;
2977 while let Some(span) = self.composite_span_at(t) {
2978 t = span.end();
2979 out.push(span);
2980 }
2981 out
2982 }
2983
2984 /// Split every lane at `timeline_frame`, so that frame becomes the first
2985 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
2986 /// (`false`, no change) when no lane has a clip to split there -- at a
2987 /// placement's own start, in a gap, and past the end -- all of which would
2988 /// produce an empty clip or nothing at all.
2989 ///
2990 /// Lanes' halves share an id only where they are the *same* span: the lanes
2991 /// are edited apart, so the clip being cut here may start (or end)
2992 /// somewhere else on another lane, and a group id whose clips disagree
2993 /// about their span is not one take (see [`links_are_consistent`], which
2994 /// refuses to load one).
2995 ///
2996 /// Metadata only: no mapping changes, in any lane.
2997 pub fn split(&mut self, timeline_frame: u32) -> bool {
2998 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
2999 }
3000
3001 /// [`split`](Project::split), with the snapshot optional and the lanes
3002 /// named: a batch that has already taken a snapshot
3003 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3004 /// region and must still be one undo press, and a *scoped* batch must not
3005 /// cut a lane it was told to leave alone.
3006 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3007 let cut: Vec<Option<Clip>> = self
3008 .lanes
3009 .iter()
3010 .enumerate()
3011 .map(|(i, l)| {
3012 on.contains(&i)
3013 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3014 .flatten()
3015 })
3016 .collect();
3017 // The same question on the subtitle lanes, in their own arithmetic: a
3018 // razor cuts the captions with the picture, and a frame where only a
3019 // caption can be cut is still a cut.
3020 let cut_subs: Vec<bool> = self
3021 .lanes
3022 .iter()
3023 .enumerate()
3024 .map(|(i, l)| {
3025 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
3026 })
3027 .collect();
3028 // The links the captions carry, read before the room is opened below
3029 // -- `sub_open_room` takes the id off both halves, exactly as
3030 // `open_room` does for a clip, and the split hands the halves theirs
3031 // back afterwards.
3032 let sub_orig: Vec<Option<u32>> = self
3033 .lanes
3034 .iter()
3035 .zip(&cut_subs)
3036 .map(|(l, &cut)| {
3037 cut.then(|| {
3038 l.subs
3039 .iter()
3040 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3041 .and_then(|s| s.link)
3042 })
3043 .flatten()
3044 })
3045 .collect();
3046 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3047 return false;
3048 }
3049 if snapshot {
3050 self.snapshot();
3051 }
3052 for (data, _) in self
3053 .lanes
3054 .iter_mut()
3055 .zip(&cut_subs)
3056 .filter(|&(_, &cut)| cut)
3057 {
3058 // A split is room of no width: the halves keep their windows by
3059 // proportion and nothing moves.
3060 sub_open_room(&mut data.subs, timeline_frame, 0);
3061 debug_assert!(subs_sorted_disjoint(&data.subs));
3062 }
3063 // Each side is its own question, and the answer is the group the clip
3064 // already carried: the left half *keeps* its take's id -- the take the
3065 // frames before the cut still are -- and the right halves of one take
3066 // share one fresh id of their own, clips and captions alike. A lane
3067 // holding no group (a `place`ment, a caption nobody grouped) comes out
3068 // of the cut holding none, which is what it went in with. The captions'
3069 // own links were drawn above, before the room opened.
3070 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3071 let mut distinct: Vec<u32> = Vec::new();
3072 for id in orig.iter().chain(&sub_orig).flatten() {
3073 if !distinct.contains(id) {
3074 distinct.push(*id);
3075 }
3076 }
3077 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3078 let right_of =
3079 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
3080 for (l, data) in self.lanes.iter_mut().enumerate() {
3081 if !cut_subs[l] {
3082 continue;
3083 }
3084 // The pair the razor just made: they touch at the frame it cut.
3085 if let Some(idx) = data
3086 .subs
3087 .iter()
3088 .position(|s| s.end() == timeline_frame)
3089 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
3090 {
3091 data.subs[idx].link = sub_orig[l];
3092 data.subs[idx + 1].link = right_of(sub_orig[l]);
3093 }
3094 }
3095 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3096 // The lanes this call was not scoped to are not cut, whatever their
3097 // own clips would allow.
3098 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
3099 continue;
3100 };
3101 let mut tail = data.clips[idx];
3102 // Where the cut lands *in the file*, which is the clip's own rate
3103 // away from where it lands on the timeline. Both halves keep the
3104 // speed, and `splittable` has already refused any frame at which
3105 // the two would not add up to the one being cut.
3106 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3107 tail.start = timeline_frame;
3108 tail.link = right_of(orig[data_i]);
3109 // A split makes a new edge for each half, and a fade is a promise
3110 // about an edge: only the half that *kept* the original edge
3111 // keeps that fade, re-clamped to its own now-shorter length (a
3112 // cut inside the ramp shortens it, never leaves it pointing past
3113 // the clip it is on); the edge the cut itself made starts, or
3114 // ends, flat -- there was no silence there to ramp out of.
3115 tail.fade_in = 0;
3116 tail.fade_out = tail.fade_out.min(tail.frames());
3117 // A dissolve is a promise about the *end* edge, same as
3118 // `fade_out`: only the half that kept the clip's original end
3119 // (the tail) keeps it, re-clamped to its own now-shorter length;
3120 // the head's new end is the cut the razor just made, which starts
3121 // flat -- there was no successor to dissolve into there.
3122 tail.transition_out = tail.transition_out.min(tail.frames());
3123 data.clips[idx].out_frame = tail.in_frame;
3124 data.clips[idx].link = orig[data_i];
3125 data.clips[idx].fade_out = 0;
3126 data.clips[idx].transition_out = 0;
3127 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3128 data.clips.insert(idx + 1, tail);
3129 }
3130 true
3131 }
3132
3133 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3134 /// at `timeline_frame` in every lane and put the result back in one group.
3135 /// Only what a split could have produced is rejoined -- the two sides must
3136 /// touch on the timeline *and* be consecutive frames of the same source --
3137 /// so the clip list comes back exactly as it was and traversal with it.
3138 /// `false` when no lane has such a pair. The rejoined placement keeps the
3139 /// **left** half's id, which is the take the split left on it: rejoining a
3140 /// cut take puts the take back, id and all.
3141 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3142 // What each lane would end up covering, if it joins here at all.
3143 let joined: Vec<Option<(u32, u32)>> = self
3144 .lanes
3145 .iter()
3146 .map(|l| {
3147 joinable(&l.clips, timeline_frame)
3148 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3149 })
3150 .collect();
3151 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3152 let join_subs: Vec<Option<usize>> = self
3153 .lanes
3154 .iter()
3155 .map(|l| sub_joinable(&l.subs, timeline_frame))
3156 .collect();
3157 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3158 return false;
3159 }
3160 self.snapshot();
3161 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3162 if let Some(idx) = sub {
3163 data.subs[idx].frames += data.subs[idx + 1].frames;
3164 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3165 data.subs.remove(idx + 1);
3166 debug_assert!(subs_sorted_disjoint(&data.subs));
3167 }
3168 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3169 continue;
3170 };
3171 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3172 data.clips.remove(idx + 1);
3173 }
3174 true
3175 }
3176
3177 /// Take the placement at `idx` of `lane` out of its group: every clip and
3178 /// every caption carrying its id -- on however many lanes -- is handed an
3179 /// id of its own, so from here on each half moves, trims and is deleted
3180 /// alone. The music video whose sound is to be cut against its picture
3181 /// starts here, and so does the caption that has to come off the picture it
3182 /// was pinned to.
3183 ///
3184 /// An id of its own rather than none at all: a half no other lane is grouped
3185 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3186 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3187 /// as detached. `None` would instead say "was never part of a take", which
3188 /// is what a one-lane [`place`](Project::place) means.
3189 ///
3190 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3191 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3192 /// the group back. Refused (`false`, nothing changed) for an index that is
3193 /// not there, a placement in no group at all, and one whose group has no
3194 /// other half -- that one is already detached, and a refusal must not cost
3195 /// an undo step.
3196 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3197 let Some(members) = self.group_of(lane, idx) else {
3198 return false;
3199 };
3200 if members.alone() {
3201 return false;
3202 }
3203 let Some(id) = self
3204 .lane(lane)
3205 .get(idx)
3206 .and_then(|c| c.link)
3207 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3208 else {
3209 return false;
3210 };
3211 self.snapshot();
3212 // Drawn before the walk: `new_link` takes the whole project, and the
3213 // walk holds the lanes.
3214 let count = members.clips.len() + members.subs.len();
3215 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3216 for data in &mut self.lanes {
3217 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3218 c.link = fresh.pop();
3219 }
3220 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3221 s.link = fresh.pop();
3222 }
3223 }
3224 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3225 true
3226 }
3227
3228 /// Put two clips on two lanes into one group, so what moves one moves the
3229 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3230 /// how a picture is regrouped with sound it was never opened with. Whatever
3231 /// either of them was grouped with comes along: those clips cover this same
3232 /// span already, so the result is one group and not two overlapping ones.
3233 ///
3234 /// Same frames or nothing: a group id names **one span** on however many
3235 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3236 /// clips that do not cover the same frames cannot be one take, and the
3237 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3238 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3239 /// mean, not the rule.
3240 ///
3241 /// Metadata only, one snapshot. The error says what is wrong, because
3242 /// `false` would not: a bad index, one lane twice (a group is at most one
3243 /// clip per lane), spans that disagree, and a pair that is already one take
3244 /// -- nothing changes, and none of them costs an undo step.
3245 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3246 if a == b {
3247 return Err(format!(
3248 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3249 a.label()
3250 )
3251 .into());
3252 }
3253 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3254 p.lane(lane)
3255 .get(idx)
3256 .copied()
3257 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3258 };
3259 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3260 if (x.start, x.end()) != (y.start, y.end()) {
3261 return Err(format!(
3262 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3263 a.label(),
3264 x.start,
3265 x.end(),
3266 b.label(),
3267 y.start,
3268 y.end()
3269 )
3270 .into());
3271 }
3272 if x.link.is_some() && x.link == y.link {
3273 return Err("those two are one take already".into());
3274 }
3275 self.snapshot();
3276 let id = self.new_link();
3277 // Every clip either of them was grouped with, by the same rule: all of
3278 // them cover this span, so one id over the lot stays consistent.
3279 let old = [x.link, y.link];
3280 for data in &mut self.lanes {
3281 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3282 if old.contains(&c.link) {
3283 c.link = Some(id);
3284 }
3285 }
3286 }
3287 // And the two themselves, which a `place` may have left in no group.
3288 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3289 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3290 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3291 Ok(())
3292 }
3293
3294 /// Put every placement the picks name into one group -- the group a hand
3295 /// builds with ctrl-click and a menu: the picture, its sound and the
3296 /// caption over it, on as many lanes as the picks name. What any of them
3297 /// was already grouped with rides along (one group, not two sharing a
3298 /// member), and the members keep their own spans: a group is one id over
3299 /// one placement per lane, and the offsets between them are what the group
3300 /// preserves -- a drag, a trim and a delete all move the members *by the
3301 /// same distance*, not to the same frames.
3302 ///
3303 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3304 /// and the refusal says which lane -- and a pick that names nothing is
3305 /// refused with its own words. At least two picks, or there is nothing to
3306 /// group.
3307 ///
3308 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3309 /// apart again. None of the refusals changes anything or costs an undo
3310 /// step.
3311 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3312 if picks.len() < 2 {
3313 return Err("a group is two placements or more: pick another one first".into());
3314 }
3315 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3316 for &(lane, idx) in picks {
3317 if seen.contains(&lane) {
3318 return Err(format!(
3319 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3320 track",
3321 lane.label()
3322 )
3323 .into());
3324 }
3325 seen.push(lane);
3326 let there = if lane.kind == LaneKind::Subtitle {
3327 idx < self.sub_lane(lane).len()
3328 } else {
3329 idx < self.lane(lane).len()
3330 };
3331 if !there {
3332 let what = if lane.kind == LaneKind::Subtitle {
3333 "subtitle"
3334 } else {
3335 "clip"
3336 };
3337 return Err(
3338 format!("there is no {what} {idx} on {}", lane.label()).into()
3339 );
3340 }
3341 }
3342 let links: Vec<Option<u32>> = picks
3343 .iter()
3344 .map(|&(lane, idx)| {
3345 if lane.kind == LaneKind::Subtitle {
3346 self.sub_lane(lane)[idx].link
3347 } else {
3348 self.lane(lane)[idx].link
3349 }
3350 })
3351 .collect();
3352 // The picks are already one per lane (`seen`, above), but a pick's
3353 // *existing* group can carry a second member onto a lane another
3354 // pick (or another existing group in the merge) already occupies --
3355 // two captions on one sub lane, say, each grouped with a different
3356 // clip before this call. Merging both in would leave that lane with
3357 // two members of one id, which `links_are_consistent` may never see:
3358 // refused by name, before anything moves, rather than a group closed
3359 // broken.
3360 let labels = handles(&self.lanes);
3361 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3362 for (li, data) in self.lanes.iter().enumerate() {
3363 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3364 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3365 if n > 0 {
3366 per_lane.insert(li, n as u32);
3367 }
3368 }
3369 // A pick that carries no link of its own is invisible to the scan
3370 // above (there is no `Some` to match): it still claims its lane.
3371 for &(lane, _) in picks {
3372 let li = self.index(lane).expect("checked above");
3373 per_lane.entry(li).or_insert(0);
3374 if !self.lanes[li]
3375 .clips
3376 .iter()
3377 .any(|c| c.link.is_some() && links.contains(&c.link))
3378 && !self.lanes[li]
3379 .subs
3380 .iter()
3381 .any(|s| s.link.is_some() && links.contains(&s.link))
3382 {
3383 *per_lane.get_mut(&li).expect("just inserted") += 1;
3384 }
3385 }
3386 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3387 return Err(format!(
3388 "a group is one placement per lane: merging these groups would put two on {}",
3389 labels[li].label()
3390 )
3391 .into());
3392 }
3393 self.snapshot();
3394 let id = self.new_link();
3395 // Whatever any pick was grouped with comes along, for [`group`]'s
3396 // reason -- one id over the lot, not two groups sharing a member.
3397 for data in &mut self.lanes {
3398 for c in data.clips.iter_mut() {
3399 if c.link.is_some() && links.contains(&c.link) {
3400 c.link = Some(id);
3401 }
3402 }
3403 for s in data.subs.iter_mut() {
3404 if s.link.is_some() && links.contains(&s.link) {
3405 s.link = Some(id);
3406 }
3407 }
3408 }
3409 // And the picks themselves, which a `place` may have left in no group.
3410 // The lane seats are read before the walk, which holds the lanes.
3411 let seats: Vec<(usize, bool)> = picks
3412 .iter()
3413 .map(|&(lane, _)| {
3414 (
3415 self.index(lane).expect("checked above"),
3416 lane.kind == LaneKind::Subtitle,
3417 )
3418 })
3419 .collect();
3420 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3421 let _ = lane;
3422 if sub {
3423 self.lanes[at].subs[idx].link = Some(id);
3424 } else {
3425 self.lanes[at].clips[idx].link = Some(id);
3426 }
3427 }
3428 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3429 Ok(())
3430 }
3431
3432 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3433 /// lands on and leaving every other clip exactly where it is -- the
3434 /// per-lane paste. Anything already there is trimmed away (and split in two
3435 /// if `clip` lands inside it), which is what keeps the lane sorted and
3436 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3437 /// gap. Refused only for an empty `clip`.
3438 ///
3439 /// The placement belongs to no group: a clipboard clip carries the link id
3440 /// of the take it was copied from, and placing it twice -- or placing a copy
3441 /// back over the clip it came from -- would put that id on two clips of one
3442 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3443 /// `None` rather than a fresh id because a one-lane placement has nothing on
3444 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3445 /// become a group again.
3446 ///
3447 /// Refused for an empty `clip`, for a lane that is not there, and for a
3448 /// subtitle lane, which carries no picture and no sound
3449 /// ([`Project::place_sub`] is its door).
3450 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3451 if clip.out_frame <= clip.in_frame
3452 || lane.kind == LaneKind::Subtitle
3453 || self.index(lane).is_none()
3454 {
3455 return false;
3456 }
3457 self.snapshot();
3458 let clip = Clip {
3459 fade_in: 0,
3460 fade_out: 0,
3461 transition_out: 0,
3462 start: timeline_frame,
3463 link: None,
3464 ..clip
3465 };
3466 self.insert_over(lane, clip);
3467 true
3468 }
3469
3470 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3471 /// one grouped take -- what a picture let go over a further video track
3472 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3473 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3474 /// this half a file with sound landed on a layer silent, and the only way to
3475 /// hear it was to drop it a second time on an audio lane.
3476 ///
3477 /// Both halves overwrite what they land on and neither ripples, exactly as
3478 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3479 /// nothing under it moves. One history snapshot for the pair, the added lane
3480 /// included, so one [`Project::undo`] takes the whole placement back. The two
3481 /// carry one link, which is what makes them one take to a drag, a trim and a
3482 /// save.
3483 ///
3484 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3485 /// there or is not a video lane: sound placed alone is
3486 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3487 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3488 if clip.out_frame <= clip.in_frame
3489 || lane.kind != LaneKind::Video
3490 || self.index(lane).is_none()
3491 {
3492 return false;
3493 }
3494 self.snapshot();
3495 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3496 // an ord names a lane only while every ord below it does.
3497 while self.lane_count(LaneKind::Audio) <= lane.ord {
3498 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3499 }
3500 let clip = Clip {
3501 fade_in: 0,
3502 fade_out: 0,
3503 transition_out: 0,
3504 start: timeline_frame,
3505 link: Some(self.new_link()),
3506 ..clip
3507 };
3508 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3509 self.insert_over(half, clip);
3510 }
3511 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3512 true
3513 }
3514
3515 /// `clip` into `lane` at its own start, over whatever it lands on: the
3516 /// insert both placement doors make, which is what keeps a lane sorted and
3517 /// disjoint. The caller has checked that the lane is there.
3518 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3519 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3520 clear(clips, clip.start, clip.end());
3521 let idx = clips.partition_point(|c| c.start < clip.start);
3522 clips.insert(idx, clip);
3523 debug_assert!(sorted_disjoint(clips));
3524 }
3525
3526 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3527 /// frame `start`: the drag that rearranges takes, along a track and across
3528 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3529 /// was. `start` at the clip's own is the pure lane change.
3530 ///
3531 /// The whole group travels the same distance, each half on the lane it
3532 /// already sits on -- a link means "these cover one span on however many
3533 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3534 /// sound would be a group no save could load. Only the dragged half changes
3535 /// lane, and that is not a desync: a link names no lane at all.
3536 ///
3537 /// `start` is **clamped**, never refused, to the room the group has: no
3538 /// member crosses a neighbour on the lane it lands on, exactly as
3539 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3540 /// dragging past a neighbour means "as far as it goes", and butting up
3541 /// against the take next door is how clips are laid end to end. The
3542 /// tightest member's wall wins, so a sound half boxed in between two others
3543 /// holds its picture still.
3544 ///
3545 /// Refused, changing nothing and costing no undo step, for a lane that is
3546 /// not there, an index that is not there, a move across *kinds* (a picture
3547 /// cannot play on an audio lane, and the save it wrote would not open
3548 /// again), a head let go *inside* another clip or into a gap too narrow to
3549 /// hold this one -- a move that overwrote what it landed on would destroy a
3550 /// take the pointer never named, which is what [`place`](Project::place)
3551 /// may do and a drag may not -- a half let go onto the lane its own partner
3552 /// is on, and a drop that changes neither lane nor frame, which is a clip
3553 /// picked up and put back down, i.e. a click.
3554 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3555 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3556 return false;
3557 };
3558 if from.kind != to.kind {
3559 return false;
3560 }
3561 let members = self.group_of(from, idx).expect("the clip was found");
3562 let held = self.index(from).expect("the clip was found on it");
3563 // The two halves of one group would land on one span of one lane, which
3564 // is the one thing a link may never mean. Refused rather than clamped:
3565 // the partner moves the same distance, so there is no room for it
3566 // anywhere on that lane.
3567 if dest != held
3568 && members
3569 .clips
3570 .iter()
3571 .chain(&members.subs)
3572 .any(|&(l, _)| l == dest)
3573 {
3574 return false;
3575 }
3576 let want = i64::from(start) - i64::from(clip.start);
3577 // How far the group may travel, in timeline frames and signed: every
3578 // member -- the clips and any caption grouped with them -- narrows it
3579 // to the gap it is landing in, and what is left is what the pointer is
3580 // clamped to.
3581 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3582 return false;
3583 };
3584 if lo > hi {
3585 return false;
3586 }
3587 let delta = want.clamp(lo, hi);
3588 if delta == 0 && dest == held {
3589 return false;
3590 }
3591 self.snapshot();
3592 for &(l, i) in &members.clips {
3593 let c = &mut self.lanes[l].clips[i];
3594 // In range by the walls above, which are `u32` frames throughout.
3595 c.start = (i64::from(c.start) + delta) as u32;
3596 }
3597 for &(l, i) in &members.subs {
3598 let s = &mut self.lanes[l].subs[i];
3599 s.start = (i64::from(s.start) + delta) as u32;
3600 }
3601 if dest != held {
3602 let clip = self.lanes[held].clips.remove(idx);
3603 let clips = &mut self.lanes[dest].clips;
3604 let at = clips.partition_point(|c| c.start < clip.start);
3605 clips.insert(at, clip);
3606 }
3607 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3608 debug_assert!(members
3609 .clips
3610 .iter()
3611 .chain(&members.subs)
3612 .all(|&(l, _)| {
3613 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3614 }));
3615 true
3616 }
3617
3618 /// How far a group drag may travel, `(least, most)` in timeline frames and
3619 /// signed: every member narrows the range to the gap it is landing in --
3620 /// the clips against their lanes' clips and the captions against their
3621 /// lanes' captions -- and what is left is what the pointer is clamped to.
3622 /// `travelling` names the one member that changes lane, if any: the clip a
3623 /// hand is carrying onto another track, whose walls are read on the lane it
3624 /// is let go over at the frame the pointer named. `None` when a member has
3625 /// no gap to land in at all.
3626 fn move_room(
3627 &self,
3628 members: &Members,
3629 travelling: Option<(usize, usize, usize, u32)>,
3630 ) -> Option<(i64, i64)> {
3631 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3632 for &(l, i) in members.clips.iter().chain(&members.subs) {
3633 let sub = members.subs.contains(&(l, i));
3634 let (start, frames) = match self.lanes[l]
3635 .clips
3636 .get(i)
3637 .filter(|_| !sub)
3638 .map(|c| (c.start, c.frames()))
3639 {
3640 Some(pair) => pair,
3641 None => {
3642 let s = self.lanes[l].subs.get(i)?;
3643 (s.start, s.frames)
3644 }
3645 };
3646 let land = travelling
3647 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3648 .map_or(l, |(_, _, dest, _)| dest);
3649 // Which gap this member's walls are read off: its own place on the
3650 // lane it stays on, and the frame the pointer named on the lane it
3651 // is let go over. A clip's neighbours are the clips of the lane it
3652 // lands on and a caption's are its captions -- the two lists of one
3653 // lane never meet.
3654 let at = match travelling {
3655 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3656 _ => start,
3657 };
3658 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3659 let neighbours: Vec<(u32, u32)> = if sub {
3660 self.lanes[land]
3661 .subs
3662 .iter()
3663 .map(|s| (s.start, s.end()))
3664 .collect()
3665 } else {
3666 self.lanes[land]
3667 .clips
3668 .iter()
3669 .map(|c| (c.start, c.end()))
3670 .collect()
3671 };
3672 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3673 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3674 continue;
3675 }
3676 if *other_start <= at && at < *other_end {
3677 // A head let go inside another placement, which a clamp
3678 // has no answer for: the drop is refused.
3679 return None;
3680 }
3681 match other_end <= &at {
3682 true => wall_lo = wall_lo.max(*other_end),
3683 false => wall_hi = wall_hi.min(*other_start),
3684 }
3685 }
3686 if wall_hi - wall_lo < frames {
3687 return None;
3688 }
3689 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3690 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3691 }
3692 Some((lo, hi))
3693 }
3694
3695 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3696 /// the drag on a clip's end that makes it play more or less of its source.
3697 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3698 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3699 /// is room that was already empty. One snapshot, so a whole drag is one
3700 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3701 /// sample. Changes the timeline->source mapping: the caller must reseek.
3702 ///
3703 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3704 /// exactly what they played before, which is what makes this a trim and not
3705 /// a slip.
3706 ///
3707 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3708 /// legal means "as far as it goes", and stopping the box there is the
3709 /// affordance. The walls are: one frame of clip always survives, an edge
3710 /// never crosses the neighbouring clip on its own lane, an in-point never
3711 /// walks back past the source's first frame, and an out-point never runs
3712 /// past `source_frames[clip.source]` -- the caller's table of how long each
3713 /// source actually is ([`Project`] does not know, and a clip ending past its
3714 /// file's last frame is a save that will not open again; see
3715 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3716 /// there may not grow at all.
3717 ///
3718 /// Linked placements trim *together*, by one delta: every member's same
3719 /// edge moves the distance the dragged one did, clamped to the room its
3720 /// own walls leave -- offsets between the members of a hand-built group
3721 /// survive the trim, exactly as they survive a drag.
3722 ///
3723 /// `false`, changing nothing and costing no undo step, for an index that is
3724 /// not there and for an edge that is already where it was asked to go.
3725 pub fn trim(
3726 &mut self,
3727 lane: Lane,
3728 idx: usize,
3729 edge: Edge,
3730 to: u32,
3731 source_frames: &[u32],
3732 ) -> bool {
3733 let (Some((lo, hi)), Some(clip)) = (
3734 self.trim_room(lane, idx, edge, source_frames),
3735 self.lane(lane).get(idx).copied(),
3736 ) else {
3737 return false;
3738 };
3739 let to = to.clamp(lo, hi);
3740 let at = match edge {
3741 Edge::Start => clip.start,
3742 Edge::End => clip.end(),
3743 };
3744 if to == at {
3745 return false;
3746 }
3747 // Worked out before anything moves: at a slow rate a room can be too
3748 // narrow to hold even one source frame ([`Speed::fit`]), and the
3749 // dragged clip refusing to fit must refuse the whole gesture rather
3750 // than be given a range wider than its room -- which is the overlap
3751 // the lane invariant exists to forbid. The walls below leave that room,
3752 // so this is the backstop for a project that came in through another
3753 // door.
3754 let room = match edge {
3755 // The frames that stay play what they played, so what survives is
3756 // measured from the *end*.
3757 Edge::Start => clip.end() - to,
3758 Edge::End => to - clip.start,
3759 };
3760 let Some(keep) = clip.speed.fit(room) else {
3761 return false;
3762 };
3763 let members = self.group_of(lane, idx).expect("checked above");
3764 self.snapshot();
3765 let still = self.is_still(&clip);
3766 let held = self.index(lane).expect("checked above");
3767 let c = &mut self.lanes[held].clips[idx];
3768 match edge {
3769 // A still has no earlier frame to walk an in-point back to --
3770 // every frame of it is the same picture -- so its head grows
3771 // *forward*: the range it plays is however long the new room is,
3772 // anchored at the source's frame 0. Bounded by `lo`, which is where
3773 // the cap in `source_frames` is applied.
3774 Edge::Start if still => {
3775 c.in_frame = 0;
3776 c.out_frame = keep;
3777 c.start = to;
3778 }
3779 Edge::Start => {
3780 // Non-negative by `lo`, which is what keeps the in-point on the
3781 // source.
3782 c.in_frame = c.out_frame - keep.min(c.out_frame);
3783 c.start = to;
3784 }
3785 // Never wider than the room the edge was clamped to: see
3786 // [`Speed::fit`].
3787 Edge::End => c.out_frame = c.in_frame + keep,
3788 }
3789 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3790 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3791 true
3792 }
3793
3794 /// The rest of a group after one member's `edge` has moved by `delta`:
3795 /// every other member's same edge moves the same distance, clamped to the
3796 /// room its own walls leave -- a clip's against its lane and its source,
3797 /// a caption's against its own lane, its window following by the
3798 /// placement's own proportion. The undo step is the caller's: this is the
3799 // second half of one edit, not an edit of its own.
3800 fn follow_group(
3801 &mut self,
3802 members: &Members,
3803 dragged: &(usize, usize),
3804 edge: Edge,
3805 delta: i64,
3806 source_frames: &[u32],
3807 ) {
3808 for &(l, i) in &members.clips {
3809 if (l, i) == *dragged {
3810 continue;
3811 }
3812 let c = self.lanes[l].clips[i];
3813 let at = match edge {
3814 Edge::Start => c.start,
3815 Edge::End => c.end(),
3816 };
3817 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3818 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3819 if to == at {
3820 continue;
3821 }
3822 let room = match edge {
3823 Edge::Start => c.end() - to,
3824 Edge::End => to - c.start,
3825 };
3826 let Some(keep) = c.speed.fit(room) else {
3827 continue;
3828 };
3829 let still = self.is_still(&self.lanes[l].clips[i]);
3830 let c = &mut self.lanes[l].clips[i];
3831 match edge {
3832 Edge::Start if still => {
3833 c.in_frame = 0;
3834 c.out_frame = keep;
3835 c.start = to;
3836 }
3837 Edge::Start => {
3838 c.in_frame = c.out_frame - keep.min(c.out_frame);
3839 c.start = to;
3840 }
3841 Edge::End => c.out_frame = c.in_frame + keep,
3842 }
3843 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3844 }
3845 for &(l, i) in &members.subs {
3846 if (l, i) == *dragged {
3847 continue;
3848 }
3849 let s = self.lanes[l].subs[i];
3850 let at = match edge {
3851 Edge::Start => s.start,
3852 Edge::End => s.end(),
3853 };
3854 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3855 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3856 if to == at {
3857 continue;
3858 }
3859 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3860 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3861 }
3862 }
3863
3864 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3865 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3866 /// What a front-end drawing the box *during* a drag asks, so the live width
3867 /// is the width the release will commit and an edge stops under the pointer
3868 /// rather than snapping back. The **clip's own** walls: the rest of its
3869 /// group follows by the same delta within their own ([`follow_group`]), so
3870 /// what is drawn for the dragged edge is what its own clip will commit.
3871 /// `None` for an index that is not there.
3872 pub fn trim_room(
3873 &self,
3874 lane: Lane,
3875 idx: usize,
3876 edge: Edge,
3877 source_frames: &[u32],
3878 ) -> Option<(u32, u32)> {
3879 let l = self.index(lane)?;
3880 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3881 }
3882
3883 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3884 /// its lane's storage index: the one wall computation, asked for the clip
3885 /// itself and for each member a group trim carries.
3886 fn clip_room(
3887 &self,
3888 l: usize,
3889 i: usize,
3890 edge: Edge,
3891 source_frames: &[u32],
3892 ) -> (u32, u32) {
3893 let clips = &self.lanes[l].clips;
3894 let c = clips[i];
3895 let (lo, hi) = match edge {
3896 Edge::Start => (
3897 // Back to the source's own first frame -- as many *timeline*
3898 // frames as that head is worth at the clip's rate, which at
3899 // real time is the head itself -- and never over the clip in
3900 // front of it. Saturating because a clip may hold *more*
3901 // head than the timeline has room for -- a ripple delete
3902 // slides a clip back to frame 0 with its in-point wherever
3903 // the cut left it -- and frame 0 is the other wall.
3904 //
3905 // A still is measured from its *tail* instead: it has no
3906 // in-point worth the name (every frame the same picture), so
3907 // its head reaches exactly as far as its tail does -- out to
3908 // the length the caller's table gives it, whole. Measured
3909 // from the in-point it would have no head room at all, which
3910 // is a placed picture whose left edge cannot be dragged out.
3911 // No entry in the table means no growth, as it does at the
3912 // other end.
3913 if self.is_still(&c) {
3914 c.end().saturating_sub(
3915 c.speed
3916 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3917 )
3918 } else {
3919 c.start.saturating_sub(c.speed.room(c.in_frame))
3920 }
3921 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3922 // One *frame of clip* always survives, and at a rate below
3923 // real time one frame of clip is several frames of timeline
3924 // ([`Speed::room`]): an edge dragged closer than that would
3925 // ask for a range no source frame fits in. At real time this
3926 // is `end - 1`, unchanged.
3927 c.end() - c.speed.room(1),
3928 ),
3929 Edge::End => (
3930 // ...and the same wall from the other end: the shortest this
3931 // clip can be is the room one source frame of it takes.
3932 c.start + c.speed.room(1),
3933 // Out to whatever is left of the source -- again in timeline
3934 // frames, at this clip's rate -- and never over the clip
3935 // behind it.
3936 c.start
3937 .saturating_add(
3938 c.speed.room(
3939 source_frames
3940 .get(c.source)
3941 .copied()
3942 .unwrap_or(c.out_frame)
3943 .saturating_sub(c.in_frame),
3944 ),
3945 )
3946 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3947 ),
3948 };
3949 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3950 // contains the edge's own place, and a caller's wrong `source_frames`
3951 // must not become an empty range (or a panicking `clamp`) here.
3952 (lo, hi.max(lo))
3953 }
3954
3955 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
3956 /// every frame is the same picture, so which frame of it a clip's in-point
3957 /// names is not a question -- what [`Project::trim`] lets grow at either
3958 /// end. `false` for a source that is not there.
3959 fn is_still(&self, clip: &Clip) -> bool {
3960 self.sources
3961 .get(clip.source)
3962 .is_some_and(|s| crate::is_image(&s.path))
3963 }
3964
3965 /// The placements that move as one with the one at `idx` of `lane` --
3966 /// itself and whatever carries its link, on the media lanes and the
3967 /// subtitle ones alike. `None` for an index that is not there.
3968 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3969 let sub = lane.kind == LaneKind::Subtitle;
3970 let link = if sub {
3971 self.sub_lane(lane).get(idx)?.link
3972 } else {
3973 self.lane(lane).get(idx)?.link
3974 };
3975 let mut members = Members::default();
3976 match link {
3977 Some(link) => {
3978 for (l, data) in self.lanes.iter().enumerate() {
3979 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
3980 members.clips.push((l, i));
3981 }
3982 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
3983 members.subs.push((l, i));
3984 }
3985 }
3986 }
3987 None => {
3988 let l = self.index(lane).expect("the placement was found on it");
3989 if sub {
3990 members.subs.push((l, idx));
3991 } else {
3992 members.clips.push((l, idx));
3993 }
3994 }
3995 }
3996 Some(members)
3997 }
3998
3999 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4000 /// new group, pushing everything from there on later by its length in
4001 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4002 /// the clip it lands in is split around it; past the end of the timeline it
4003 /// goes down where it was asked for, with black in front of it -- which is
4004 /// what a library row let go on the open bed means, and what the ghost under
4005 /// the pointer promised. A clipboard means "put it here", not "here and
4006 /// black in front", and clamps to the end at its own door
4007 /// ([`crate::PlaybackSession::paste_at`]).
4008 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4009 ///
4010 /// `V1` and `A1` and no other lane, because a take is one picture and one
4011 /// sound: copying it onto every lane there is would play the same audio
4012 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4013 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4014 /// video lane it is a clip that decodes to nothing, and a save carrying one
4015 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4016 /// `V1` only, for the mirror of that reason. The room is still opened on
4017 /// every media lane, or the lanes it was not inserted into would slide out
4018 /// of step with the ones it was -- and the subtitle lanes are left alone:
4019 /// the words keep their own clock, and a caption that should travel with a
4020 /// clip is what a group is for.
4021 ///
4022 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4023 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4024 /// an empty `clip` and for one naming a source that is not there (both of
4025 /// which the public fields let a caller build), and for a paste whose ripple
4026 /// would push a clip past the last frame there is -- nothing is changed by
4027 /// any of them.
4028 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4029 let Some(source) = self.sources.get(clip.source) else {
4030 return false;
4031 };
4032 if clip.out_frame <= clip.in_frame {
4033 return false;
4034 }
4035 let audio_only = crate::is_audio(&source.path);
4036 // ...and its mirror: a still is a picture and no sound, so a copy of one
4037 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4038 // worker tries to demux -- which silences the *whole session*, not just
4039 // that clip -- and a save the engine's own `open_project` then refuses.
4040 let picture_only = crate::is_image(&source.path);
4041 // The frame it was asked for and no other: a row let go on the empty
4042 // bed past the last clip lands *there*, under the ghost that promised
4043 // it, with black in front. Clamping to the end here made every drop on
4044 // open bed an append -- the clipboard's rule, applied to a hand that
4045 // had named a place.
4046 let at = timeline_frame;
4047 // The room it takes on the timeline, which its speed decides -- not the
4048 // source range it reads.
4049 let len = clip.frames();
4050 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4051 // hand-written file may hold a clip that ends at the very last frame
4052 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4053 // rather than wrapped there -- a wrapped start lands *behind* the clip
4054 // it belongs after, which is an overlap no save will read back.
4055 if at.checked_add(len).is_none()
4056 || self
4057 .lanes
4058 .iter()
4059 .flat_map(|l| &l.clips)
4060 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4061 {
4062 return false;
4063 }
4064 // ...and room *to open*: the paste splits whatever it lands inside of,
4065 // and a speeded clip can only be cut where its own rate has a source
4066 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4067 // of one, which is the overlap a lane may never hold. At real time every
4068 // frame answers, so this cannot refuse an unspeeded paste.
4069 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4070 if self
4071 .lanes
4072 .iter()
4073 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4074 {
4075 return false;
4076 }
4077 self.snapshot();
4078 let clip = Clip {
4079 fade_in: 0,
4080 fade_out: 0,
4081 transition_out: 0,
4082 start: at,
4083 link: Some(self.new_link()),
4084 ..clip
4085 };
4086 // Only lanes that can play the source: a file with no picture belongs on
4087 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4088 // it for an import. On a video lane it would decode to nothing, and the
4089 // save it wrote would not open again.
4090 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4091 (true, _) => &[LaneKind::Audio],
4092 (_, true) => &[LaneKind::Video],
4093 _ => &[LaneKind::Video, LaneKind::Audio],
4094 };
4095 let takes: Vec<usize> = kinds
4096 .iter()
4097 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4098 .collect();
4099 for (i, data) in self.lanes.iter_mut().enumerate() {
4100 open_room(&mut data.clips, at, len);
4101 // The subtitle lanes are NOT touched: a paste inserts media, and
4102 // the words keep their own clock. Opening room here used to split
4103 // a caption the paste landed inside and slide the rest behind it
4104 // -- "a caption that stayed put while the picture moved on no
4105 // longer says the same thing" -- but a caption pinned to nothing
4106 // (and a video arriving on a timeline of words alone) has no
4107 // picture to follow, and the split did to the words what no hand
4108 // asked for. A caption that should travel with a clip is what a
4109 // group is for, and a group moves as one.
4110 if takes.contains(&i) {
4111 let idx = data.clips.partition_point(|c| c.start < at);
4112 data.clips.insert(idx, clip);
4113 }
4114 debug_assert!(sorted_disjoint(&data.clips));
4115 debug_assert!(subs_sorted_disjoint(&data.subs));
4116 }
4117 true
4118 }
4119
4120 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4121 /// silence, and nothing else moves. Refused only for an out-of-range index
4122 /// (which a lane that is not there always is) -- lifting the last placement
4123 /// there is leaves an *empty* timeline, which is a state the project holds
4124 /// like any other and an undo brings back.
4125 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4126 if idx >= self.lane(lane).len() {
4127 return false;
4128 }
4129 self.snapshot();
4130 self.lane_mut(lane).expect("checked above").remove(idx);
4131 true
4132 }
4133
4134 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4135 /// the hole: everything after slides back by `len`. The rippling delete --
4136 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4137 /// empty range; a delete that leaves nothing behind empties the timeline,
4138 /// which is a state like any other and one undo away.
4139 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4140 if len == 0 {
4141 return false;
4142 }
4143 // Nothing reaches past `at`: there is nothing to cut and nothing to
4144 // slide back, and a delete that changes nothing must not cost an undo
4145 // step (see [`snapshot`](Project::snapshot)).
4146 if !self
4147 .lanes
4148 .iter()
4149 .flat_map(|l| &l.clips)
4150 .any(|c| c.end() > at)
4151 {
4152 return false;
4153 }
4154 self.snapshot();
4155 let on = all_lanes(&self.lanes);
4156 ripple(&mut self.lanes, &on, at, len);
4157 true
4158 }
4159
4160 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4161 /// out of the lanes in `scope` and close each hole, as one edit: the
4162 /// jumpcut a silence scan asks for ([`crate::silence`]).
4163 ///
4164 /// A lane that is not in `scope` **does not move**, which is the whole
4165 /// point of the parameter: the silences of a podcast track come out
4166 /// without the music track under it sliding. `scope` is an arbitrary set of
4167 /// lanes and not a kind or a range, so a caller with its own idea of what
4168 /// is selected (a take, a track, everything) says it in lanes and nothing
4169 /// here has to learn about selection.
4170 ///
4171 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4172 /// reason this exists rather than a caller's loop over
4173 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4174 /// undo press, not forty. Cut back to front, so a region's frames still
4175 /// mean what the caller measured while the ones before it are cut.
4176 ///
4177 /// The list is sorted and overlapping entries are merged before anything is
4178 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4179 /// other's frames. Refused, with no undo step, for an empty list, for a
4180 /// scope naming no lane that is there, and -- by name -- when the scope
4181 /// would take one half of a take with it
4182 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4183 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4184 let regions = tidy(regions);
4185 let on = self.scoped(scope)?;
4186 let Some(&(first, _)) = regions.first() else {
4187 return Err("nothing to cut".into());
4188 };
4189 self.scope_holds_takes_whole(&on, first)?;
4190 self.snapshot();
4191 for &(at, len) in regions.iter().rev() {
4192 ripple(&mut self.lanes, &on, at, len);
4193 }
4194 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4195 Ok(())
4196 }
4197
4198 /// The storage indices of `scope`, which is what every batch below walks.
4199 /// `Err` for a scope that names nothing there rather than a silent no-op:
4200 /// an edit asked for on a lane that is not there did not happen, and the
4201 /// caller has to hear so.
4202 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4203 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4204 match on.is_empty() {
4205 true => Err("no track to work on".into()),
4206 false => Ok(on),
4207 }
4208 }
4209
4210 /// The law a scoped ripple lives under: **a group travels as one**, so a
4211 /// batch that moves one half of a take and not the other would leave the
4212 /// halves disagreeing about where they stand -- an offset no hand asked
4213 /// for, and the reason the take's lanes have to be scoped together.
4214 ///
4215 /// Refused by name rather than widened silently. Widening would edit a
4216 /// track the user did not scope, which is exactly the surprise scoping
4217 /// exists to end; a front-end that wants the take is free to *say* the
4218 /// take's lanes, and to name them in what it tells the user afterwards.
4219 ///
4220 /// Only from `from` on: a take sitting entirely before the first cut does
4221 /// not move, so it is not this rule's business.
4222 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4223 let labels = handles(&self.lanes);
4224 // The halves of a group are on either of a lane's lists, and the
4225 // refusal names whichever sits outside the scope -- a clip like it
4226 // always has, and a caption now that a group may hold one.
4227 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4228 let Some(id) = link else {
4229 return Ok(());
4230 };
4231 for (j, data) in self.lanes.iter().enumerate() {
4232 if on.contains(&j) {
4233 continue;
4234 }
4235 let clip = data.clips.iter().find(|o| o.link == Some(id));
4236 let sub = data.subs.iter().find(|s| s.link == Some(id));
4237 if let Some(half) = clip {
4238 return Err(format!(
4239 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4240 moving one track of a take would pull it apart -- take the whole take, \
4241 or detach them first",
4242 labels[j].label(),
4243 half.start
4244 )
4245 .into());
4246 }
4247 if let Some(half) = sub {
4248 return Err(format!(
4249 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4250 moving one track of a take would pull it apart -- take the whole take, \
4251 or detach them first",
4252 labels[j].label(),
4253 half.start
4254 )
4255 .into());
4256 }
4257 }
4258 Ok(())
4259 };
4260 for &i in on {
4261 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4262 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4263 }
4264 // A caption before the first cut does not move, so it is not this
4265 // rule's business -- exactly the clip test's own line.
4266 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4267 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4268 }
4269 }
4270 Ok(())
4271 }
4272
4273 /// Play every one of `regions` at `speed` instead of cutting it: each is
4274 /// split out of whatever covers it, re-rated, and the room it no longer
4275 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4276 /// does not ripple, and a hole where a silence shrank is the one thing this
4277 /// must not leave. One snapshot for the lot, like
4278 /// [`cut_regions`](Project::cut_regions).
4279 ///
4280 /// The rate is **absolute**, not a multiplier on what is there: running it
4281 /// twice over the same stretch leaves it at `speed`, not at `speed`
4282 /// squared, so a second pass over an already-cut timeline changes nothing.
4283 ///
4284 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4285 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4286 ///
4287 /// Refused by name, with nothing changed and no undo step, when:
4288 ///
4289 /// * the scope would take one half of a take with it
4290 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4291 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4292 /// shrink by different amounts and the ripple would pull them apart,
4293 /// which is what cutting does not suffer and why delete mode has no such
4294 /// refusal;
4295 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4296 /// piece could not be split out exactly;
4297 /// * two lanes' pieces would end up different lengths, which is a group
4298 /// whose halves disagree about their span (the refusal
4299 /// [`write_speed`](Project::write_speed) already makes, in its words);
4300 /// * the region would grow rather than shrink, i.e. it already plays faster
4301 /// than `speed`.
4302 pub fn speed_regions(
4303 &mut self,
4304 regions: &[(u32, u32)],
4305 speed: Speed,
4306 scope: &[Lane],
4307 ) -> crate::Result<()> {
4308 let regions = tidy(regions);
4309 let on = self.scoped(scope)?;
4310 let Some(&(first, _)) = regions.first() else {
4311 return Err("nothing to speed up".into());
4312 };
4313 self.scope_holds_takes_whole(&on, first)?;
4314 let labels = handles(&self.lanes);
4315 // Before anything is touched, because this is the refusal a person can
4316 // act on: a clip that laps over the edge of a silence has to be trimmed
4317 // (or the silences cut instead), and saying so after a rollback would
4318 // be saying it about a timeline that already looks different.
4319 for &(at, len) in &regions {
4320 for &l in &on {
4321 for c in &self.lanes[l].clips {
4322 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4323 {
4324 return Err(format!(
4325 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4326 speeding it up would pull the lanes apart -- trim it first, or cut the \
4327 silences out instead",
4328 labels[l].label(),
4329 c.start,
4330 at + len
4331 )
4332 .into());
4333 }
4334 }
4335 }
4336 }
4337 // The rest is checked as it is built: a split's own arithmetic is what
4338 // says whether a rate can address an edge. So the snapshot is taken
4339 // first and *rolled back* on a refusal -- one undo either way, and a
4340 // refusal still costs no step (`undo` pops the one just pushed).
4341 self.snapshot();
4342 for &(at, len) in regions.iter().rev() {
4343 self.write_split(at, false, &on);
4344 self.write_split(at + len, false, &on);
4345 let mut room: Option<(Lane, u32)> = None;
4346 let mut refused = None;
4347 for &l in &on {
4348 let clips = &self.lanes[l].clips;
4349 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4350 if (c.start, c.end()) != (at, at + len) {
4351 // *Which* edge did not come off: a rate that cannot
4352 // address the end of the silence is not a rate that
4353 // cannot address its start, and naming the wrong frame
4354 // sends the user looking in the wrong place.
4355 let edge = match c.start == at {
4356 true => at + len,
4357 false => at,
4358 };
4359 refused = Some(format!(
4360 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4361 detach it, or put it back to 1.00x first",
4362 labels[l].label(),
4363 c.start,
4364 c.speed
4365 ));
4366 continue;
4367 }
4368 let after = speed.frames(c.len());
4369 match room {
4370 None => room = Some((labels[l], after)),
4371 Some((first, n)) if n != after => {
4372 refused = Some(format!(
4373 "at {speed} the {} half of the silence at frame {at} would cover \
4374 {after} frames and the {} half {n}: they are one take and a take \
4375 is one span -- detach them first",
4376 labels[l].label(),
4377 first.label()
4378 ));
4379 }
4380 Some(_) => {}
4381 }
4382 }
4383 }
4384 let shrunk = match (refused, room) {
4385 (Some(e), _) => {
4386 self.undo();
4387 return Err(e.into());
4388 }
4389 // A gap on every lane: nothing to re-rate, and nothing to close.
4390 (None, None) => continue,
4391 (None, Some((_, after))) => after,
4392 };
4393 // The region's new length, on every scoped lane alike.
4394 let after = shrunk;
4395 let Some(delta) = len.checked_sub(shrunk) else {
4396 self.undo();
4397 return Err(format!(
4398 "the silence at frame {at} already plays faster than {speed}: \
4399 at that rate it would be {shrunk} frames instead of {len}"
4400 )
4401 .into());
4402 };
4403 for &l in &on {
4404 for c in &mut self.lanes[l].clips {
4405 if c.start == at && c.end() == at + len {
4406 c.speed = speed;
4407 } else if c.start >= at + len {
4408 c.start -= delta;
4409 }
4410 }
4411 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4412 // The captions on a scoped lane travel with the region's time:
4413 // a piece inside it plays in `after` frames instead of `len`
4414 // -- same words on less timeline, its window untouched, for
4415 // [`write_speed`]'s reason -- and everything behind the region
4416 // slides up by what the region gave back.
4417 //
4418 // The pieces inside re-time by their *boundaries*, not each
4419 // on its own: rounding one piece's start and its neighbour's
4420 // start apart can land both on the same frame (two one-frame
4421 // cues of a thirty-frame region at 2x both want frame 15), so
4422 // the mapped boundaries are walked in order and forced apart
4423 // -- each piece at least one frame, none past the region's own
4424 // new end, where the first follower lands exactly. A rounding
4425 // artifact is clamped, not refused: nothing about the words
4426 // asked for an overlap.
4427 let share = f64::from(after) / f64::from(len).max(1.);
4428 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4429 let mut prev = at;
4430 let subs = &mut self.lanes[l].subs;
4431 for i in 0..subs.len() {
4432 let s = subs[i];
4433 if s.start >= at + len {
4434 subs[i].start = s.start - delta;
4435 } else if s.start >= at && s.end() <= at + len {
4436 let mut start = map(s.start).max(prev);
4437 let end = map(s.end()).max(start + 1).min(at + after);
4438 start = start.min(end - 1);
4439 subs[i].start = start;
4440 subs[i].frames = end - start;
4441 prev = end;
4442 }
4443 }
4444 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4445 }
4446 }
4447 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4448 Ok(())
4449 }
4450
4451 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4452 /// -- the whole-group delete a single-lane front-end means. `false` for a
4453 /// bad index. Changes the mapping: the caller must reseek.
4454 pub fn delete(&mut self, idx: usize) -> bool {
4455 self.delete_in(Lane::V1, idx)
4456 }
4457
4458 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4459 /// in no group (or a group of one, which is the same thing to a delete) is
4460 /// what it always was: its own span cut out of *every* lane, so the
4461 /// timeline closes up under it. A clip in a group takes the group with it,
4462 /// each member by its **own** span and on its **own** lane -- the members
4463 /// keep their offsets, so their spans may disagree, and the lanes may end
4464 /// up out of step with each other, which is inherent to a hand-built group
4465 /// and one undo away. Every member -- clips and captions alike -- goes by
4466 /// the same law: its own span out of its own lane, hole closed; a caption
4467 /// in no group keeps the lift that leaves a gap, which is its own door's
4468 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4469 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4470 /// index, and for a lane that is not there. Changes the mapping: the
4471 /// caller must reseek.
4472 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4473 let Some(members) = self.group_of(lane, idx) else {
4474 return false;
4475 };
4476 if !members.alone() {
4477 return self.delete_members(&members);
4478 }
4479 let Some(clip) = self.lane(lane).get(idx).copied() else {
4480 return false;
4481 };
4482 self.ripple_delete(clip.start, clip.frames())
4483 }
4484
4485 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4486 /// caption in no group lifts, exactly as its own key always made it
4487 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4488 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4489 /// span out of its own lane, hole closed, captions and clips alike.
4490 /// `false` for a bad index.
4491 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4492 let Some(members) = self.group_of(lane, idx) else {
4493 return false;
4494 };
4495 if !members.alone() {
4496 return self.delete_members(&members);
4497 }
4498 self.lift_sub(lane, idx)
4499 }
4500
4501 /// The one whole-group delete both doors land in: every member's own span
4502 /// cut out of its own lane and the hole closed there -- clips and
4503 /// captions by the same law -- and nothing else on another lane moves,
4504 /// which is what keeps one member's ripple from dragging another
4505 /// member's lane out from under it. One snapshot, one undo step.
4506 fn delete_members(&mut self, members: &Members) -> bool {
4507 self.snapshot();
4508 for &(l, i) in &members.clips {
4509 let c = self.lanes[l].clips[i];
4510 ripple(&mut self.lanes, &[l], c.start, c.frames());
4511 }
4512 // The captions go by the same law their clip siblings do -- the span
4513 // out of its own lane, the hole closed -- and not by the lift a
4514 // *lone* caption's delete is: deleted with its group, the words after
4515 // it slide up with everything else, or the lane the group emptied is
4516 // the one lane the delete left a hole in. `ripple` is the one
4517 // mechanism (it clears the span and shifts the rest, clips and
4518 // captions alike); a sub lane holds no clips, so its other list is
4519 // untouched.
4520 for &(l, i) in &members.subs {
4521 let s = self.lanes[l].subs[i];
4522 ripple(&mut self.lanes, &[l], s.start, s.frames);
4523 }
4524 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4525 true
4526 }
4527
4528 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4529 #[cfg(test)]
4530 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4531 self.lane(lane)
4532 }
4533
4534 /// How many undo steps are stacked: what the sweep asks so "one op, one
4535 /// snapshot" is a count and not a guess.
4536 #[cfg(test)]
4537 pub(crate) fn history_len(&self) -> usize {
4538 self.history.len()
4539 }
4540
4541 /// How many redo steps are stacked: what the sweep asks to check `undo`
4542 /// left a branch behind, and that a fresh edit clears it.
4543 #[cfg(test)]
4544 pub(crate) fn redo_len(&self) -> usize {
4545 self.redo.len()
4546 }
4547
4548 /// Every part of the project that an edit can change, as comparable
4549 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4550 #[cfg(test)]
4551 pub(crate) fn parts(&self) -> SweepParts {
4552 SweepParts(
4553 self.sources.len(),
4554 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4555 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4556 )
4557 }
4558
4559 /// Restore every lane from before the last successful edit -- the clips and
4560 /// the lane list both. `false` when there is nothing left to undo. Pushes
4561 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4562 /// forward again.
4563 pub fn undo(&mut self) -> bool {
4564 match self.history.pop() {
4565 Some(prev) => {
4566 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4567 true
4568 }
4569 None => false,
4570 }
4571 }
4572
4573 /// Restore every lane from before the last [`Project::undo`] -- the
4574 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4575 /// is nothing left to redo, which is also true after any fresh edit: a
4576 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4577 pub fn redo(&mut self) -> bool {
4578 match self.redo.pop() {
4579 Some(next) => {
4580 self.history.push(std::mem::replace(&mut self.lanes, next));
4581 true
4582 }
4583 None => false,
4584 }
4585 }
4586
4587 /// The project an export renders from: everything a render reads, with the
4588 /// undo history left behind. An export never walks the history back, and
4589 /// cloning it costs a copy of every lane list in the session -- this is
4590 /// taken on the UI thread, so it clones the lanes and the sources alone.
4591 pub fn export_snapshot(&self) -> Self {
4592 Self {
4593 sources: self.sources.clone(),
4594 lanes: self.lanes.clone(),
4595 eq: self.eq.clone(),
4596 color: self.color.clone(),
4597 transform: self.transform.clone(),
4598 history: Vec::new(),
4599 redo: Vec::new(),
4600 next_link: self.next_link,
4601 subtitles: self.subtitles.clone(),
4602 limiter: self.limiter,
4603 tone: self.tone,
4604 }
4605 }
4606
4607 /// Half-open `(source, start, end)` segments in *source* seconds, from
4608 /// `timeline_frame` to the end of the timeline -- the play list for the
4609 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4610 /// worker synthesises that many seconds of silence, which is what keeps the
4611 /// audio master clock counting across a hole instead of stalling on it.
4612 /// The first entry is partial when the position is mid-clip. Empty when the
4613 /// position is past the end or `fps` is not usable.
4614 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4615 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4616 }
4617
4618 /// [`segments_from`](Project::segments_from) for a named lane.
4619 pub fn lane_segments_from(
4620 &self,
4621 lane: Lane,
4622 timeline_frame: u32,
4623 fps: f64,
4624 ) -> Vec<(Option<usize>, f64, f64)> {
4625 if !(fps.is_finite() && fps > 0.0) {
4626 return Vec::new();
4627 }
4628 self.spans_from(lane, timeline_frame)
4629 .iter()
4630 .map(|span| match span.from {
4631 // A clip's window is in *source* seconds: where in the file it
4632 // reads from, which a delete before it never shifts. How many
4633 // source frames that is, is the span's own arithmetic -- at a
4634 // speed it is not the timeline length ([`Span::source_len`]).
4635 Some((source, in_frame)) => (
4636 Some(source),
4637 f64::from(in_frame) / fps,
4638 f64::from(in_frame + span.source_len()) / fps,
4639 ),
4640 // A gap has no file, so all it can say is how long it is.
4641 None => (None, 0.0, f64::from(span.len) / fps),
4642 })
4643 .collect()
4644 }
4645
4646 /// One play list per audio lane that *holds* something, in display order --
4647 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4648 /// what an export asks how many lanes it would have to mix.
4649 ///
4650 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4651 /// audio lane at all) still yields one all-gap list, so it plays silence
4652 /// against a master clock exactly as it did before there were lanes to
4653 /// count. Lanes with nothing on them are left out rather than mixed in as
4654 /// silence: they would cost a decode thread each and add zero.
4655 pub fn audio_segments_from(
4656 &self,
4657 timeline_frame: u32,
4658 fps: f64,
4659 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4660 self.audio_lanes()
4661 .into_iter()
4662 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4663 .collect()
4664 }
4665
4666 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4667 /// builds a play list for, in the same order. Public because everything
4668 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4669 /// which lane an mp4 export would copy -- has to read the very list the
4670 /// sound comes off, or the two answers drift apart (which is exactly how an
4671 /// `A2`-only project once exported silently, ledger).
4672 pub fn audio_lanes(&self) -> Vec<Lane> {
4673 let lanes: Vec<Lane> = self
4674 .lanes()
4675 .into_iter()
4676 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4677 .collect();
4678 match lanes.is_empty() {
4679 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4680 // no sound still plays silence against the master clock.
4681 true => vec![Lane::A1],
4682 false => lanes,
4683 }
4684 }
4685
4686 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4687 /// segments plays at, and how long the timeline gives it: the same lanes in
4688 /// the same order, one entry per segment, `None` for a segment at real time
4689 /// -- which is every segment of a project nobody has speeded, and the path
4690 /// the audio worker leaves bit-identical.
4691 ///
4692 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4693 /// the segment tuple is what every opener and a dozen tests speak, and a
4694 /// rate is not part of *which samples* a segment names.
4695 ///
4696 /// The seconds are what makes a resample exact: a segment's own window
4697 /// resolves to whole source frames, and dividing that by the rate would
4698 /// leave each clip a fraction of a frame short or long -- a drift that grows
4699 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4700 /// the last few samples of each segment instead, so the sound stays locked
4701 /// to the picture however many speeded cuts it walks through.
4702 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4703 self.audio_lanes()
4704 .into_iter()
4705 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4706 .collect()
4707 }
4708
4709 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4710 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4711 /// same walk, same `fps` refusal.
4712 pub fn lane_speeds_from(
4713 &self,
4714 lane: Lane,
4715 timeline_frame: u32,
4716 fps: f64,
4717 ) -> Vec<Option<Stretch>> {
4718 if !(fps.is_finite() && fps > 0.0) {
4719 return Vec::new();
4720 }
4721 self.spans_from(lane, timeline_frame)
4722 .iter()
4723 .map(|span| {
4724 (!span.speed.is_normal()).then(|| Stretch {
4725 step: span.speed.as_f64(),
4726 timeline_secs: f64::from(span.len) / fps,
4727 })
4728 })
4729 .collect()
4730 }
4731
4732 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4733 /// segments plays through: the same lanes in the same order, one entry per
4734 /// segment, `None` where the segment is a gap or its clip plays flat.
4735 ///
4736 /// A parallel list rather than a fourth element of the segment tuple: that
4737 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4738 /// and an effect is not part of *which samples* a segment names. A short
4739 /// list therefore means "flat from here on" rather than a length mismatch --
4740 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4741 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4742 self.audio_lanes()
4743 .into_iter()
4744 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4745 .collect()
4746 }
4747
4748 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4749 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4750 /// same walk, same `fps` refusal, so the two lists cannot come out different
4751 /// lengths.
4752 pub fn lane_eqs_from(
4753 &self,
4754 lane: Lane,
4755 timeline_frame: u32,
4756 fps: f64,
4757 ) -> Vec<Option<EqParams>> {
4758 if !(fps.is_finite() && fps > 0.0) {
4759 return Vec::new();
4760 }
4761 self.spans_from(lane, timeline_frame)
4762 .iter()
4763 // A span off a clip covers that clip's frames and no others, so its
4764 // own start names the clip -- the index a [`Span`] does not carry.
4765 .map(|span| {
4766 self.map(lane, span.start)
4767 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4768 })
4769 .collect()
4770 }
4771
4772 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
4773 /// segments plays through: the same lanes in the same order, one entry per
4774 /// segment, `None` where the segment is a gap or its clip has neither a
4775 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
4776 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
4777 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
4778 self.audio_lanes()
4779 .into_iter()
4780 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
4781 .collect()
4782 }
4783
4784 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
4785 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
4786 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
4787 if !(fps.is_finite() && fps > 0.0) {
4788 return Vec::new();
4789 }
4790 self.spans_from(lane, timeline_frame)
4791 .iter()
4792 .map(|span| {
4793 let (idx, _) = self.map(lane, span.start)?;
4794 let clip = self.lane(lane).get(idx)?;
4795 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
4796 // `span.len` is the clip's own remaining frames from
4797 // `span.start` on -- shorter than `clip.frames()` only
4798 // when this is the first span of a seek mid-clip.
4799 elapsed: clip.frames().saturating_sub(span.len),
4800 fade_in: clip.fade_in,
4801 fade_out: clip.fade_out,
4802 total: clip.frames(),
4803 })
4804 })
4805 .collect()
4806 }
4807
4808 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4809 /// it has decided it will succeed -- a refusal must not cost an undo step.
4810 /// Clears the redo stack: a fresh edit branches off from here, so whatever
4811 /// `undo` had left to redo is no longer where this edit leads back to.
4812 fn snapshot(&mut self) {
4813 if self.history.len() == HISTORY_CAP {
4814 self.history.remove(0);
4815 }
4816 self.history.push(self.lanes.clone());
4817 self.redo.clear();
4818 }
4819
4820 fn new_link(&mut self) -> u32 {
4821 let id = self.next_link;
4822 self.next_link = self.next_link.saturating_add(1);
4823 id
4824 }
4825
4826}
4827
4828/// The handle of every lane, in storage order -- the one definition of what
4829/// [`Lane::ord`] counts.
4830fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4831 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4832 lanes
4833 .iter()
4834 .map(|l| match l.kind {
4835 LaneKind::Video => {
4836 video += 1;
4837 Lane::new(LaneKind::Video, video - 1)
4838 }
4839 LaneKind::Audio => {
4840 audio += 1;
4841 Lane::new(LaneKind::Audio, audio - 1)
4842 }
4843 LaneKind::Subtitle => {
4844 subtitle += 1;
4845 Lane::new(LaneKind::Subtitle, subtitle - 1)
4846 }
4847 })
4848 .collect()
4849}
4850
4851/// The one law a caption re-time scales by: frame `f` moves about the held
4852/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4853/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4854/// [`TimelineMap`] piece from this single answer so the two cannot drift
4855/// apart by a frame the way they once did.
4856fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4857 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4858 .round()
4859 .clamp(0., f64::from(u32::MAX)) as u32
4860}
4861
4862/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4863/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4864/// a speed cannot be applied twice or forgotten in one of them.
4865fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4866 // Clamped inside the clip's own range: rounding at a slow rate can put the
4867 // last timeline frame of a clip a frame past its out-point, and a source
4868 // frame outside the range is one the next clip owns.
4869 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4870}
4871
4872/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4873/// Binary search: the sorted-disjoint invariant is what makes it legal.
4874fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4875 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4876 (frame < clips[idx].end()).then_some(idx)
4877}
4878
4879/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4880/// there would cut in two. A placement's own first frame is not inside it.
4881fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4882 let idx = at(clips, frame)?;
4883 // ...and, on a speeded clip, one its rate can actually address
4884 // ([`Speed::split_at`]): a cut between two showings of one source frame
4885 // would leave halves that no longer add up to the clip that was cut.
4886 (frame > clips[idx].start)
4887 .then_some(idx)
4888 .filter(|&idx| split_source(&clips[idx], frame).is_some())
4889}
4890
4891/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
4892/// rate cannot address that frame.
4893fn split_source(c: &Clip, frame: u32) -> Option<u32> {
4894 c.speed
4895 .split_at(c.len(), frame - c.start)
4896 .map(|src| c.in_frame + src)
4897}
4898
4899/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
4900/// rejoin: they must touch there, and be consecutive frames of one source.
4901fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
4902 let idx = clips.iter().position(|c| c.end() == frame)?;
4903 let next = clips.get(idx + 1)?;
4904 let joined = clips[idx].len() + next.len();
4905 (next.start == frame
4906 && next.source == clips[idx].source
4907 && next.in_frame == clips[idx].out_frame
4908 // ...at one rate, and one that puts the rejoined clip back in exactly
4909 // the room the two took up: what a split could have produced, which is
4910 // all this undoes.
4911 && next.speed == clips[idx].speed
4912 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
4913 .then_some(idx)
4914}
4915
4916/// The lane invariant: sorted by `start`, no two placements overlapping, no
4917/// empty placement. Checked at every constructor and asserted after every
4918/// mutation -- the offset model is only tractable while it holds.
4919/// The one thing an equalizer setting may not be: a value the text format
4920/// cannot write and read back as itself. Checked wherever params come in, so
4921/// what an edit produces is always what a save writes and a load reads.
4922fn finite(params: &EqParams) -> bool {
4923 params
4924 .bands
4925 .iter()
4926 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
4927}
4928
4929/// The same for a colour grade: [`crate::color`] itself falls back to identity
4930/// on a non-finite value, but a value that cannot be written and read back as
4931/// itself has no business reaching the model.
4932fn color_finite(p: &ColorParams) -> bool {
4933 p.brightness.is_finite()
4934 && p.contrast.is_finite()
4935 && p.saturation.is_finite()
4936 && p.tint.is_finite()
4937}
4938
4939/// The same for a transform: [`crate::scale`] clamps a non-finite value to
4940/// identity at read time, but a value that cannot round-trip has no business
4941/// reaching the model.
4942fn transform_finite(p: &TransformParams) -> bool {
4943 p.pos_x.is_finite()
4944 && p.pos_y.is_finite()
4945 && p.scale.is_finite()
4946 && p.rotate.is_finite()
4947 && p.crop_l.is_finite()
4948 && p.crop_r.is_finite()
4949 && p.crop_t.is_finite()
4950 && p.crop_b.is_finite()
4951}
4952
4953fn sorted_disjoint(clips: &[Clip]) -> bool {
4954 clips.iter().all(|c| c.out_frame > c.in_frame)
4955 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
4956}
4957
4958/// The very same invariant on a subtitle lane, in that lane's own two units:
4959/// sorted by `start`, no two placements overlapping, no empty placement at
4960/// either end. Asserted after every mutation, exactly as its twin is.
4961fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
4962 subs.iter()
4963 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
4964 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
4965}
4966
4967/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
4968/// the one conversion between a lane's clock and a cue's, and `0` for a rate
4969/// that is not one (every caller of this has already refused such a rate).
4970fn us_of(frames: i64, fps: f64) -> i64 {
4971 match fps.is_finite() && fps > 0.0 {
4972 true => ((frames as f64) / fps * 1e6).round() as i64,
4973 false => 0,
4974 }
4975}
4976
4977/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
4978/// dropping what is inside the hole, splitting what straddles it and trimming
4979/// what overlaps an edge. The windows follow the cut by proportion
4980/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
4981fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
4982 let mut out = Vec::with_capacity(subs.len() + 1);
4983 for s in subs.drain(..) {
4984 if s.end() <= start || s.start >= end {
4985 out.push(s);
4986 continue;
4987 }
4988 if s.start < start {
4989 out.push(SubClip {
4990 frames: start - s.start,
4991 out_us: s.window_at(start),
4992 // Both pieces lose the group id, for [`clear`]'s reason: one
4993 // id on two boxes of one lane is the one thing it may never
4994 // mean.
4995 link: None,
4996 ..s
4997 });
4998 }
4999 if s.end() > end {
5000 out.push(SubClip {
5001 start: end,
5002 frames: s.end() - end,
5003 in_us: s.window_at(end),
5004 link: None,
5005 ..s
5006 });
5007 }
5008 }
5009 *subs = out;
5010}
5011
5012/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5013/// `len`, splitting a placement that straddles `at` so the two halves end up on
5014/// either side of the hole. A `len` of 0 is that split alone, which is what a
5015/// [`Project::split`] over a subtitle lane is.
5016fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5017 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5018 let s = subs[idx];
5019 let cut = s.window_at(at);
5020 subs[idx] = SubClip {
5021 frames: at - s.start,
5022 out_us: cut,
5023 link: None,
5024 ..s
5025 };
5026 subs.insert(
5027 idx + 1,
5028 SubClip {
5029 start: at,
5030 frames: s.end() - at,
5031 in_us: cut,
5032 link: None,
5033 ..s
5034 },
5035 );
5036 }
5037 for s in subs.iter_mut().filter(|s| s.start >= at) {
5038 s.start += len;
5039 }
5040}
5041
5042/// [`joinable`] for a subtitle lane: the first of the two placements a
5043/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5044/// produced and nothing else -- they touch on the timeline, they read the same
5045/// track, and the second one's window carries on where the first's stopped.
5046fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5047 let idx = subs.iter().position(|s| s.end() == frame)?;
5048 let next = subs.get(idx + 1)?;
5049 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5050 .then_some(idx)
5051}
5052
5053/// How far one `edge` of the caption at `idx` may travel against its own lane's
5054/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5055/// rate, which a caption *following* a group's trim does not have to be exact
5056/// about -- its own walls, its own one surviving frame, and nothing that needs
5057/// a clock.
5058fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5059 let s = &subs[idx];
5060 match edge {
5061 Edge::Start => (
5062 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5063 s.end() - 1,
5064 ),
5065 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5066 }
5067}
5068
5069/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5070/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5071/// forwards and backwards. The caption a group's trim is carrying has no rate
5072/// of its own and needs none: what one frame of it is worth in microseconds is
5073/// the window it already shows over the frames it already takes.
5074fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5075 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5076 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5077 match edge {
5078 Edge::Start => {
5079 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5080 s.frames = s.end() - to;
5081 s.start = to;
5082 }
5083 Edge::End => {
5084 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5085 s.frames = to - s.start;
5086 }
5087 }
5088 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5089}
5090
5091/// The grouping invariant, checked in release at [`Project::from_parts`] and
5092/// asserted by the tests after every edit: a link id names **at most one**
5093/// placement per lane -- a clip on a media lane or a caption on a subtitle
5094/// one, whichever carries it. That is all "these move together" can mean now
5095/// that a group is assembled by hand: the members keep their own spans and
5096/// their own offsets, and what binds them is the id alone.
5097///
5098/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5099/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5100/// placements of one group may cover different frames -- the offset-preserving
5101/// group a hand builds with [`Project::group_all`], which a drag moves by one
5102/// delta rather than by one span.
5103///
5104/// A link no other lane carries is legal and is not an error: lifting one half
5105/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5106/// timeline has to load again.
5107/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5108/// asked by the sweep suite's universal law.
5109#[cfg(test)]
5110pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5111 links_are_consistent(&p.lanes)
5112}
5113
5114fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5115 let handles = handles(lanes);
5116 for (data, lane) in lanes.iter().zip(&handles) {
5117 for (i, c) in data.clips.iter().enumerate() {
5118 let Some(id) = c.link else { continue };
5119 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5120 return Err(
5121 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5122 );
5123 }
5124 }
5125 // ...and the same for the captions, in their own list on the same lane:
5126 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5127 // id could be doubled on.
5128 for (i, s) in data.subs.iter().enumerate() {
5129 let Some(id) = s.link else { continue };
5130 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5131 return Err(format!(
5132 "link {id} names two captions in the {} lane",
5133 lane.label()
5134 )
5135 .into());
5136 }
5137 }
5138 }
5139 Ok(())
5140}
5141
5142/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5143/// it go, one straddling it is split in two, one overlapping an edge is
5144/// trimmed. Source frames follow the trim, so what is left plays what it always
5145/// played. Leaves the lane sorted and disjoint.
5146///
5147/// A piece the hole cut is no longer the take its group id names -- and both
5148/// halves of a straddled placement carrying that id would be the same id twice
5149/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5150fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5151 let mut out = Vec::with_capacity(clips.len() + 1);
5152 for c in clips.drain(..) {
5153 // Disjoint from the hole: untouched.
5154 if c.end() <= start || c.start >= end {
5155 out.push(c);
5156 continue;
5157 }
5158 // The head that survives in front of the hole -- as much source as fits
5159 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5160 // which at real time is that room itself. Never *more*: a head that
5161 // outgrew its room would reach into the hole it is being cut out of,
5162 // which is exactly the overlap a slow clip punched at a frame its rate
5163 // cannot address used to leave (at 0.25x a single source frame is four
5164 // timeline frames, and three frames of room hold none of it). `None`
5165 // there means no remainder at all, and the piece simply goes.
5166 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5167 && c.start < start
5168 {
5169 out.push(Clip {
5170 fade_in: 0,
5171 fade_out: 0,
5172 transition_out: 0,
5173 out_frame: c.in_frame + keep.min(c.len()),
5174 link: None,
5175 ..c
5176 });
5177 }
5178 // ...and the tail behind it, which keeps reading up to where it would
5179 // have: measured from its out-point for the head's reason, so what it
5180 // occupies still ends where the whole clip did -- and dropped whole on
5181 // the same `None`.
5182 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5183 && c.end() > end
5184 {
5185 out.push(Clip {
5186 fade_in: 0,
5187 fade_out: 0,
5188 transition_out: 0,
5189 start: end,
5190 in_frame: c.out_frame - keep.min(c.len()),
5191 link: None,
5192 ..c
5193 });
5194 }
5195 }
5196 *clips = out;
5197}
5198
5199/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5200/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5201/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5202/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5203/// the caller.
5204fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5205 for &i in on {
5206 let clips = &mut lanes[i].clips;
5207 clear(clips, at, at + len);
5208 for c in clips.iter_mut().filter(|c| c.start >= at) {
5209 c.start -= len;
5210 }
5211 debug_assert!(sorted_disjoint(clips));
5212 // The subtitle lanes close the hole with everything else: a caption
5213 // left standing where the picture it belongs to was cut out is the
5214 // desync a lane model exists to make impossible.
5215 let subs = &mut lanes[i].subs;
5216 sub_clear(subs, at, at + len);
5217 for s in subs.iter_mut().filter(|s| s.start >= at) {
5218 s.start -= len;
5219 }
5220 debug_assert!(subs_sorted_disjoint(subs));
5221 }
5222}
5223
5224/// Every lane, as the index list the two above take: what "the whole timeline"
5225/// is spelled as, and the scope [`Project::ripple_delete`] and
5226/// [`Project::split`] have always had.
5227fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5228 (0..lanes.len()).collect()
5229}
5230
5231/// A caller's region list as a batch may use it: sorted by start, empty entries
5232/// dropped, and touching or overlapping entries merged into one.
5233///
5234/// Overlapping regions are the one thing a batch cannot take -- cutting the
5235/// second would cut frames the first already moved -- and a detector handing
5236/// back two that touch means one silence, not two cuts. Merged rather than
5237/// refused: this is arithmetic on a preview, not a user's mistake.
5238fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5239 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5240 sorted.sort_by_key(|&(at, _)| at);
5241 let mut out: Vec<(u32, u32)> = Vec::new();
5242 for (at, len) in sorted {
5243 let end = at.saturating_add(len);
5244 match out.last_mut() {
5245 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5246 _ => out.push((at, len)),
5247 }
5248 }
5249 out
5250}
5251
5252/// Slides everything from `at` on later by `len`, splitting a placement that
5253/// straddles `at` so the two halves end up on either side of the hole. The
5254/// insert half of a rippling paste. The two halves lose the group id for the
5255/// reason [`clear`] gives.
5256fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5257 if let Some(idx) = splittable(clips, at) {
5258 let mut tail = clips[idx];
5259 // The cut in *source* frames, at the clip's own rate. `splittable` has
5260 // already refused a frame the rate cannot address, which is why
5261 // [`Project::paste`] refuses one too rather than opening room inside a
5262 // clip that cannot be cut there.
5263 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5264 tail.start = at;
5265 tail.link = None;
5266 clips[idx].out_frame = tail.in_frame;
5267 clips[idx].link = None;
5268 clips.insert(idx + 1, tail);
5269 }
5270 for c in clips.iter_mut().filter(|c| c.start >= at) {
5271 c.start += len;
5272 }
5273}
5274
5275/// Absolute, symlink-resolved when the file is reachable; the path as given
5276/// when it is not -- an unreadable path still deserves an index, it simply
5277/// dedups by spelling.
5278pub(crate) fn canonical(path: &Path) -> PathBuf {
5279 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5280}
5281
5282#[cfg(test)]
5283mod tests {
5284 use super::*;
5285
5286 const FPS: f64 = 30.0;
5287 /// Never opened -- `Project` is pure data, so a path that does not exist is
5288 /// simply a path that dedups by spelling.
5289 const FILE: &str = "/nonexistent/a.mp4";
5290 const FILE2: &str = "/nonexistent/b.mp4";
5291
5292 /// A contiguous placement, group id ignored: what most assertions compare.
5293 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5294 Clip {
5295 fade_in: 0,
5296 fade_out: 0,
5297 transition_out: 0,
5298 start,
5299 in_frame,
5300 out_frame,
5301 source,
5302 link: None,
5303 eq: None,
5304 color: None,
5305 transform: None,
5306 fit: FitPolicy::default(),
5307 speed: Speed::NORMAL,
5308 }
5309 }
5310
5311 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5312 /// apart -- which is what makes the table's dedup and its prune visible.
5313 fn band_at(n: u32) -> EqParams {
5314 EqParams {
5315 bands: vec![crate::eq::Band {
5316 freq_hz: 1000.0,
5317 gain_db: f64::from(n) as f32 * 1.5,
5318 q: 0.707,
5319 kind: crate::eq::BandKind::Peak,
5320 }],
5321 }
5322 }
5323
5324 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5325 /// for the colour table.
5326 fn grade_at(n: u32) -> ColorParams {
5327 ColorParams {
5328 brightness: f64::from(n) as f32 * 0.05,
5329 ..Default::default()
5330 }
5331 }
5332
5333 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5334 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5335 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5336 }
5337
5338 /// Every lane with its group ids blanked, for comparing shape.
5339 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5340 p.lanes()
5341 .into_iter()
5342 .map(|l| {
5343 p.lane(l)
5344 .iter()
5345 .map(|c| Clip { link: None, ..*c })
5346 .collect()
5347 })
5348 .collect()
5349 }
5350
5351 /// The *source frame* every timeline frame reads, per lane -- the traversal
5352 /// a player performs. Deliberately not the clip index: a split changes which
5353 /// clip a frame belongs to, and nothing else.
5354 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5355 (0..p.timeline_frames() + 2)
5356 .map(|f| {
5357 p.lanes()
5358 .into_iter()
5359 .map(|l| p.map(l, f).map(|(_, source)| source))
5360 .collect()
5361 })
5362 .collect()
5363 }
5364
5365 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5366 /// fixture. Built through `split` so the constructor path is exercised too.
5367 fn three() -> Project {
5368 let mut p = Project::single(FILE, 9);
5369 assert!(p.split(3));
5370 assert!(p.split(5));
5371 assert_eq!(
5372 shape(&p),
5373 [
5374 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5375 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5376 ]
5377 );
5378 p
5379 }
5380
5381 #[test]
5382 fn single_is_the_whole_file_on_both_lanes() {
5383 let p = Project::single(FILE, 150);
5384 assert_eq!(p.clips().len(), 1);
5385 assert_eq!(p.lane(Lane::A1).len(), 1);
5386 assert_eq!(p.timeline_frames(), 150);
5387 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5388 // grouped: video and audio carry the same link
5389 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5390 assert!(p.clips()[0].link.is_some());
5391 // degenerate mapping: timeline == source
5392 assert_eq!(p.map_timeline(0), Some((0, 0)));
5393 assert_eq!(p.map_timeline(149), Some((0, 149)));
5394 assert_eq!(p.map_timeline(150), None);
5395 // never-empty invariant survives a bogus frame count
5396 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5397 }
5398
5399 #[test]
5400 fn split_cuts_every_lane_and_regroups_it_back() {
5401 let mut p = Project::single(FILE, 9);
5402 let before = traversal(&p);
5403 let before_shape = shape(&p);
5404
5405 assert!(p.split(4));
5406 for l in p.lanes() {
5407 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5408 }
5409 // The two sides are two groups, one per side, matching across the lanes.
5410 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5411 assert_eq!(v[0].link, a[0].link);
5412 assert_eq!(v[1].link, a[1].link);
5413 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5414 // A split changes no mapping, in either lane.
5415 assert_eq!(traversal(&p), before, "a split moves nothing");
5416
5417 assert!(p.regroup(4), "the inverse rejoins them");
5418 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5419 assert_eq!(traversal(&p), before);
5420 assert_eq!(
5421 p.lane(Lane::V1)[0].link,
5422 p.lane(Lane::A1)[0].link,
5423 "and the rejoined clip is one group again"
5424 );
5425 }
5426
5427 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
5428 /// the very first frame of a fade-in, unity at its last, equal-power
5429 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
5430 /// at all.
5431 #[test]
5432 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
5433 let f = Fade {
5434 elapsed: 0,
5435 fade_in: 10,
5436 fade_out: 10,
5437 total: 40,
5438 };
5439 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
5440 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
5441 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
5442 assert!(
5443 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
5444 "equal-power midpoint is sin(pi/4)"
5445 );
5446 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
5447 // The fade-out is the same curve, mirrored, counting down from the
5448 // clip's end: unity at the frame the ramp starts, the same
5449 // equal-power midpoint, and -- since `total` itself is one past the
5450 // clip's last valid frame -- the very last frame is one step short of
5451 // the silence a fade-in's own frame `0` lands on exactly.
5452 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
5453 assert!(
5454 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
5455 "the fade-out's own equal-power midpoint"
5456 );
5457 assert!(
5458 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
5459 "one step short of silence at the clip's last playable frame"
5460 );
5461 }
5462
5463 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
5464 /// not adjacent, and otherwise sets the shared edge's fades and nothing
5465 /// else.
5466 #[test]
5467 fn crossfade_only_joins_adjacent_audio_clips() {
5468 let mut p = Project::single(FILE, 20);
5469 assert!(p.split(10));
5470 assert!(
5471 !p.crossfade(Lane::V1, 0, 5),
5472 "video is not an audio lane"
5473 );
5474 assert!(
5475 !p.crossfade(Lane::A1, 1, 5),
5476 "there is no clip after idx 1"
5477 );
5478 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
5479 let a = p.lane(Lane::A1);
5480 assert_eq!(a[0].fade_out, 5);
5481 assert_eq!(a[1].fade_in, 5);
5482 assert_eq!(a[0].fade_in, 0);
5483 assert_eq!(a[1].fade_out, 0);
5484
5485 // A gap between two clips is not adjacency, even on an audio lane.
5486 let mut p2 = Project::single(FILE, 1);
5487 let a2 = p2.add_lane(LaneKind::Audio);
5488 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
5489 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5490 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
5491 }
5492
5493 /// The rule [`Project::write_split`] follows for the edge the razor makes:
5494 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
5495 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
5496 /// mirror image.
5497 #[test]
5498 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
5499 let mut p = Project::single(FILE, 20);
5500 assert!(p.set_fade_in(Lane::V1, 0, 15));
5501 assert!(p.set_fade_out(Lane::V1, 0, 15));
5502 assert!(p.split(5));
5503 let v = p.lane(Lane::V1);
5504 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
5505 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
5506 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
5507 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
5508 }
5509
5510 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
5511 /// no successor, and two clips that do not touch, and otherwise clamps
5512 /// the dissolve to the shorter of the two clips it spans.
5513 #[test]
5514 fn set_transition_out_only_dissolves_adjacent_video_clips() {
5515 let mut p = Project::single(FILE, 20);
5516 assert!(p.split(15), "a short 5-frame tail to clamp against");
5517 assert!(
5518 !p.set_transition_out(Lane::A1, 0, 5),
5519 "audio is not a video lane"
5520 );
5521 assert!(
5522 !p.set_transition_out(Lane::V1, 1, 5),
5523 "there is no clip after idx 1"
5524 );
5525 assert!(
5526 p.set_transition_out(Lane::V1, 0, 100),
5527 "the two halves are adjacent"
5528 );
5529 assert_eq!(
5530 p.transition_out_of(Lane::V1, 0),
5531 5,
5532 "clamped to the shorter neighbour's 5 frames"
5533 );
5534
5535 // A gap between two clips is not adjacency, even on the video lane.
5536 let mut p2 = Project::single(FILE, 1);
5537 let v2 = p2.add_lane(LaneKind::Video);
5538 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
5539 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5540 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
5541 }
5542
5543 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
5544 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
5545 /// only the half that kept the clip's original *end* keeps the dissolve,
5546 /// re-clamped to its own now-shorter length; the head the cut just made
5547 /// has no successor to dissolve into and starts flat.
5548 #[test]
5549 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
5550 let mut p = Project::single(FILE, 20);
5551 assert!(
5552 !p.set_transition_out(Lane::V1, 0, 0),
5553 "one clip on the lane, no successor to dissolve into yet"
5554 );
5555 // Give the clip a dissolve by hand, then cut it in two.
5556 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
5557 assert!(p.split(5));
5558 let v = p.lane(Lane::V1);
5559 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
5560 assert_eq!(
5561 v[1].transition_out, 15,
5562 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
5563 );
5564 }
5565
5566 /// The music video's own path: the take comes apart into halves that carry
5567 /// ids of their own, one undo puts it back, and two clips over the same
5568 /// frames become one take again by hand.
5569 #[test]
5570 fn a_take_comes_apart_and_goes_back_together() {
5571 let mut p = Project::single(FILE, 9);
5572 let one = p.clips()[0].link.expect("a fresh project is one take");
5573 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5574
5575 // A third lane in the same group -- and the merge case with it: a
5576 // placement is in no group, and grouping it in leaves *one* group.
5577 let v2 = p.add_lane(LaneKind::Video);
5578 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5579 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5580 p.group(Lane::V1, 0, v2, 0)
5581 .expect("the same frames, one lane over");
5582 let id = p.clips()[0].link.expect("still a group");
5583 assert!(
5584 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5585 "one id over the three, not two groups sharing a span"
5586 );
5587 links_are_consistent(&p.lanes).expect("one id, one span");
5588
5589 // Detached by the sound: every half of the group, not only the two.
5590 assert!(p.ungroup(Lane::A1, 0));
5591 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5592 assert!(
5593 ids.iter().all(Option::is_some),
5594 "a half keeps an id of its own"
5595 );
5596 assert!(
5597 ids.iter()
5598 .enumerate()
5599 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5600 "and no two halves are the same group any more: {ids:?}"
5601 );
5602 links_are_consistent(&p.lanes).expect("a lone id is legal");
5603
5604 // One snapshot for the whole detach.
5605 assert!(p.undo());
5606 assert!(
5607 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5608 "one undo puts the whole group back"
5609 );
5610
5611 // And back together by hand: the two the pointer named, and only them.
5612 assert!(p.ungroup(Lane::V1, 0));
5613 p.group(Lane::V1, 0, Lane::A1, 0)
5614 .expect("both cover [0, 9)");
5615 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5616 assert_ne!(
5617 p.lane(v2)[0].link,
5618 p.lane(Lane::V1)[0].link,
5619 "the third half stayed detached"
5620 );
5621 links_are_consistent(&p.lanes).expect("one id, one span");
5622 }
5623
5624 /// What a group may not be, and what a detach has nothing to take apart --
5625 /// none of which may cost an undo step.
5626 #[test]
5627 fn a_group_is_one_span_and_one_clip_per_lane() {
5628 let mut p = three();
5629 let before = shape(&p);
5630 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5631
5632 assert!(
5633 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5634 "two clips of one lane are never one take"
5635 );
5636 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5637 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5638 assert!(
5639 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5640 "{spans}"
5641 );
5642 assert!(
5643 spans.contains("trim them to matching bounds first"),
5644 "{spans}"
5645 );
5646 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5647
5648 // A half nothing else is grouped with is already detached, a placement
5649 // is in no group at all, and an index that is not there has nothing to
5650 // detach either.
5651 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5652 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5653 assert!(p.lift(Lane::A1, 0));
5654 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5655 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5656
5657 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5658 assert!(p.undo());
5659 assert!(p.undo());
5660 assert_eq!(shape(&p), before);
5661 }
5662
5663 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5664 /// scene under the cursor, measured the way a viewer would -- the source
5665 /// frame playing at the playhead is the same frame after the write, at
5666 /// every playhead position the re-rate can catch one.
5667 #[test]
5668 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5669 let caption = |start: u32, frames: u32| SubClip {
5670 start,
5671 frames,
5672 track: 0,
5673 in_us: 0,
5674 out_us: i64::from(frames) * 1_000_000,
5675 link: None,
5676 };
5677 let track = || SubtitleTrack {
5678 path: FILE.into(),
5679 track: None,
5680 language: "eng".into(),
5681 name: String::new(),
5682 label: "eng".into(),
5683 cues: Vec::new(),
5684 bitmap: false,
5685 refused: None,
5686 };
5687 // A group of a 300-frame clip and a caption offset 30 frames into it.
5688 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5689 let s1 = p.add_lane(LaneKind::Subtitle);
5690 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5691 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5692
5693 // The frame playing at `at`: which clip, and which source frame of it.
5694 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5695 p.span_at(Lane::V1, at)
5696 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5697 };
5698
5699 // Inside the held clip: the source frame under the playhead is the
5700 // same one after the re-rate, at 2x and at half speed both.
5701 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5702 let at = 120;
5703 let before = playing(&p, at).expect("a clip under the playhead");
5704 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5705 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5706 .expect("room for it");
5707 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5708 assert_eq!(before, after, "{what}: the same source frame plays");
5709 // ...and the write itself is untouched by the question.
5710 assert!(p.undo(), "{what}: one step back");
5711 }
5712
5713 // Past the group -- the clip ends at 300 and the caption at 270, so
5714 // from 300 on nothing is re-timed under the playhead: unmoved.
5715 for at in [300u32, 301, 1_000] {
5716 assert_eq!(
5717 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5718 Some(at),
5719 "at {at}: outside every member, unmoved"
5720 );
5721 }
5722 // The boundary is exact: the held clip's own last frame (299) maps
5723 // to its new one (149 -- the last frame inside [0, 150), where the
5724 // shrunken clip's last source frame plays), and its first stays put.
5725 assert_eq!(
5726 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5727 Some(149)
5728 );
5729 assert_eq!(
5730 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5731 Some(0)
5732 );
5733 // A spot the caption shares with the clip maps by the clip (it is
5734 // what is *playing* there): the held clip's own proportion, which on
5735 // this fixture is also its head.
5736 assert_eq!(
5737 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5738 Some(45),
5739 "the clip under the caption owns the spot"
5740 );
5741 }
5742
5743 /// A playhead inside another clip member of the group: that member keeps
5744 /// its own head, so the mapping is by its proportion and not the held
5745 /// clip's -- and the frame under the cursor is still the frame that was.
5746 #[test]
5747 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5748 let mut p = Project::single(FILE, 300);
5749 // A second clip, grouped with the first but starting 300 later: the
5750 // head the group shares and its own differ by exactly that.
5751 let v2 = p.add_lane(LaneKind::Video);
5752 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5753 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5754 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5755
5756 let at = 450; // inside the second member, 150 past its head
5757 let before = p.span_at(v2, at).and_then(|s| s.from);
5758 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5759 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5760 .expect("room for it");
5761 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5762 assert_eq!(before, after, "the second member's own frame plays");
5763 // ...and the mapping itself: 150 past its head halves, the head stays.
5764 assert_eq!(mapped, Some(375));
5765 }
5766
5767 /// The link counter a load seeds sits past every id the file names,
5768 /// captions included: a hand-grouped caption may carry the highest id there
5769 /// is, and a counter that read the clips alone would hand it to the next
5770 /// group that asked -- silently grouping the caption with clips it never
5771 /// met.
5772 #[test]
5773 fn the_link_counter_sits_past_a_caption_only_id() {
5774 let track = || SubtitleTrack {
5775 path: FILE.into(),
5776 track: None,
5777 language: "eng".into(),
5778 name: String::new(),
5779 label: "eng".into(),
5780 cues: Vec::new(),
5781 bitmap: false,
5782 refused: None,
5783 };
5784 let mut p = Project::single(FILE, 9);
5785 p.add_lane(LaneKind::Subtitle);
5786 let caption = SubClip {
5787 start: 0,
5788 frames: 6,
5789 track: 0,
5790 in_us: 0,
5791 out_us: 6_000_000,
5792 // The highest id in the file, and only a caption carries it.
5793 link: Some(1),
5794 };
5795 let mut p = p
5796 .with_subtitles(vec![track()])
5797 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5798 .expect("a caption may carry the file's highest id");
5799
5800 // A new group on lanes the caption is not on mints the next id -- which
5801 // must not be the caption's.
5802 let v2 = p.add_lane(LaneKind::Video);
5803 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5804 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5805 .expect("the clips group");
5806 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5807 assert_ne!(
5808 minted,
5809 1,
5810 "the caption's id is not re-issued to clips"
5811 );
5812 assert_eq!(
5813 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5814 Some(1),
5815 "the caption keeps its own group"
5816 );
5817 assert!(links_are_consistent(&p.lanes).is_ok());
5818 }
5819
5820 /// A rate re-times the caption members of the group by the ratio it gives
5821 /// the held clip: the span on the timeline compresses about the held clip's
5822 /// head, the words' own window untouched -- and one undo puts it back.
5823 #[test]
5824 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5825 let caption = |start: u32, frames: u32| SubClip {
5826 start,
5827 frames,
5828 track: 0,
5829 in_us: 0,
5830 out_us: i64::from(frames) * 1_000_000,
5831 link: None,
5832 };
5833 let track = || SubtitleTrack {
5834 path: FILE.into(),
5835 track: None,
5836 language: "eng".into(),
5837 name: String::new(),
5838 label: "eng".into(),
5839 cues: Vec::new(),
5840 bitmap: false,
5841 refused: None,
5842 };
5843 let grouped = || {
5844 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5845 let s1 = p.add_lane(LaneKind::Subtitle);
5846 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5847 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5848 (p, s1)
5849 };
5850
5851 // An aligned take, doubled: the caption plays in half the frames.
5852 let (mut p, s1) = grouped();
5853 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5854 .expect("room for it");
5855 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5856 let s = p.sub_lane(s1)[0];
5857 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5858 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5859 assert!(links_are_consistent(&p.lanes).is_ok());
5860 assert!(p.undo());
5861 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5862
5863 // An offset group, slowed to half: the caption's *offset from the held
5864 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5865 // 0.5x, and still ends where the clip does.
5866 let (mut p, s1) = grouped();
5867 p.lift_sub(s1, 0);
5868 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5869 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5870 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5871 .expect("room for it");
5872 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5873 let s = p.sub_lane(s1)[0];
5874 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5875 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
5876
5877 // A stretch that runs the caption into its neighbour is refused, by
5878 // lane and frame, and costs no undo step.
5879 let (mut p, s1) = grouped();
5880 p.lift_sub(s1, 0);
5881 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5882 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
5883 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5884 let history = p.history.len();
5885 let err = p
5886 .set_speed(Lane::V1, 0, Speed::from_permille(500))
5887 .unwrap_err()
5888 .to_string();
5889 assert!(
5890 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
5891 "{err}"
5892 );
5893 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
5894 }
5895
5896 /// The silence scan's speed-up re-times the captions on a scoped lane with
5897 /// everything else: the piece inside the region plays in the region's new
5898 /// frames, and what sits behind the region slides up with the clips.
5899 #[test]
5900 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
5901 let caption = |start: u32, frames: u32| SubClip {
5902 start,
5903 frames,
5904 track: 0,
5905 in_us: 0,
5906 out_us: i64::from(frames) * 1_000_000,
5907 link: None,
5908 };
5909 let track = || SubtitleTrack {
5910 path: FILE.into(),
5911 track: None,
5912 language: "eng".into(),
5913 name: String::new(),
5914 label: "eng".into(),
5915 cues: Vec::new(),
5916 bitmap: false,
5917 refused: None,
5918 };
5919 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5920 let s1 = p.add_lane(LaneKind::Subtitle);
5921 // Words over the region [30, 60) and words behind it.
5922 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5923 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
5924
5925 // The region [30, 60) plays at 4x: 30 frames become 8, everything
5926 // behind slides up 22.
5927 // The scope is what the card's Take row says, caption lane included.
5928 p.speed_regions(
5929 &[(30, 30)],
5930 Speed::from_permille(4000),
5931 &[Lane::V1, Lane::A1, s1],
5932 )
5933 .expect("the region speeds up");
5934 let subs = p.sub_lane(s1);
5935 assert_eq!(
5936 (subs[0].start, subs[0].frames),
5937 (30, 8),
5938 "the piece inside plays in the region's new frames"
5939 );
5940 assert_eq!(
5941 (subs[1].start, subs[1].frames),
5942 (38, 30),
5943 "the piece behind slides up by what the region gave back"
5944 );
5945 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
5946 }
5947
5948 /// [`Project::speeded_playhead`]'s caption arm fires only when the
5949 /// playhead is inside a caption member and outside every clip member --
5950 /// a shape every other fixture avoids by keeping its caption inside the
5951 /// held clip. Here the caption overhangs the clip's tail, and the
5952 /// playhead standing in that overhang is answered by the caption's own
5953 /// piece: it scales about the held clip's head by the held clip's own
5954 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
5955 #[test]
5956 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
5957 let caption = |start: u32, frames: u32| SubClip {
5958 start,
5959 frames,
5960 track: 0,
5961 in_us: 0,
5962 out_us: i64::from(frames) * 1_000_000,
5963 link: None,
5964 };
5965 let track = || SubtitleTrack {
5966 path: FILE.into(),
5967 track: None,
5968 language: "eng".into(),
5969 name: String::new(),
5970 label: "eng".into(),
5971 cues: Vec::new(),
5972 bitmap: false,
5973 refused: None,
5974 };
5975 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5976 let s1 = p.add_lane(LaneKind::Subtitle);
5977 // The caption spans [80, 100) -- ten frames past the clip's own end
5978 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
5979 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
5980 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5981 // At 2x the clip halves to 45 frames; the overhang frame 95, which
5982 // no clip member's old span reaches, is the caption's own question:
5983 // half of 95 is 47.5, rounded to 48.
5984 assert_eq!(
5985 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
5986 Some(48),
5987 "the overhang frame answers through the caption's own piece"
5988 );
5989 }
5990
5991 /// `write_speed` and `speeded_playhead` are two questions of the SAME
5992 /// map ([`map`]'s architecture law): a caption's landed span comes from
5993 /// the map's own ends, and the playhead standing at the caption's own
5994 /// last frame before the write has to land exactly where the write put
5995 /// it -- across clip lengths and rates that round differently, and an
5996 /// odd-length caption straddling the clip's own tail edge, the corner
5997 /// where `write_speed` used to answer a frame short.
5998 #[test]
5999 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6000 let caption = |start: u32, frames: u32| SubClip {
6001 start,
6002 frames,
6003 track: 0,
6004 in_us: 0,
6005 out_us: i64::from(frames) * 1_000_000,
6006 link: None,
6007 };
6008 let track = || SubtitleTrack {
6009 path: FILE.into(),
6010 track: None,
6011 language: "eng".into(),
6012 name: String::new(),
6013 label: "eng".into(),
6014 cues: Vec::new(),
6015 bitmap: false,
6016 refused: None,
6017 };
6018 for &len in &[90u32, 91, 177, 300, 301] {
6019 for &permille in &[500u16, 2000, 2500, 3000] {
6020 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6021 let s1 = p.add_lane(LaneKind::Subtitle);
6022 // An odd-length caption straddling the clip's tail edge: its
6023 // own last frame lands past the held clip.
6024 let c_start = len.saturating_sub(3);
6025 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6026 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6027 let speed = Speed::from_permille(permille);
6028 let last = c_start + 7 - 1;
6029 let mapped = p
6030 .speeded_playhead(Lane::V1, 0, speed, last)
6031 .expect("the caption is there");
6032 if p.set_speed(Lane::V1, 0, speed).is_err() {
6033 continue; // a refusal changes nothing: not this law's cell
6034 }
6035 let landed = p.sub_lane(s1)[0];
6036 if permille >= 1000 {
6037 // A speed-up compresses the timeline: many old frames
6038 // share one new frame, so the caption's own last old
6039 // frame lands flush with the write's own boundary --
6040 // the exact law [`write_speed`]'s worked drift-fix case
6041 // is stated against.
6042 assert_eq!(
6043 mapped,
6044 landed.end() - 1,
6045 "len {len} permille {permille}: the playhead at the caption's own \
6046 last frame lands where the write actually put it"
6047 );
6048 } else {
6049 // A slow-down expands it: one old frame becomes several
6050 // new ones, and `apply` answers where that frame's own
6051 // block *starts*, not where the caption's last new
6052 // frame (the end of that same block) sits -- a
6053 // one-frame gap inherent to the piece's own semantics,
6054 // not a drift between the two callers. Both still have
6055 // to agree the answer sits inside the caption the write
6056 // actually landed.
6057 assert!(
6058 (landed.start..landed.end()).contains(&mapped),
6059 "len {len} permille {permille}: the playhead lands inside the \
6060 caption the write actually put ({landed:?}), got {mapped}"
6061 );
6062 }
6063 }
6064 }
6065 }
6066
6067 /// A grouped caption's cues re-time with its clip: the placement's window
6068 /// crossed the timeline at its own proportion before any rate, and a
6069 /// re-rate changes that proportion (the frames compress, the window does
6070 /// not). A cue eight seconds into a window played at 2x crosses the screen
6071 /// four seconds in -- and at unity every cue lands exactly where it always
6072 /// did, byte for byte.
6073 #[test]
6074 fn a_grouped_captions_cues_re_time_with_its_clip() {
6075 let track = SubtitleTrack {
6076 path: FILE.into(),
6077 track: None,
6078 language: "eng".into(),
6079 name: String::new(),
6080 label: "eng".into(),
6081 cues: vec![crate::subtitle::Cue {
6082 start_us: 8_000_000,
6083 end_us: 9_000_000,
6084 text: "late line".into(),
6085 image: None,
6086 }],
6087 bitmap: false,
6088 refused: None,
6089 };
6090 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6091 let s1 = p.add_lane(LaneKind::Subtitle);
6092 // Ten seconds of the track over ten seconds of timeline: unity.
6093 p.place_sub(
6094 s1,
6095 0,
6096 SubClip {
6097 start: 0,
6098 frames: 300,
6099 track: 0,
6100 in_us: 0,
6101 out_us: 10_000_000,
6102 link: None,
6103 },
6104 )
6105 .expect("placed");
6106
6107 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6108 let unity = p.sub_lane_cues(s1, FPS);
6109 assert_eq!(
6110 unity
6111 .iter()
6112 .map(|c| (c.start_us, c.end_us, &*c.text))
6113 .collect::<Vec<_>>(),
6114 [(8_000_000, 9_000_000, "late line")],
6115 "a unity placement maps exactly as it always did"
6116 );
6117
6118 // Grouped with the clip and re-rated to 2x: the same window now crosses
6119 // in half the time, so the cue at 8s of it lands 4s in.
6120 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6121 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6122 .expect("room for it");
6123 let re_timed = p.sub_lane_cues(s1, FPS);
6124 assert_eq!(
6125 re_timed
6126 .iter()
6127 .map(|c| (c.start_us, c.end_us))
6128 .collect::<Vec<_>>(),
6129 [(4_000_000, 4_500_000)],
6130 "the cue crosses with the clip's new rate"
6131 );
6132 }
6133
6134 /// A video arriving on a timeline of words mutates none of them: the
6135 /// import's rippling insert used to open room on the subtitle lanes too,
6136 /// splitting a caption it landed inside and sliding the rest behind the
6137 /// video -- the hand asked for an add, and got a cut it never made. The
6138 /// words keep their own clock; co-travel is what a group is for.
6139 #[test]
6140 fn an_arriving_clip_never_touches_the_captions() {
6141 let caption = |start: u32, frames: u32| SubClip {
6142 start,
6143 frames,
6144 track: 0,
6145 in_us: i64::from(start) * 1_000_000 / 30,
6146 out_us: i64::from(start + frames) * 1_000_000 / 30,
6147 link: None,
6148 };
6149 let track = || SubtitleTrack {
6150 path: FILE.into(),
6151 track: None,
6152 language: "eng".into(),
6153 name: String::new(),
6154 label: "eng".into(),
6155 cues: Vec::new(),
6156 bitmap: false,
6157 refused: None,
6158 };
6159 // A timeline of words alone: 60 frames of caption, no media clips.
6160 let mut p = Project::single(FILE, 60)
6161 .with_subtitles(vec![track()]);
6162 for l in [Lane::V1, Lane::A1] {
6163 while !p.lane(l).is_empty() {
6164 p.lift(l, 0);
6165 }
6166 }
6167 let s1 = p.add_lane(LaneKind::Subtitle);
6168 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6169 let before = p.sub_lane(s1).to_vec();
6170
6171 // The video lands BEFORE the caption's span: nothing moves.
6172 let vid = clip(0, 0, 30, 0);
6173 assert!(p.paste(0, vid), "the video goes down at the head");
6174 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6175
6176 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6177 // byte the placement the hand made.
6178 assert!(p.paste(15, vid), "a second video lands inside the caption");
6179 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6180 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6181 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6182 assert!(links_are_consistent(&p.lanes).is_ok());
6183 }
6184
6185 /// The region's caption pieces re-time by mapped boundaries forced apart:
6186 /// rounding start and length independently can land two cues on one frame,
6187 /// and the artifact is clamped -- one frame each, in order, none past the
6188 /// region's new end -- never an overlap on the lane.
6189 #[test]
6190 fn a_regions_caption_pieces_never_round_onto_one_another() {
6191 let caption = |start: u32, frames: u32| SubClip {
6192 start,
6193 frames,
6194 track: 0,
6195 in_us: 0,
6196 out_us: i64::from(frames) * 1_000_000,
6197 link: None,
6198 };
6199 let track = |n| SubtitleTrack {
6200 path: FILE.into(),
6201 track: None,
6202 language: "eng".into(),
6203 name: String::new(),
6204 label: format!("eng{n}"),
6205 cues: Vec::new(),
6206 bitmap: false,
6207 refused: None,
6208 };
6209 // Three lanes, one repro shape each: adjacent one-frame cues, a
6210 // three-frame pair, and the region's last cue against the first
6211 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6212 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6213 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6214 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6215 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6216 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6217 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6218 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6219 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6220
6221 let mut scope = vec![Lane::V1, Lane::A1];
6222 scope.extend(lanes.iter().copied());
6223 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6224 .expect("the region speeds up");
6225 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6226 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6227 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6228 };
6229 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6230 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6231 // and the walk pushes the second to where the first ends.
6232 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6233 // The last cue of the region ends exactly where the region now does
6234 // (frame 15), and the caption behind it lands on that same frame:
6235 // touching, never overlapping.
6236 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6237 for &lane in &lanes {
6238 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6239 }
6240 }
6241
6242 /// The scope law names a caption half too: a scoped cut that would move one
6243 // track of a group whose caption sits outside the scope is refused.
6244 #[test]
6245 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6246 let caption = |start: u32, frames: u32| SubClip {
6247 start,
6248 frames,
6249 track: 0,
6250 in_us: 0,
6251 out_us: i64::from(frames) * 1_000_000,
6252 link: None,
6253 };
6254 let track = || SubtitleTrack {
6255 path: FILE.into(),
6256 track: None,
6257 language: "eng".into(),
6258 name: String::new(),
6259 label: "eng".into(),
6260 cues: Vec::new(),
6261 bitmap: false,
6262 refused: None,
6263 };
6264 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6265 let s1 = p.add_lane(LaneKind::Subtitle);
6266 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6267 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6268
6269 // The subtitle lane is not in the scope, so the group's caption half
6270 // sits outside it: refused, in the law's own words.
6271 let err = p
6272 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6273 .unwrap_err()
6274 .to_string();
6275 assert!(
6276 err.contains("is one take with the S1 caption at frame 0"),
6277 "{err}"
6278 );
6279
6280 // ...and with the caption's lane in the scope, the cut carries it:
6281 // the words over the hole go, and the words behind slide up.
6282 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6283 .expect("the whole group is in the scope");
6284 let subs = p.sub_lane(s1);
6285 assert_eq!(
6286 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6287 [(0, 10), (10, 75)],
6288 "the caption is cut and shifted with the clips"
6289 );
6290 }
6291
6292 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6293 /// mates riding along, the offsets kept, the refusals in words.
6294 #[test]
6295 fn a_hand_built_group_holds_clips_and_a_caption() {
6296 let caption = |start: u32, frames: u32| SubClip {
6297 start,
6298 frames,
6299 track: 0,
6300 in_us: 0,
6301 out_us: i64::from(frames) * 1_000_000,
6302 link: None,
6303 };
6304 let track = || SubtitleTrack {
6305 path: FILE.into(),
6306 track: None,
6307 language: "eng".into(),
6308 name: String::new(),
6309 label: "eng".into(),
6310 cues: Vec::new(),
6311 bitmap: false,
6312 refused: None,
6313 };
6314 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6315 let v2 = p.add_lane(LaneKind::Video);
6316 let s1 = p.add_lane(LaneKind::Subtitle);
6317 // A layer at its own offset, and a caption over the head of the take.
6318 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6319 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6320
6321 // Too few, one lane twice, and an index that is not there: words, no
6322 // snapshot.
6323 let history = p.history.len();
6324 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6325 assert!(p
6326 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6327 .unwrap_err()
6328 .to_string()
6329 .contains("V1 is picked twice"));
6330 assert!(p
6331 .group_all(&[(Lane::V1, 0), (s1, 9)])
6332 .unwrap_err()
6333 .to_string()
6334 .contains("no subtitle 9"));
6335 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6336
6337 // The group: the picture, the layer, and the caption -- and the sound
6338 // the picture was already grouped with comes along unasked.
6339 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6340 .expect("three picks, three lanes");
6341 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6342 for lane in [Lane::V1, Lane::A1, v2] {
6343 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6344 }
6345 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6346 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6347 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6348 assert!(links_are_consistent(&p.lanes).is_ok());
6349 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6350
6351 // ...and one undo takes it apart again.
6352 assert!(p.undo());
6353 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
6354
6355 // Detach names a caption like it names a clip: every member an id of
6356 // its own, which is never `None` (see `ungroup`).
6357 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
6358 assert!(p.ungroup(s1, 0));
6359 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
6360 assert!(loose_sub.is_some() && loose_clip.is_some());
6361 assert_ne!(loose_sub, loose_clip);
6362 assert!(links_are_consistent(&p.lanes).is_ok());
6363 }
6364
6365 /// Two captions on one sub lane, each already grouped with a *different*
6366 /// clip: `group_all` over both those clips would merge the two existing
6367 /// groups into one id and leave both captions on `s1` carrying it --
6368 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
6369 /// group closes. Refused by name, and nothing moves.
6370 #[test]
6371 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
6372 let caption = |start: u32, frames: u32| SubClip {
6373 start,
6374 frames,
6375 track: 0,
6376 in_us: 0,
6377 out_us: i64::from(frames) * 1_000_000,
6378 link: None,
6379 };
6380 let track = || SubtitleTrack {
6381 path: FILE.into(),
6382 track: None,
6383 language: "eng".into(),
6384 name: String::new(),
6385 label: "eng".into(),
6386 cues: Vec::new(),
6387 bitmap: false,
6388 refused: None,
6389 };
6390 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6391 let v2 = p.add_lane(LaneKind::Video);
6392 let s1 = p.add_lane(LaneKind::Subtitle);
6393 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
6394 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
6395 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6396 // V1 grouped with the first caption, v2 with the second -- two
6397 // separate groups, each already one member per lane.
6398 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6399 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
6400 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
6401
6402 let history = p.history.len();
6403 let err = p
6404 .group_all(&[(Lane::V1, 0), (v2, 0)])
6405 .unwrap_err()
6406 .to_string();
6407 assert!(err.contains("one placement per lane"), "{err}");
6408 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
6409 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
6410 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
6411 assert!(links_are_consistent(&p.lanes).is_ok());
6412 }
6413
6414 /// A split hands the caption of a group the same ids it hands the clips:
6415 /// the left halves keep the group, the right halves share a fresh one.
6416 #[test]
6417 fn a_split_cuts_a_grouped_caption_with_its_clips() {
6418 let caption = |start: u32, frames: u32| SubClip {
6419 start,
6420 frames,
6421 track: 0,
6422 in_us: 0,
6423 out_us: i64::from(frames) * 1_000_000,
6424 link: None,
6425 };
6426 let track = || SubtitleTrack {
6427 path: FILE.into(),
6428 track: None,
6429 language: "eng".into(),
6430 name: String::new(),
6431 label: "eng".into(),
6432 cues: Vec::new(),
6433 bitmap: false,
6434 refused: None,
6435 };
6436 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6437 let s1 = p.add_lane(LaneKind::Subtitle);
6438 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
6439 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6440 let take = p.lane(Lane::V1)[0].link.expect("the group id");
6441
6442 assert!(p.split(4));
6443 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6444 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6445 assert_eq!(left.frames, 4);
6446 assert_eq!(
6447 right.link,
6448 p.lane(Lane::V1)[1].link,
6449 "the caption's tail shares the clips' fresh id"
6450 );
6451 assert_ne!(right.link, Some(take));
6452 assert!(links_are_consistent(&p.lanes).is_ok());
6453
6454 // Regroup at the seam restores the take, caption included.
6455 assert!(p.regroup(4));
6456 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6457 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6458 }
6459
6460 /// Deleting a member of a hand-built group takes the group: every
6461 /// member's own span out of its own lane, hole closed -- the lanes may
6462 /// end up out of step, which is what one undo restores together.
6463 #[test]
6464 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6465 let caption = |start: u32, frames: u32| SubClip {
6466 start,
6467 frames,
6468 track: 0,
6469 in_us: 0,
6470 out_us: i64::from(frames) * 1_000_000,
6471 link: None,
6472 };
6473 let track = || SubtitleTrack {
6474 path: FILE.into(),
6475 track: None,
6476 language: "eng".into(),
6477 name: String::new(),
6478 label: "eng".into(),
6479 cues: Vec::new(),
6480 bitmap: false,
6481 refused: None,
6482 };
6483 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6484 let s1 = p.add_lane(LaneKind::Subtitle);
6485 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6486 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6487 // A neighbour on a lane the group does not touch.
6488 let v2 = p.add_lane(LaneKind::Video);
6489 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6490
6491 // By the picture or by the caption, the same whole-group delete.
6492 assert!(p.delete_sub_in(s1, 0));
6493 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6494 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6495 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6496 assert!(links_are_consistent(&p.lanes).is_ok());
6497 assert!(p.undo(), "one step puts the group back");
6498 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6499 }
6500
6501 /// The delete law, one statement for every anchor: a caption deleted
6502 /// WITH its group ripples its lane exactly as its clip siblings do --
6503 /// the hole closes and what follows slides up -- while a caption lifted
6504 /// alone leaves its gap, as it always has. And the delete of a grouped
6505 /// clip takes the group from whichever member was clicked.
6506 #[test]
6507 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
6508 let caption = |start: u32, frames: u32| SubClip {
6509 start,
6510 frames,
6511 track: 0,
6512 in_us: 0,
6513 out_us: i64::from(frames) * 1_000_000,
6514 link: None,
6515 };
6516 let track = || SubtitleTrack {
6517 path: FILE.into(),
6518 track: None,
6519 language: "eng".into(),
6520 name: String::new(),
6521 label: "eng".into(),
6522 cues: Vec::new(),
6523 bitmap: false,
6524 refused: None,
6525 };
6526 // V+A+S grouped, with a second caption BEHIND the group's caption:
6527 // closing the hole is what the second caption's position says.
6528 let group = || {
6529 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6530 let s1 = p.add_lane(LaneKind::Subtitle);
6531 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6532 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6533 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6534 (p, s1)
6535 };
6536
6537 // Deleted by the picture: all three lanes close.
6538 let (mut p, s1) = group();
6539 assert!(p.delete_in(Lane::V1, 0));
6540 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6541 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6542 assert_eq!(
6543 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6544 [60],
6545 "the caption's lane closed by its own span: the follower slid up"
6546 );
6547 assert!(p.undo(), "one step");
6548 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6549
6550 // By the sound: the same whole-group delete.
6551 let (mut p, s1) = group();
6552 assert!(p.delete_in(Lane::A1, 0));
6553 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6554 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6555
6556 // By the caption itself: the same again.
6557 let (mut p, s1) = group();
6558 assert!(p.delete_sub_in(s1, 0));
6559 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6560 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6561 assert!(links_are_consistent(&p.lanes).is_ok());
6562
6563 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6564 // unchanged.
6565 let (mut p, s1) = group();
6566 assert!(p.ungroup(s1, 0), "the caption stands alone");
6567 assert!(p.lift_sub(s1, 0));
6568 assert_eq!(
6569 p.sub_lane(s1)[0].start, 90,
6570 "the follower stayed put: a lone caption's lift is a gap"
6571 );
6572 }
6573
6574 /// Dragging a grouped caption carries its clips, one delta for all of them
6575 /// -- and a caption in no group refuses an overlap exactly as it always did.
6576 #[test]
6577 fn dragging_a_grouped_caption_carries_its_group() {
6578 let caption = |start: u32, frames: u32| SubClip {
6579 start,
6580 frames,
6581 track: 0,
6582 in_us: 0,
6583 out_us: i64::from(frames) * 1_000_000,
6584 link: None,
6585 };
6586 let track = || SubtitleTrack {
6587 path: FILE.into(),
6588 track: None,
6589 language: "eng".into(),
6590 name: String::new(),
6591 label: "eng".into(),
6592 cues: Vec::new(),
6593 bitmap: false,
6594 refused: None,
6595 };
6596 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6597 let s1 = p.add_lane(LaneKind::Subtitle);
6598 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6599 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6600
6601 // Same lane, further along: everyone moves by the same eight frames.
6602 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6603 assert_eq!(p.sub_lane(s1)[0].start, 10);
6604 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6605 assert!(links_are_consistent(&p.lanes).is_ok());
6606
6607 // ...and an ungrouped caption is the caption it always was.
6608 assert!(p.ungroup(s1, 0));
6609 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6610 let s1 = q.add_lane(LaneKind::Subtitle);
6611 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6612 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6613 assert!(q
6614 .move_sub(s1, 0, s1, 3)
6615 .unwrap_err()
6616 .to_string()
6617 .contains("already covers"));
6618 }
6619
6620 /// A trim carries a group's caption by the same delta as its clips, clamped
6621 /// to the caption's own walls -- the offsets between the members survive.
6622 #[test]
6623 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6624 let caption = |start: u32, frames: u32| SubClip {
6625 start,
6626 frames,
6627 track: 0,
6628 in_us: 0,
6629 out_us: i64::from(frames) * 1_000_000,
6630 link: None,
6631 };
6632 let track = || SubtitleTrack {
6633 path: FILE.into(),
6634 track: None,
6635 language: "eng".into(),
6636 name: String::new(),
6637 label: "eng".into(),
6638 cues: Vec::new(),
6639 bitmap: false,
6640 refused: None,
6641 };
6642 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6643 let s1 = p.add_lane(LaneKind::Subtitle);
6644 // The caption sits two frames into the take and ends one early. The
6645 // source runs past the clip, or there is no tail to pull out.
6646 let src = &[20];
6647 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6648 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6649
6650 // The tail goes out by three: the clip to 12, the caption to 11.
6651 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6652 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6653 assert_eq!(
6654 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6655 (2, 11),
6656 "the caption follows by the delta"
6657 );
6658 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6659
6660 // The head comes in by two: everyone's start moves two along.
6661 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6662 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6663 assert!(links_are_consistent(&p.lanes).is_ok());
6664 }
6665
6666 #[test]
6667 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6668 let mut p = three();
6669 let before = shape(&p);
6670 assert!(!p.split(0), "timeline 0 has nothing before it");
6671 assert!(!p.split(3), "existing boundary");
6672 assert!(!p.split(5), "existing boundary");
6673 assert!(!p.split(9), "one past the last frame");
6674 assert!(!p.split(1_000));
6675 assert_eq!(shape(&p), before);
6676 // one undo lands before the *second* split, so the refusals pushed nothing
6677 assert!(p.undo());
6678 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6679
6680 // ...and a frame that is a gap in both lanes has nothing to split.
6681 let mut p = three();
6682 assert!(p.lift(Lane::V1, 1));
6683 assert!(p.lift(Lane::A1, 1));
6684 assert!(!p.split(4), "a gap is not a clip");
6685 }
6686
6687 #[test]
6688 fn regroup_refuses_what_a_split_could_not_have_made() {
6689 let mut p = three();
6690 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6691 assert!(p.regroup(5));
6692 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6693 // A boundary with a gap on one side, and one where the sources do not
6694 // meet, are both refused.
6695 let mut p = three();
6696 assert!(p.lift(Lane::V1, 1));
6697 assert!(p.lift(Lane::A1, 1));
6698 assert!(!p.regroup(3), "nothing starts at 3 any more");
6699 let mut p = three();
6700 for l in p.lanes() {
6701 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6702 }
6703 assert!(!p.regroup(3), "source 100 does not follow source 3");
6704 assert!(!p.regroup(0), "nothing ends at 0");
6705 assert!(!p.regroup(1_000));
6706 }
6707
6708 #[test]
6709 fn map_and_spans_sweep_every_boundary() {
6710 let p = three();
6711 assert_eq!(p.timeline_frames(), 9);
6712 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6713 // contiguous source here, so the clip index is what actually moves
6714 let expect = [
6715 (0, (0, 0)),
6716 (1, (0, 1)),
6717 (2, (0, 2)),
6718 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6719 (4, (1, 4)),
6720 (5, (2, 5)),
6721 (6, (2, 6)),
6722 (7, (2, 7)),
6723 (8, (2, 8)),
6724 ];
6725 for (t, want) in expect {
6726 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6727 }
6728 assert_eq!(p.map_timeline(9), None);
6729 // A span is the rest of the clip from where it was asked about.
6730 assert_eq!(
6731 p.span_at(Lane::V1, 6),
6732 Some(Span {
6733 start: 6,
6734 len: 3,
6735 from: Some((0, 6)),
6736 speed: Speed::NORMAL
6737 })
6738 );
6739 assert_eq!(p.span_at(Lane::V1, 9), None);
6740 }
6741
6742 /// The fit policy is one byte *in* the clip rather than an index into a
6743 /// table like the eq and the grade: there is nothing for a table to share.
6744 /// It costs the clip nothing at all -- the fields before it (a `usize`
6745 /// source and two `Option<u16>`s) already left the struct padded to 40
6746 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
6747 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
6748 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
6749 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
6750 /// words after it pads out to the next multiple of 8: 56 bytes total.
6751 /// The transform index is a third `Option<u16>`, same reason as the eq and
6752 /// colour ones before it -- it lands in bytes already spent on padding, so
6753 /// the struct still costs 56.
6754 /// This is the assert that says so: a clip that grows a word grows every
6755 /// undo snapshot and every clipboard copy with it.
6756 #[test]
6757 fn a_fit_policy_costs_the_clip_no_word() {
6758 assert_eq!(
6759 std::mem::size_of::<Clip>(),
6760 56,
6761 "Clip changed size: {} bytes",
6762 std::mem::size_of::<Clip>()
6763 );
6764 }
6765
6766 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6767 /// anything in `three()` so it is recognisable wherever it lands.
6768 const PASTED: Clip = Clip {
6769 fade_in: 0,
6770 fade_out: 0,
6771 transition_out: 0,
6772 start: 0,
6773 in_frame: 100,
6774 out_frame: 102,
6775 source: 0,
6776 link: None,
6777 eq: None,
6778 color: None,
6779 transform: None,
6780 fit: FitPolicy::Fit,
6781 speed: Speed::NORMAL,
6782 };
6783
6784 #[test]
6785 fn paste_mid_clip_splits_around_it() {
6786 let mut p = three();
6787 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6788 assert_eq!(p.timeline_frames(), 11);
6789 assert_eq!(
6790 shape(&p)[0],
6791 vec![
6792 clip(0, 0, 3, 0),
6793 clip(3, 3, 5, 0),
6794 clip(5, 5, 6, 0),
6795 clip(6, 100, 102, 0),
6796 clip(8, 6, 9, 0),
6797 ]
6798 );
6799 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6800 // The pasted frames are exactly where they were asked for, and the
6801 // split-off remainder resumes after them.
6802 assert_eq!(p.map_timeline(6), Some((3, 100)));
6803 assert_eq!(p.map_timeline(7), Some((3, 101)));
6804 assert_eq!(p.map_timeline(8), Some((4, 6)));
6805 }
6806
6807 #[test]
6808 fn paste_at_boundary_zero_and_end() {
6809 let mut p = three();
6810 assert!(p.paste(3, PASTED), "existing boundary: no split");
6811 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6812 assert_eq!(p.map_timeline(3), Some((1, 100)));
6813
6814 let mut p = three();
6815 assert!(p.paste(0, PASTED));
6816 assert_eq!(p.map_timeline(0), Some((0, 100)));
6817 assert_eq!(p.map_timeline(2), Some((1, 0)));
6818
6819 // At the end: appended, there being nothing in front to leave black.
6820 let mut p = three();
6821 assert!(p.paste(9, PASTED));
6822 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6823 // Past it: down on the frame it was asked for, black in front of it --
6824 // a row let go on the open bed lands under the ghost that promised it.
6825 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6826 assert!(p.paste(1_000, PASTED));
6827 assert_eq!(p.timeline_frames(), 1_002);
6828 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6829 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6830
6831 // An empty clip is the one thing refused, and it pushes no history.
6832 let mut p = three();
6833 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6834 assert_eq!(p.clips().len(), 3);
6835 }
6836
6837 /// The data-loss paste: a clip of a source with no picture used to land on
6838 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6839 /// carried it was refused on the way back in ("a box with a larger size").
6840 #[test]
6841 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6842 let mut p = three();
6843 let wav = p.import("/nonexistent/song.wav", 0);
6844 let copied = Clip {
6845 fade_in: 0,
6846 fade_out: 0,
6847 transition_out: 0,
6848 source: wav,
6849 ..PASTED
6850 };
6851 assert!(p.paste(3, copied));
6852 // The room is opened on every lane, or the two would slide apart...
6853 assert_eq!(p.timeline_frames(), 11);
6854 assert_eq!(
6855 shape(&p)[0],
6856 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6857 "the video lane got room and nothing else"
6858 );
6859 // ...but the clip itself only reaches the lane that can play it.
6860 assert_eq!(
6861 shape(&p)[1],
6862 vec![
6863 clip(0, 0, 3, 0),
6864 clip(3, 100, 102, wav),
6865 clip(5, 3, 5, 0),
6866 clip(7, 5, 9, 0)
6867 ]
6868 );
6869 // A source with a picture is unchanged: still the grouped pair.
6870 let mut p = three();
6871 assert!(p.paste(3, PASTED));
6872 assert_eq!(shape(&p)[0], shape(&p)[1]);
6873 }
6874
6875 /// A hand-written file may hold a clip that ends at the very last frame
6876 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
6877 /// to wrap its start round to the front of the lane: an overlap in debug, a
6878 /// project no reload would accept in release.
6879 #[test]
6880 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
6881 let far = clip(u32::MAX - 90, 0, 90, 0);
6882 let parts = |c: Clip| {
6883 Project::from_parts(
6884 vec![Source::new(FILE, 0)],
6885 two(vec![c], vec![c]),
6886 Vec::new(),
6887 Vec::new(),
6888 Vec::new(),
6889 )
6890 .expect("valid parts")
6891 };
6892 let mut p = parts(far);
6893 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
6894 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
6895 assert!(!p.undo(), "...and pushes no history either");
6896 assert!(
6897 !p.paste(u32::MAX, PASTED),
6898 "appending has nowhere to go either: the timeline ends at the last frame"
6899 );
6900 // With room for exactly those frames the same paste is taken.
6901 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
6902 assert!(p.paste(0, PASTED));
6903 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
6904 }
6905
6906 #[test]
6907 fn paste_undoes_in_one_step() {
6908 let mut p = three();
6909 let before = shape(&p);
6910 assert!(p.paste(6, PASTED));
6911 assert!(p.undo());
6912 assert_eq!(shape(&p), before, "a paste is one undo step");
6913 }
6914
6915 #[test]
6916 fn a_copy_outlives_the_clip_it_came_from() {
6917 let mut p = three();
6918 let copied = p.clips()[1]; // [3,5)
6919 assert!(p.delete(1));
6920 // Just a frame range: the source is still on disk either way.
6921 assert!(p.paste(0, copied));
6922 assert_eq!(p.map_timeline(0), Some((0, 3)));
6923 assert_eq!(p.timeline_frames(), 9);
6924 }
6925
6926 #[test]
6927 fn delete_closes_the_gap_on_both_lanes() {
6928 let mut p = three();
6929 assert!(p.delete(1));
6930 assert_eq!(p.timeline_frames(), 7);
6931 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
6932 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
6933 // timeline 3 used to be source 3; the gap closed so it is source 5 now
6934 assert_eq!(p.map_timeline(3), Some((1, 5)));
6935 assert_eq!(p.map_timeline(6), Some((1, 8)));
6936 assert_eq!(p.map_timeline(7), None);
6937 }
6938
6939 #[test]
6940 fn delete_first_last_and_only() {
6941 let mut p = three();
6942 assert!(p.delete(0));
6943 assert_eq!(p.map_timeline(0), Some((0, 3)));
6944 assert_eq!(p.timeline_frames(), 6);
6945
6946 let mut p = three();
6947 assert!(p.delete(2));
6948 assert_eq!(p.timeline_frames(), 5);
6949 assert_eq!(p.map_timeline(4), Some((1, 4)));
6950
6951 assert!(!p.delete(2), "index past the end");
6952 assert!(p.delete(1));
6953 assert!(p.delete(0), "and the last remaining clip goes too");
6954 assert_eq!(p.clips().len(), 0);
6955 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
6956 assert!(!p.delete(0), "there is nothing left to delete");
6957 assert!(p.undo(), "one gesture, one undo");
6958 assert_eq!(p.clips().len(), 1);
6959 }
6960
6961 /// The offset model's point: one lane loses a clip, the other does not move.
6962 #[test]
6963 fn a_lift_leaves_a_gap_and_moves_nothing() {
6964 let mut p = three();
6965 let video_before = shape(&p)[0].clone();
6966 assert!(p.lift(Lane::A1, 1));
6967 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
6968 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
6969 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
6970 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
6971 assert_eq!(p.map(Lane::A1, 4), None);
6972 assert_eq!(
6973 p.span_at(Lane::A1, 3),
6974 Some(Span {
6975 start: 3,
6976 len: 2,
6977 from: None,
6978 speed: Speed::NORMAL
6979 })
6980 );
6981 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
6982 assert!(p.undo());
6983 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
6984 }
6985
6986 #[test]
6987 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
6988 let mut p = three();
6989 assert!(p.lift(Lane::A1, 2));
6990 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
6991 assert_eq!(
6992 p.span_at(Lane::A1, 5),
6993 Some(Span {
6994 start: 5,
6995 len: 4,
6996 from: None,
6997 speed: Speed::NORMAL
6998 }),
6999 "the audio lane holds silence to the end of the picture"
7000 );
7001 assert_eq!(p.span_at(Lane::A1, 9), None);
7002 // Every lane covers the timeline exactly, gaps included.
7003 for l in p.lanes() {
7004 let spans = p.spans_from(l, 0);
7005 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7006 assert_eq!(spans[0].start, 0);
7007 }
7008 }
7009
7010 /// The timeline is emptiable: the last placement comes off like any other,
7011 /// the project holds "nothing on any lane" as a state, and one undo per
7012 /// gesture brings it back.
7013 #[test]
7014 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7015 let mut p = Project::single(FILE, 9);
7016 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7017 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7018 assert_eq!(p.timeline_frames(), 0);
7019 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7020 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7021 assert!(!p.lift(Lane::A1, 0), "index past the end");
7022 assert!(p.undo(), "and the last lift comes back");
7023 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7024 // A saved-and-loaded empty timeline is a project like any other, and it
7025 // still names the file its frame rate came from.
7026 assert!(p.lift(Lane::V1, 0));
7027 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7028 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7029 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7030 assert_eq!(back.timeline_frames(), 0);
7031 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7032 }
7033
7034 /// What a keyboard selection walks: one answer per lane, gaps included --
7035 /// the composite's own answer is one lane's and cannot say what the audio
7036 /// lane holds under the same playhead.
7037 #[test]
7038 fn lane_clip_at_answers_for_each_lane_separately() {
7039 let mut p = Project::single(FILE, 9);
7040 assert!(p.split(3), "both lanes split");
7041 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7042 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7043 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7044 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7045 // A gap on one lane leaves the other's clip selectable there.
7046 assert!(p.lift(Lane::A1, 0));
7047 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7048 assert_eq!(
7049 p.lane_clip_at(Lane::A1, 3),
7050 Some(0),
7051 "indices moved with it"
7052 );
7053 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7054 // A lane that is not there is not a panic.
7055 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7056 }
7057
7058 #[test]
7059 fn place_overwrites_only_its_own_lane() {
7060 let mut p = three();
7061 let audio_before = shape(&p)[1].clone();
7062 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7063 // is trimmed, nothing shifts.
7064 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7065 assert_eq!(
7066 shape(&p)[0],
7067 vec![
7068 clip(0, 0, 3, 0),
7069 clip(3, 3, 4, 0),
7070 clip(4, 100, 102, 0),
7071 clip(6, 6, 9, 0),
7072 ]
7073 );
7074 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7075 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7076
7077 // Placed inside one clip, it splits it in two.
7078 let mut p = Project::single(FILE, 9);
7079 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7080 assert_eq!(
7081 shape(&p)[0],
7082 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7083 );
7084 // ...and placed past the end it makes a gap, which is the whole point.
7085 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7086 assert_eq!(p.timeline_frames(), 22);
7087 assert_eq!(
7088 p.span_at(Lane::V1, 9),
7089 Some(Span {
7090 start: 9,
7091 len: 11,
7092 from: None,
7093 speed: Speed::NORMAL
7094 })
7095 );
7096 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7097 }
7098
7099 /// A file with sound let go over a further video track: both halves go down,
7100 /// on the same frames, and the audio row is added when the `+ V` button left
7101 /// the project without one. One undo takes the lane and both clips back.
7102 #[test]
7103 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7104 let mut p = three();
7105 let v2 = p.add_lane(LaneKind::Video);
7106 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7107
7108 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7109 let a2 = Lane::new(LaneKind::Audio, 1);
7110 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7111 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7112 assert_eq!(p.lane(v2)[0].start, 4);
7113 assert_eq!(p.lane(v2)[0].end(), 6);
7114 assert_eq!(
7115 p.lane(v2)[0].link,
7116 p.lane(a2)[0].link,
7117 "one take, not two placements"
7118 );
7119 assert!(p.lane(v2)[0].link.is_some());
7120 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7121 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7122
7123 // The pair overwrites its own two lanes and nothing else, exactly as a
7124 // one-lane place does.
7125 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7126 assert_eq!(p.lane(v2), p.lane(a2));
7127 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7128 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7129
7130 assert!(p.undo(), "one step for the second pair");
7131 assert_eq!(p.lane(v2).len(), 1);
7132 assert!(p.undo(), "one step for the first pair *and* its lane");
7133 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7134 assert!(p.lane(v2).is_empty());
7135
7136 // Refusals cost nothing: sound placed alone is `place`'s door.
7137 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7138 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7139 assert!(
7140 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7141 "a lane that is not there"
7142 );
7143 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7144 }
7145
7146 /// The drag between tracks: let go at the frames it already covers the clip
7147 /// keeps them, one undo takes it back, and every way it can be refused
7148 /// leaves the project untouched.
7149 #[test]
7150 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7151 let v2 = Lane::new(LaneKind::Video, 1);
7152 let mut p = three();
7153 assert_eq!(p.add_lane(LaneKind::Video), v2);
7154 let before = shape(&p);
7155
7156 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7157 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7158 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7159 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7160 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7161 // One snapshot: a single undo, and the lane list survives it.
7162 assert!(p.undo());
7163 assert_eq!(shape(&p), before);
7164
7165 // A lane that is not there, the lane and frame it is already at, an
7166 // index that is not there, and a move across kinds: all refused,
7167 // nothing changed.
7168 let history = p.history.len();
7169 for (from, idx, to, start) in [
7170 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7171 (Lane::V1, 1, Lane::V1, 3),
7172 (Lane::V1, 9, v2, 3),
7173 (Lane::V1, 1, Lane::A1, 3),
7174 (Lane::A1, 1, v2, 3),
7175 ] {
7176 assert!(
7177 !p.move_clip(from, idx, to, start),
7178 "{from:?} {idx} -> {to:?} at {start}"
7179 );
7180 }
7181 assert_eq!(shape(&p), before);
7182 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7183
7184 // Landing on another clip is refused rather than overwriting it: the
7185 // pointer named the lane, never the take already sitting there.
7186 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7187 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7188 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7189 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7190 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7191 }
7192
7193 /// The drag *along* a track, which is the one every other editor has: the
7194 /// clip lands on the frame the pointer let it go at, and stops dead against
7195 /// the neighbour rather than overwriting it.
7196 #[test]
7197 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7198 let sources = vec![Source::new(FILE, 0)];
7199 let lanes = vec![
7200 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7201 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7202 ];
7203 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7204 let before = shape(&p);
7205
7206 // Into the gap, exactly where it was let go -- nothing else moves.
7207 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7208 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7209 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7210 // Dragged past the clip in front of it: clamped to its wall, laid end
7211 // to end with it, never over it.
7212 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7213 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7214 // One undo per drag, and both of them together are the state it started
7215 // in -- the frames each clip plays never changed.
7216 assert!(p.undo() && p.undo());
7217 assert_eq!(shape(&p), before);
7218
7219 // A drop that changes nothing is a click, not an edit.
7220 let history = p.history.len();
7221 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7222 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7223 }
7224
7225 /// A drag carries the whole take: the sound half travels exactly as far as
7226 /// the picture does, and the tighter of their two walls stops both.
7227 #[test]
7228 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7229 let mut p = three();
7230 assert!(
7231 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7232 "room to the right"
7233 );
7234 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7235 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7236 // Something in the sound's way, and nothing at all in the picture's.
7237 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7238 let before = shape(&p);
7239
7240 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7241 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7242 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7243 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7244 assert!(p.undo());
7245 assert_eq!(shape(&p), before, "one undo for the whole take");
7246 }
7247
7248 /// The drag that does both at once -- another lane *and* another frame --
7249 /// which is what a pointer let go over a lane always names.
7250 #[test]
7251 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7252 let v2 = Lane::new(LaneKind::Video, 1);
7253 let mut p = three();
7254 assert_eq!(p.add_lane(LaneKind::Video), v2);
7255
7256 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7257 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7258 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7259 assert_eq!(
7260 p.lane(Lane::A1)[2].start,
7261 20,
7262 "its sound travelled the same distance"
7263 );
7264 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7265 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7266 }
7267
7268 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7269 /// [`three`] cuts up all nine of its frames.
7270 const SRC: &[u32] = &[9];
7271
7272 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7273 /// else on the lane moves, and every wall stops the edge rather than
7274 /// refusing the gesture.
7275 #[test]
7276 fn trimming_the_tail_stops_at_every_wall() {
7277 let mut p = three();
7278
7279 // Pulled in: a gap opens behind it and the clip after it stays put.
7280 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7281 assert_eq!(
7282 shape(&p)[0],
7283 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7284 );
7285 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7286 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7287
7288 // ...and back out, no further than the clip behind it.
7289 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7290 assert_eq!(
7291 shape(&p)[0][1],
7292 clip(3, 3, 5, 0),
7293 "stopped at the neighbour"
7294 );
7295 assert!(
7296 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7297 "already at the wall"
7298 );
7299
7300 // One frame of clip always survives, however far back the pointer went.
7301 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7302 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7303
7304 // The last clip has no neighbour, so what stops it is the file: nine
7305 // frames is nine frames.
7306 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7307 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7308 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7309 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7310 // A source nobody told us the length of may not grow at all -- an
7311 // out-point past the end of a file is a save that will not open again.
7312 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7313 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7314 }
7315
7316 /// The head pulled in takes the in-point with it -- what stays plays what it
7317 /// always played -- and stops at the source's own first frame.
7318 #[test]
7319 fn trimming_the_head_moves_the_in_point() {
7320 let mut p = three();
7321 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7322 assert_eq!(
7323 shape(&p)[0][0],
7324 clip(2, 2, 3, 0),
7325 "two frames off the front"
7326 );
7327 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7328 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7329 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7330 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7331 // One frame survives here too.
7332 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7333 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7334
7335 // A clip that does not begin at its source's first frame: its head goes
7336 // back to source frame 0 and not one frame further.
7337 let mut p = Project::single(FILE, 9);
7338 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7339 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7340 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7341 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7342 }
7343
7344 /// A clip whose in-point is *past* its own start -- what a ripple delete
7345 /// leaves, the piece in front of it gone and this one slid back to frame 0
7346 /// carrying the in-point the cut gave it. Its head has more source behind it
7347 /// than the timeline has room for, and the timeline's own first frame is the
7348 /// wall: asking is not an overflow, and the answer is 0.
7349 #[test]
7350 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
7351 let mut p = Project::single(FILE, 9);
7352 assert!(p.split(5));
7353 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
7354 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
7355
7356 assert_eq!(
7357 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
7358 Some((0, 3)),
7359 "back to frame 0 at most, and one frame of clip always survives"
7360 );
7361 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
7362 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7363 assert_eq!(
7364 shape(&p)[0],
7365 vec![clip(2, 7, 9, 0)],
7366 "the in-point followed"
7367 );
7368 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
7369 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
7370 }
7371
7372 /// A still is trimmed from its head exactly as it is from its tail: it has
7373 /// no earlier frame to walk an in-point back to, so the wall is the length
7374 /// the caller's table allows it, measured back from the tail. Measured from
7375 /// the in-point -- which a placed picture has at 0 -- its left edge could
7376 /// never be dragged outwards at all.
7377 #[test]
7378 fn a_stills_head_stretches_out_like_its_tail() {
7379 const STILL: &str = "/nonexistent/card.png";
7380 /// What a still is held to, as `PlaybackSession` fills the table in.
7381 const CAP: &[u32] = &[60];
7382
7383 let mut p = Project::single(STILL, 20);
7384 assert!(p.lift(Lane::A1, 0), "a picture is silent");
7385 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
7386 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
7387
7388 // A source with no entry in the table may not grow, here as at the tail.
7389 assert_eq!(
7390 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
7391 Some((100, 119)),
7392 "a length nobody told us buys no head room"
7393 );
7394 assert_eq!(
7395 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
7396 Some((60, 119)),
7397 "back to a whole cap's worth, one frame of clip surviving"
7398 );
7399 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
7400 assert_eq!(
7401 shape(&p)[0][0],
7402 clip(80, 0, 40, 0),
7403 "twenty frames longer, and still read from the source's first frame"
7404 );
7405 // Past the cap is clamped, exactly as the tail is -- not refused.
7406 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
7407 assert_eq!(
7408 shape(&p)[0][0],
7409 clip(60, 0, 60, 0),
7410 "a cap's worth, no more"
7411 );
7412 // ...and the clip in front is the nearer wall of the two: no head trim
7413 // may open an overlap.
7414 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
7415 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
7416 assert_eq!(
7417 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
7418 Some((85, 119)),
7419 "up to the neighbour's last frame and not over it"
7420 );
7421 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
7422 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
7423 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
7424 }
7425
7426 /// Linked halves trim as one: a link is one span on however many lanes, so
7427 /// the sound follows the picture's edge -- and the tightest wall of the two
7428 /// is what stops both.
7429 #[test]
7430 fn linked_halves_trim_together() {
7431 let mut p = three();
7432 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
7433 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
7434
7435 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
7436 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
7437 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
7438 assert!(
7439 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
7440 "either half drags it"
7441 );
7442 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
7443 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7444
7445 // Something in the way on the *audio* lane stops the picture's tail as
7446 // well: the group can only go as far as its tightest member.
7447 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
7448 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7449 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
7450 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
7451 links_are_consistent(&p.lanes).expect("still one span");
7452 }
7453
7454 /// A whole drag is one undo step -- the front-end commits once, at the
7455 /// release -- and an edge asked to stay where it is costs none at all.
7456 #[test]
7457 fn a_trim_is_one_undo_step() {
7458 let mut p = three();
7459 let before = shape(&p);
7460 let history = p.history.len();
7461
7462 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7463 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7464 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7465 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7466 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7467 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7468
7469 assert!(p.undo());
7470 assert_eq!(shape(&p), before, "both halves back, in one step");
7471 }
7472
7473 /// A moved half stays in its group: a link names a span, not a lane, so the
7474 /// picture on `V2` is still the same take as the sound under it on `A1`.
7475 #[test]
7476 fn move_clip_keeps_the_group() {
7477 let v2 = Lane::new(LaneKind::Video, 1);
7478 let mut p = three();
7479 p.add_lane(LaneKind::Video);
7480 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7481 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7482 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7483 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7484 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7485 assert_eq!(
7486 p.lane(v2)[0].start,
7487 p.lane(Lane::A1)[1].start,
7488 "and still covers the same span as its sound"
7489 );
7490 }
7491
7492 #[test]
7493 fn ripple_delete_spans_partial_clips() {
7494 let mut p = three();
7495 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
7496 assert!(p.ripple_delete(2, 4));
7497 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
7498 assert_eq!(shape(&p)[1], shape(&p)[0]);
7499 assert_eq!(p.timeline_frames(), 5);
7500 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
7501 assert!(p.undo());
7502 assert_eq!(shape(&p), shape(&three()));
7503 // One that takes everything is a delete like any other: the timeline
7504 // empties, and the undo it cost brings it back whole.
7505 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
7506 assert_eq!(p.timeline_frames(), 0);
7507 assert!(
7508 !p.ripple_delete(0, 100),
7509 "and a delete with nothing left to take is not an undo step"
7510 );
7511 assert!(p.undo());
7512 assert_eq!(shape(&p), shape(&three()));
7513 }
7514
7515 #[test]
7516 fn undo_restores_exactly() {
7517 let mut p = three();
7518 let after_splits = shape(&p);
7519 assert!(p.delete(1));
7520 assert!(p.undo());
7521 assert_eq!(shape(&p), after_splits);
7522
7523 // walk all the way back through both splits, then run dry
7524 assert!(p.undo());
7525 assert_eq!(p.clips().len(), 2);
7526 assert!(p.undo());
7527 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7528 assert!(!p.undo(), "empty history");
7529 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7530 }
7531
7532 #[test]
7533 fn redo_restores_exactly() {
7534 let mut p = three();
7535 assert!(p.delete(1));
7536 let after_delete = p.parts();
7537 assert!(p.undo());
7538 assert!(p.redo());
7539 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
7540 assert!(!p.redo(), "empty redo stack");
7541 }
7542
7543 #[test]
7544 fn edit_after_undo_empties_redo() {
7545 let mut p = three();
7546 assert!(p.delete(1));
7547 assert!(p.undo());
7548 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
7549 assert!(p.split(1), "a fresh edit");
7550 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
7551 assert!(!p.redo(), "so redo has nothing left");
7552 }
7553
7554 #[test]
7555 fn redo_on_empty_stack_is_false() {
7556 let mut p = three();
7557 assert!(!p.redo(), "nothing has been undone yet");
7558 }
7559
7560 /// Past the cap the *oldest* step goes, so a long session undoes exactly
7561 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
7562 #[test]
7563 fn history_stops_at_the_cap() {
7564 let mut p = Project::single(FILE, 400);
7565 for frame in 1..=150 {
7566 assert!(p.split(frame), "split {frame} is an edit");
7567 }
7568 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
7569 for step in 0..HISTORY_CAP {
7570 assert!(p.undo(), "undo {step} is inside the cap");
7571 }
7572 assert!(!p.undo(), "and the 101st has nothing left to take");
7573 // 100 undos off 150 splits is the timeline after the 50th: the older
7574 // steps were dropped, not the newer ones.
7575 assert_eq!(p.clips().len(), 51);
7576 }
7577
7578 /// Undo/redo by hand across a split must never merge two takes into one
7579 /// group by reusing an id.
7580 #[test]
7581 fn group_ids_are_never_reused() {
7582 let mut p = Project::single(FILE, 9);
7583 assert!(p.split(3));
7584 let first = p.clips()[1].link;
7585 assert!(p.undo());
7586 assert!(p.split(5));
7587 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
7588 }
7589
7590 #[test]
7591 fn segments_from_reads_the_audio_lane() {
7592 let p = three();
7593 // mid-clip: partial first segment, whole clips after it
7594 assert_eq!(
7595 p.segments_from(4, FPS),
7596 vec![
7597 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7598 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7599 ]
7600 );
7601 // on a boundary: nothing partial
7602 assert_eq!(
7603 p.segments_from(3, FPS),
7604 vec![
7605 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7606 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7607 ]
7608 );
7609 // from the top: one entry per clip
7610 assert_eq!(p.segments_from(0, FPS).len(), 3);
7611 // last clip only
7612 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7613 // past the end / unusable fps
7614 assert!(p.segments_from(9, FPS).is_empty());
7615 assert!(p.segments_from(0, 0.0).is_empty());
7616 assert!(p.segments_from(0, f64::NAN).is_empty());
7617 }
7618
7619 #[test]
7620 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7621 let mut p = three();
7622 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7623 assert_eq!(
7624 p.segments_from(0, FPS),
7625 vec![
7626 (Some(0), 0.0, 3.0 / 30.0),
7627 (None, 0.0, 2.0 / 30.0),
7628 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7629 ]
7630 );
7631 // The list still covers exactly the timeline: that is what stops the
7632 // master clock stalling at the hole.
7633 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7634 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7635 // Starting inside the gap trims the silence, not the clip after it.
7636 assert_eq!(
7637 p.segments_from(4, FPS),
7638 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7639 );
7640 // ...and a lane that is nothing but gap is a run of silence.
7641 assert!(p.lift(Lane::A1, 0));
7642 assert!(p.lift(Lane::A1, 0));
7643 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7644 }
7645
7646 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7647 /// of source 0 then [0,4) of source 1.
7648 fn two_sources() -> Project {
7649 let mut p = three();
7650 let s = p.import(FILE2, 0);
7651 assert_eq!(s, 1);
7652 assert!(p.append_clip(s, 4));
7653 p
7654 }
7655
7656 #[test]
7657 fn import_dedups_and_appends() {
7658 let mut p = Project::single(FILE, 9);
7659 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7660 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7661 assert_eq!(p.import(FILE2, 0), 1);
7662 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7663 // ...but the same file on another audio stream is another source: it is
7664 // what a clip names, and a clip plays exactly one stream.
7665 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7666 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7667 assert_eq!(p.sources()[2].audio_stream, 1);
7668 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7669 assert!(p.undo());
7670 assert_eq!(p.sources().len(), 3);
7671 assert!(!p.append_clip(3, 5), "unknown source index");
7672 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7673
7674 // Two spellings of one real file are one source: this is the case the
7675 // raw-path comparison above would get wrong.
7676 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7677 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7678 let mut p = Project::single(here, 9);
7679 assert_eq!(p.import(detour, 0), 0);
7680 assert_eq!(p.sources().len(), 1);
7681 }
7682
7683 #[test]
7684 fn append_clip_is_one_undo_step() {
7685 let mut p = two_sources();
7686 assert_eq!(p.timeline_frames(), 13);
7687 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7688 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7689 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7690 assert!(p.undo());
7691 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7692 assert_eq!(
7693 p.sources().len(),
7694 2,
7695 "the orphan source entry stays -- indexes are forever"
7696 );
7697 // ...and it is still usable, so a redo-by-hand costs no reimport.
7698 assert!(p.append_clip(1, 0));
7699 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7700 }
7701
7702 #[test]
7703 fn edits_carry_the_source_along() {
7704 let mut p = two_sources();
7705 // A split inside the second source splits into two source-1 clips.
7706 assert!(p.split(11));
7707 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7708 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7709
7710 // A source-1 clip pasted into source-0 territory keeps its file, and so
7711 // does the source-0 half that got split off around it.
7712 let copied = p.clips()[4];
7713 assert!(p.paste(1, copied));
7714 assert_eq!(p.clips()[1].source, 1);
7715 assert_eq!(p.clips()[1].in_frame, 2);
7716 assert_eq!(p.clips()[2].source, 0);
7717 assert!(p.undo());
7718 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
7719 }
7720
7721 #[test]
7722 fn segments_from_names_the_source() {
7723 let p = two_sources();
7724 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
7725 assert_eq!(
7726 p.segments_from(4, FPS),
7727 vec![
7728 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7729 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7730 (Some(1), 0.0, 4.0 / 30.0),
7731 ]
7732 );
7733 // Mid-clip in source 1: only that source is left.
7734 assert_eq!(
7735 p.segments_from(10, FPS),
7736 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
7737 );
7738 assert!(p.segments_from(13, FPS).is_empty());
7739 // Segments still cover exactly the timeline across the join.
7740 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7741 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
7742 }
7743
7744 #[test]
7745 fn segments_follow_deletes_and_fps() {
7746 let mut p = three();
7747 assert!(p.delete(0));
7748 // source seconds, not timeline: deleting the head does not shift them
7749 let segs = p.segments_from(0, 25.0);
7750 assert_eq!(
7751 segs,
7752 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
7753 );
7754 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
7755 assert!(
7756 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
7757 "segments must cover exactly the timeline: {played}"
7758 );
7759 }
7760
7761 #[test]
7762 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
7763 // Import a second file, undo it: source 1 is now an orphan.
7764 let mut p = two_sources();
7765 assert!(p.undo());
7766 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7767 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
7768 assert!(eq.is_empty(), "and a project with no equalizer writes none");
7769 assert!(color.is_empty(), "nor a colour it never graded with");
7770 assert_eq!(
7771 lanes,
7772 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
7773 "the clips are untouched"
7774 );
7775
7776 // Three sources where only the middle one is orphaned: the survivors
7777 // renumber, and the clips follow.
7778 let mut p = Project::single(FILE, 9);
7779 assert_eq!(p.import(FILE2, 0), 1);
7780 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
7781 assert!(p.append_clip(2, 4));
7782 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7783 assert_eq!(
7784 sources,
7785 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
7786 );
7787 assert_eq!(
7788 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
7789 [0, 1]
7790 );
7791 // ...and what comes out is loadable, with the same timeline.
7792 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
7793 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
7794 assert_eq!(reloaded.sources().len(), 2);
7795 }
7796
7797 /// Taking a file out of the library: refused by name -- lanes and counts --
7798 /// while a clip still plays from it, and once nothing does, the entry goes
7799 /// and every clip that indexed past it is renumbered onto the short list.
7800 #[test]
7801 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
7802 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
7803 // plus a second stream of FILE as source 2 with a take of its own.
7804 let mut p = two_sources();
7805 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
7806 assert!(p.append_clip(2, 4));
7807
7808 let refusal = p
7809 .remove_source(1)
7810 .expect_err("a source with clips on it cannot go")
7811 .to_string();
7812 assert!(refusal.contains(FILE2), "names the file: {refusal}");
7813 assert!(
7814 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
7815 "names the lanes holding it: {refusal}"
7816 );
7817 assert!(refusal.contains("still plays"), "{refusal}");
7818 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
7819 assert_eq!(shape(&p)[0][3].source, 1);
7820
7821 // Delete FILE2's take -- the whole span, on every lane -- and the entry
7822 // is free to go. Source 2's clips become source 1's.
7823 assert!(p.delete_in(Lane::V1, 3));
7824 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
7825 p.remove_source(1).expect("nothing plays FILE2 any more");
7826 assert_eq!(
7827 p.sources(),
7828 [Source::new(FILE, 0), Source::new(FILE, 1)],
7829 "the middle entry is gone"
7830 );
7831 assert_eq!(
7832 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
7833 [0, 0, 0, 1],
7834 "the clips past it renumbered"
7835 );
7836 assert_eq!(
7837 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
7838 [0, 0, 0, 1],
7839 "on every lane"
7840 );
7841 // What is left is a project that still loads, which is the whole point
7842 // of renumbering rather than leaving a hole.
7843 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7844 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
7845 }
7846
7847 /// The two edges of a removal: it retires the undo stack (the corner-cut on
7848 /// [`Project::remove_source`]), and the last entry goes like any other
7849 /// once nothing plays it -- a project may name no file at all.
7850 #[test]
7851 fn remove_source_retires_undo_and_empties_the_library() {
7852 let mut p = two_sources();
7853 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
7854 assert!(!p.history.is_empty(), "there is something to undo");
7855 p.remove_source(1).expect("nothing plays FILE2");
7856 assert!(
7857 p.history.is_empty(),
7858 "a snapshot naming the removed source must not survive it"
7859 );
7860 assert!(!p.undo(), "and so there is nothing left to undo");
7861
7862 // The last file standing is held to the one rule every row is -- what
7863 // plays cannot go -- and to no other.
7864 assert_eq!(p.sources().len(), 1);
7865 let refusal = p
7866 .remove_source(0)
7867 .expect_err("its clips are still on the lanes")
7868 .to_string();
7869 assert!(refusal.contains("still plays"), "{refusal}");
7870 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
7871 while p.delete_in(Lane::V1, 0) {}
7872 p.remove_source(0)
7873 .expect("the last row goes like any other");
7874 assert!(
7875 p.sources().is_empty(),
7876 "a project may name no file at all: an empty library over an empty timeline"
7877 );
7878 assert_eq!(p.timeline_frames(), 0);
7879 assert!(
7880 p.remove_source(0).is_err(),
7881 "and an index that is not there is refused, not panicked on"
7882 );
7883 }
7884
7885 /// A clip's equalizer is the clip's: it survives every edit that copies a
7886 /// placement, and it comes back with an undo.
7887 #[test]
7888 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
7889 let mut p = three();
7890 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
7891 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
7892 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7893 assert!(
7894 p.eq_of(Lane::V1, 0).is_none(),
7895 "one clip, not the lane above"
7896 );
7897
7898 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
7899 assert!(p.split(1));
7900 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7901 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
7902 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
7903
7904 // A clipboard copy carries it -- onto another lane, at that.
7905 let copied = p.lane(Lane::A1)[1];
7906 assert!(p.place(Lane::V1, 20, copied));
7907 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
7908 assert!(p.undo());
7909 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
7910
7911 // ...and a change to one is one undo step, in both directions.
7912 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
7913 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
7914 assert!(p.undo());
7915 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7916 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
7917 assert!(p.eq_of(Lane::A1, 0).is_none());
7918 assert!(p.undo());
7919 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7920
7921 // Two refusals, neither of which costs an undo step.
7922 let mut nan = band_at(1);
7923 nan.bands[0].q = f32::INFINITY;
7924 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
7925 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
7926 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7927 assert!(p.undo());
7928 assert_eq!(
7929 p.lane(Lane::A1).len(),
7930 3,
7931 "one step back is before the split"
7932 );
7933 assert!(p.undo());
7934 assert!(
7935 p.eq_of(Lane::A1, 0).is_none(),
7936 "and the next is before the setting: the refusals pushed none"
7937 );
7938 }
7939
7940 /// The table is append-only within a session, exactly as the sources are, so
7941 /// an undone setting is still in it -- and a save is where it goes.
7942 #[test]
7943 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
7944 let mut p = three();
7945 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
7946 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
7947 assert!(p.undo(), "back to the first setting");
7948 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
7949
7950 let (_, lanes, eq, _, _) = p.without_orphan_sources();
7951 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
7952 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
7953 assert_eq!(lanes[0].1[1].eq, None);
7954
7955 // One curve on three clips is one entry: settings that are equal share.
7956 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
7957 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
7958 let (_, lanes, eq, _, _) = p.without_orphan_sources();
7959 assert_eq!(eq.len(), 1, "equal settings share their entry");
7960 assert_eq!(lanes[1].1[2].eq, Some(0));
7961 reloads(&p, "an equalizer that outlived an undo");
7962 }
7963
7964 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
7965 /// grade is the clip's, through every edit that copies a placement.
7966 #[test]
7967 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
7968 let mut p = three();
7969 assert!(
7970 p.color_of(Lane::V1, 0).is_none(),
7971 "a fresh clip is ungraded"
7972 );
7973 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
7974 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7975 assert!(
7976 p.color_of(Lane::A1, 0).is_none(),
7977 "one clip, not the lane below"
7978 );
7979 assert!(
7980 p.eq_of(Lane::V1, 0).is_none(),
7981 "and a grade is not an equalizer"
7982 );
7983
7984 // Cutting a graded clip must not grade half of it: both halves inherit.
7985 assert!(p.split(1));
7986 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
7987 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
7988 assert!(
7989 p.color_of(Lane::V1, 2).is_none(),
7990 "the clip after it is ungraded"
7991 );
7992
7993 // A clipboard copy carries it -- onto another lane, at that.
7994 let copied = p.lane(Lane::V1)[1];
7995 assert!(p.place(Lane::A1, 20, copied));
7996 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
7997 assert!(p.undo());
7998 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
7999
8000 // ...and a change to one is one undo step, in both directions.
8001 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
8002 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
8003 assert!(p.undo());
8004 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8005 assert!(
8006 p.set_color(Lane::V1, 0, None),
8007 "and taking it off is an edit"
8008 );
8009 assert!(p.color_of(Lane::V1, 0).is_none());
8010 assert!(p.undo());
8011 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8012
8013 // Two refusals, neither of which costs an undo step.
8014 let nan = ColorParams {
8015 contrast: f32::NAN,
8016 ..grade_at(1)
8017 };
8018 assert!(
8019 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
8020 "no clip there"
8021 );
8022 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
8023 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8024 assert!(p.undo());
8025 assert_eq!(
8026 p.lane(Lane::V1).len(),
8027 3,
8028 "one step back is before the split"
8029 );
8030 assert!(p.undo());
8031 assert!(
8032 p.color_of(Lane::V1, 0).is_none(),
8033 "and the next is before the grade: the refusals pushed none"
8034 );
8035 }
8036
8037 /// A slider drag is one gesture: the press snapshots, every sample after it
8038 /// only regrades, and the single undo lands on what the clip was *before*
8039 /// the hand touched it -- not one step back down the drag.
8040 #[test]
8041 fn a_whole_colour_drag_undoes_in_one_step() {
8042 let mut p = three();
8043 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
8044 for n in 2..=8 {
8045 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
8046 }
8047 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
8048 assert!(p.undo());
8049 assert!(
8050 p.color_of(Lane::V1, 0).is_none(),
8051 "one undo is the whole gesture, back to ungraded"
8052 );
8053
8054 // The live write refuses what the snapshotting one refuses, and a
8055 // refusal still costs no history either way.
8056 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
8057 assert!(!p.set_color_live(
8058 Lane::V1,
8059 0,
8060 Some(ColorParams {
8061 contrast: f32::NAN,
8062 ..grade_at(1)
8063 })
8064 ));
8065 assert!(p.undo());
8066 assert_eq!(
8067 p.lane(Lane::V1).len(),
8068 2,
8069 "the next step back is the split before the drag: no sample pushed one"
8070 );
8071 }
8072
8073 /// The colour table is append-only within a session, exactly as the eq one
8074 /// is -- and a save is where an undone grade goes.
8075 #[test]
8076 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
8077 let mut p = three();
8078 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
8079 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8080 assert!(p.undo(), "back to the first grade");
8081 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
8082
8083 let (_, lanes, _, color, _) = p.without_orphan_sources();
8084 assert_eq!(
8085 color,
8086 vec![grade_at(1)],
8087 "what nothing plays is not written"
8088 );
8089 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
8090 assert_eq!(lanes[0].1[1].color, None);
8091
8092 // One grade on three clips is one entry: settings that are equal share.
8093 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
8094 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
8095 let (_, lanes, _, color, _) = p.without_orphan_sources();
8096 assert_eq!(color.len(), 1, "equal grades share their entry");
8097 assert_eq!(lanes[1].1[2].color, Some(0));
8098 reloads(&p, "a colour that outlived an undo");
8099
8100 // An equalizer and a grade on one clip are two independent tables.
8101 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
8102 let (_, lanes, eq, color, _) = p.without_orphan_sources();
8103 assert_eq!((eq.len(), color.len()), (1, 1));
8104 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
8105 }
8106
8107 /// Not a claim about correctness but about cost: a clip is copied on every
8108 /// paste, every undo snapshot and every lane clone, so its size is worth
8109 /// knowing. The eq index fit the padding a `Copy` clip already had; the
8110 /// colour one did not, and the struct grew a word. The transform index is
8111 /// a third `Option<u16>`, and it fits the padding the fit policy and the
8112 /// transition byte already left behind, so the struct did not grow again.
8113 #[test]
8114 fn a_clip_is_still_a_small_copy() {
8115 assert_eq!(
8116 std::mem::size_of::<Clip>(),
8117 56,
8118 "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index"
8119 );
8120 }
8121
8122 #[test]
8123 fn from_parts_has_no_history_and_checks_the_invariants() {
8124 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
8125 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
8126 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
8127 .expect("valid parts");
8128 assert_eq!(p.clips(), three().clips());
8129 assert!(!p.undo(), "a loaded project has nothing to undo");
8130 assert!(p.split(4), "...and is editable from there");
8131 assert!(p.undo());
8132
8133 // A lane may be empty, and so may every lane -- an emptied timeline is a
8134 // project. No lane at all is not one: there would be nothing to place on.
8135 assert!(
8136 Project::from_parts(
8137 sources.clone(),
8138 two(video.clone(), Vec::new()),
8139 Vec::new(),
8140 Vec::new(),
8141 Vec::new(),
8142 )
8143 .is_ok()
8144 );
8145 assert!(
8146 Project::from_parts(
8147 sources.clone(),
8148 two(Vec::new(), Vec::new()),
8149 Vec::new(),
8150 Vec::new(),
8151 Vec::new(),
8152 )
8153 .is_ok()
8154 );
8155 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
8156 let bad: [Vec<Clip>; 5] = [
8157 vec![clip(0, 0, 3, 1)], // source that is not there
8158 vec![clip(0, 3, 3, 0)], // empty clip
8159 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
8160 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
8161 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
8162 ];
8163 for clips in bad {
8164 assert!(
8165 Project::from_parts(
8166 sources.clone(),
8167 two(clips.clone(), Vec::new()),
8168 Vec::new(),
8169 Vec::new(),
8170 Vec::new(),
8171 )
8172 .is_err(),
8173 "{clips:?}"
8174 );
8175 assert!(
8176 Project::from_parts(
8177 sources.clone(),
8178 two(video.clone(), clips.clone()),
8179 Vec::new(),
8180 Vec::new(),
8181 Vec::new(),
8182 )
8183 .is_err()
8184 );
8185 // ...and on a third lane, which is checked by the same walk.
8186 assert!(
8187 Project::from_parts(
8188 sources.clone(),
8189 vec![
8190 (LaneKind::Video, video.clone()),
8191 (LaneKind::Audio, audio.clone()),
8192 (LaneKind::Video, clips),
8193 ],
8194 Vec::new(),
8195 Vec::new(),
8196 Vec::new(),
8197 )
8198 .is_err()
8199 );
8200 }
8201 // An equalizer index no table entry answers, and a table entry the file
8202 // format could not have written, are refused at this door too.
8203 let eqd = |i: u16| {
8204 vec![Clip {
8205 fade_in: 0,
8206 fade_out: 0,
8207 transition_out: 0,
8208 eq: Some(i),
8209 ..video[0]
8210 }]
8211 };
8212 assert!(
8213 Project::from_parts(
8214 sources.clone(),
8215 two(eqd(0), Vec::new()),
8216 Vec::new(),
8217 Vec::new(),
8218 Vec::new(),
8219 )
8220 .is_err()
8221 );
8222 let mut nan = band_at(1);
8223 nan.bands[0].freq_hz = f32::NAN;
8224 assert!(
8225 Project::from_parts(
8226 sources.clone(),
8227 two(eqd(0), Vec::new()),
8228 vec![nan],
8229 Vec::new(),
8230 Vec::new(),
8231 )
8232 .is_err()
8233 );
8234 let loaded = Project::from_parts(
8235 sources.clone(),
8236 two(eqd(0), Vec::new()),
8237 vec![band_at(1)],
8238 Vec::new(),
8239 Vec::new(),
8240 )
8241 .expect("an eq the table holds");
8242 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
8243
8244 // The same two refusals for a colour, at the same door.
8245 let graded = |i: u16| {
8246 vec![Clip {
8247 fade_in: 0,
8248 fade_out: 0,
8249 transition_out: 0,
8250 color: Some(i),
8251 fit: FitPolicy::default(),
8252 speed: Speed::NORMAL,
8253 ..video[0]
8254 }]
8255 };
8256 assert!(
8257 Project::from_parts(
8258 sources.clone(),
8259 two(graded(0), Vec::new()),
8260 Vec::new(),
8261 Vec::new(),
8262 Vec::new(),
8263 )
8264 .is_err(),
8265 "a colour index no entry answers"
8266 );
8267 assert!(
8268 Project::from_parts(
8269 sources.clone(),
8270 two(graded(0), Vec::new()),
8271 Vec::new(),
8272 vec![ColorParams {
8273 tint: f32::NAN,
8274 ..grade_at(1)
8275 }],
8276 Vec::new(),
8277 )
8278 .is_err(),
8279 "a value the file format could not have written"
8280 );
8281 let loaded = Project::from_parts(
8282 sources.clone(),
8283 two(graded(0), Vec::new()),
8284 Vec::new(),
8285 vec![grade_at(1)],
8286 Vec::new(),
8287 )
8288 .expect("a colour the table holds");
8289 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
8290
8291 // Group ids survive a load, and the next split gets a fresh one.
8292 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
8293 assert!(p.split(4));
8294 assert!(p.clips().iter().all(|c| c.link.is_some()));
8295 }
8296
8297 /// The grouping rules, at the untrusted door and after every edit that can
8298 /// touch a link. A link id is at most one placement per lane -- a clip or a
8299 /// caption, whichever carries it -- and no sequence of edits may produce
8300 /// otherwise, because what an edit produces is what a save writes and a load
8301 /// reads.
8302 ///
8303 /// Amended for the offset-preserving group: the members keep their own
8304 /// spans, so two placements of one id covering different frames is *legal*
8305 /// -- it is what a hand-built group is -- and the only refusal left is the
8306 /// doubled id inside one lane.
8307 #[test]
8308 fn a_link_id_is_never_two_clips_of_one_lane() {
8309 let sources = vec![Source::new(FILE, 0)];
8310 let linked = |start, in_frame, out_frame, link| Clip {
8311 fade_in: 0,
8312 fade_out: 0,
8313 transition_out: 0,
8314 start,
8315 in_frame,
8316 out_frame,
8317 source: 0,
8318 link: Some(link),
8319 eq: None,
8320 color: None,
8321 transform: None,
8322 fit: FitPolicy::default(),
8323 speed: Speed::NORMAL,
8324 };
8325
8326 // The door: a doubled id inside one lane, refused by name.
8327 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
8328 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
8329 .expect_err("refused")
8330 .to_string()
8331 };
8332 assert!(
8333 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
8334 .contains("link 7 names two clips in the V1 lane"),
8335 "a duplicate id inside one lane is refused by name"
8336 );
8337 // ...and the same doubling on a subtitle lane, in its own words: a
8338 // caption is the other placement an id may name.
8339 let caption = |start: u32, frames: u32, link| SubClip {
8340 start,
8341 frames,
8342 track: 0,
8343 in_us: 0,
8344 out_us: i64::from(frames) * 1_000_000,
8345 link: Some(link),
8346 };
8347 let subs = LaneData {
8348 clips: Vec::new(),
8349 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
8350 ..LaneData::new(LaneKind::Subtitle, Vec::new())
8351 };
8352 assert_eq!(
8353 links_are_consistent(&[subs]).unwrap_err().to_string(),
8354 "link 7 names two captions in the S1 lane"
8355 );
8356 // A pair covering *different* frames is legal now: the members of a
8357 // hand-built group keep their own spans, and what binds them is the id.
8358 let apart = Project::from_parts(
8359 sources.clone(),
8360 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
8361 Vec::new(),
8362 Vec::new(),
8363 Vec::new(),
8364 );
8365 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
8366 // A one-sided link is *not* an error: it is what a lift leaves behind.
8367 let mut p = Project::single(FILE, 9);
8368 assert!(p.lift(Lane::A1, 0));
8369 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
8370 assert!(
8371 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
8372 "a lifted lane's project has to load again"
8373 );
8374
8375 // The edits: nothing below may break either rule.
8376 let consistent = |p: &Project, what: &str| {
8377 assert!(
8378 links_are_consistent(&p.lanes).is_ok(),
8379 "{what}: {:?}",
8380 p.lanes
8381 );
8382 };
8383 let mut p = three();
8384 let copied = p.clips()[0];
8385 assert!(
8386 copied.link.is_some(),
8387 "the clipboard clip carries its group"
8388 );
8389 assert!(p.lift(Lane::V1, 0));
8390 assert!(p.place(Lane::V1, 0, copied));
8391 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
8392 assert_eq!(
8393 p.clips().iter().filter(|c| c.link == copied.link).count(),
8394 0,
8395 "a placement belongs to no group, so it cannot duplicate one"
8396 );
8397 consistent(&p, "lift + place twice");
8398 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
8399 consistent(&p, "place through a grouped clip");
8400 assert!(p.paste(6, copied), "a rippling paste through another");
8401 consistent(&p, "paste");
8402 assert!(p.split(2));
8403 consistent(&p, "split");
8404 assert!(p.ripple_delete(1, 3));
8405 consistent(&p, "ripple_delete");
8406 assert!(p.undo());
8407 consistent(&p, "undo");
8408 }
8409
8410 /// What an edit produces is what a save writes, so *every* state the public
8411 /// API can reach has to load again. The two the verifier panel found where
8412 /// it did not: a split and a regroup handed one group id to two clips that
8413 /// were not the same span, because the lanes had been edited apart.
8414 #[test]
8415 fn every_reachable_state_reloads() {
8416 let mut p = Project::single(FILE, 150);
8417 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
8418 assert!(p.split(10), "the lanes are cut apart at 10");
8419 reloads(&p, "place on one lane, then split");
8420
8421 let mut p = Project::single(FILE, 150);
8422 assert!(p.split(30));
8423 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
8424 assert!(p.regroup(30), "only the audio lane can rejoin");
8425 assert!(p.split(60));
8426 reloads(&p, "lift, regroup one lane, split");
8427
8428 // Two audio streams of one file, both placed: two source entries with
8429 // one path between them, which is the state a stream picked out of the
8430 // library reaches -- and the state a save has to write and read back.
8431 let mut p = Project::single(FILE, 150);
8432 let second = p.import(FILE, 1);
8433 assert_eq!(second, 1, "the same file on another stream is a new source");
8434 assert!(p.append_clip(second, 150));
8435 assert!(p.split(200));
8436 reloads(
8437 &p,
8438 "a second audio stream of the same file, placed and split",
8439 );
8440 let (sources, ..) = p.without_orphan_sources();
8441 assert_eq!(
8442 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
8443 [0, 1],
8444 "both entries survive the orphan prune: both are played"
8445 );
8446 }
8447
8448 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
8449 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
8450 /// is the stamp playback puts on a decoded source frame -- and the *last*
8451 /// source frame the pump is still holding at a timeline frame has to be
8452 /// exactly the one the export encoded there, at every rate. Anything else is
8453 /// A/V drift that grows with the clip, and no test of either side alone
8454 /// would see it.
8455 ///
8456 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
8457 /// is a better answer than the floor/floor this had: floor/floor put the
8458 /// preview a whole held frame off the export at slow rates.)
8459 #[test]
8460 fn speed_maps_both_ways() {
8461 for permille in (250..=4000).step_by(1) {
8462 let speed = Speed::from_permille(permille);
8463 assert_eq!(speed.permille(), permille, "no clamping in range");
8464 for d in 0..200u32 {
8465 let want = speed.source_at(d);
8466 // What the pump shows at `d` is the last frame whose stamp has
8467 // come due -- and it is `want`, the frame the export encodes
8468 // there. Slowed, that is the frame it is still holding; sped up,
8469 // it is the newest of the several that arrived.
8470 let held = (0..=want + 8)
8471 .filter(|&s| speed.timeline_at(s) <= d)
8472 .next_back();
8473 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
8474 }
8475 for n in 1..300u32 {
8476 // A footprint is never zero: a clip occupying no timeline frame
8477 // is a placement the lane invariants cannot hold.
8478 let frames = speed.frames(n);
8479 assert!(frames >= 1, "{speed} of {n} frames");
8480 // ...and its last timeline frame never reads past the clip.
8481 assert!(
8482 speed.source_at(frames - 1) < n,
8483 "{speed}: the last timeline frame of {n} reads past the clip"
8484 );
8485 // The trim inverse never overshoots the room it was given, and
8486 // answers for every room a footprint can be.
8487 let fit = speed.fit(frames).expect("a clip fits its own footprint");
8488 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
8489 // A room narrower than one source frame's own footprint holds
8490 // nothing, and says so rather than rounding something into it.
8491 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
8492 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
8493 }
8494 }
8495 // Real time is the identity map, byte for byte.
8496 for d in 0..1000 {
8497 assert_eq!(Speed::NORMAL.source_at(d), d);
8498 assert_eq!(Speed::NORMAL.timeline_at(d), d);
8499 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
8500 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
8501 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
8502 }
8503 // The one door: no zero, no reverse, nothing past the ends.
8504 assert_eq!(Speed::from_permille(0), Speed::MIN);
8505 assert_eq!(Speed::from_permille(249), Speed::MIN);
8506 assert_eq!(Speed::from_permille(4001), Speed::MAX);
8507 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
8508 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
8509 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
8510 }
8511
8512 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
8513 /// export encodes at a timeline frame is the one playback is holding there,
8514 /// a file is as long in timeline frames as the seconds it lasts, and the two
8515 /// compose so a speeded clip at another rate is exactly both.
8516 #[test]
8517 fn rate_composes_with_speed() {
8518 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
8519 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
8520 // the identity map or a single-rate project would move.
8521 for (source_fps, timeline_fps) in [
8522 (24000. / 1001., 30.),
8523 (30., 24000. / 1001.),
8524 (60., 30.),
8525 (25., 30.),
8526 (30., 30.),
8527 ] {
8528 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
8529 for n in 0..2000u32 {
8530 let source = rate.source_at(n);
8531 // The stamp is the *first* timeline-rate frame that shows it, so
8532 // the picture on screen at `n` is the picture encoded at `n`.
8533 let held = (0..=source + 4)
8534 .filter(|&s| rate.timeline_at(s) <= n)
8535 .next_back();
8536 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
8537 }
8538 // A file of `count` frames is `timeline_at(count)` frames long here,
8539 // and its last one still reads a frame the file has.
8540 for count in 1..500u32 {
8541 let frames = rate.timeline_at(count);
8542 assert!(frames >= 1, "a file is never zero frames long");
8543 assert!(
8544 rate.source_at(frames - 1) < count,
8545 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
8546 );
8547 }
8548 // No drift: the mapping is one exact division of the *rate itself*,
8549 // not an accumulation and not a rounded rate, so an hour in is as
8550 // true as the first second. (Held to the real ratio of the two rates
8551 // the caller asked for -- `as_f64` would be true of a wrong rate.)
8552 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
8553 let want = f64::from(n) * source_fps / timeline_fps;
8554 assert!(
8555 (f64::from(rate.source_at(n)) - want).abs() < 1.,
8556 "{source_fps} on {timeline_fps}: frame {n} drifted"
8557 );
8558 }
8559 }
8560 // The timeline's own rate is the identity, whichever way it is written.
8561 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
8562 assert!(
8563 Rate::from_fps(30.0004, 30.)
8564 .expect("30.0004 over 30")
8565 .is_real_time(),
8566 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
8567 );
8568 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
8569 // one thing `matches_timeline` refuses a file for now that the rate gate
8570 // is gone.
8571 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
8572 assert!(Rate::from_fps(30., f64::NAN).is_err());
8573 for n in 0..1000 {
8574 assert_eq!(Rate::REAL_TIME.source_at(n), n);
8575 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
8576 }
8577 // ...and the composition, in the order the decoder's door applies it:
8578 // the speed picks the clip's (timeline-rate) frame, the rate picks the
8579 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
8580 // timeline frames per frame shown, each of them exactly 800/1001 of a
8581 // file frame.
8582 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
8583 let speed = Speed::from_permille(2000);
8584 for d in 0..100u32 {
8585 assert_eq!(
8586 rate.source_at(speed.source_at(d)),
8587 (u64::from(d) * 2 * 800 / 1001) as u32,
8588 "2x of a 23.976 fps file at timeline frame {d}"
8589 );
8590 }
8591 }
8592
8593 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
8594 /// source frames per timeline frame and still starts at its own in-point,
8595 /// and a half-speed one shows every source frame twice.
8596 #[test]
8597 fn a_rate_maps_timeline_frames_onto_source_frames() {
8598 let mut p = Project::single(FILE, 40);
8599 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8600 .expect("room enough");
8601 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
8602 assert_eq!(
8603 p.map(Lane::V1, 0),
8604 Some((0, 0)),
8605 "and it starts where it did"
8606 );
8607 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
8608 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
8609 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
8610 // The span a decoder is handed: as many source frames as it will read,
8611 // which is the last shown frame's own and not one more -- timeline frame
8612 // 19 shows source frame 38, so 39 frames are read and the 40th is a
8613 // picture nothing would display.
8614 let span = p.span_at(Lane::V1, 0).expect("a span");
8615 assert_eq!((span.len, span.source_len()), (20, 39));
8616 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
8617 // ...and the same clip the other way round.
8618 let mut p = Project::single(FILE, 40);
8619 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8620 .expect("room enough");
8621 assert_eq!(p.timeline_frames(), 80);
8622 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
8623 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
8624 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
8625 assert_eq!(
8626 p.map(Lane::V1, 79),
8627 Some((0, 39)),
8628 "and the last timeline frame is still inside the source range"
8629 );
8630 }
8631
8632 /// A trim of a speeded clip is still a trim of its *source*, and the edge
8633 /// still stops at the wall: the room a rate leaves is measured in timeline
8634 /// frames and the range it commits in source ones.
8635 #[test]
8636 fn trimming_a_speeded_clip_stays_inside_its_room() {
8637 let mut p = Project::single(FILE, 40);
8638 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8639 .expect("room enough");
8640 // A second clip butted against the first, so the wall is a real one.
8641 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
8642 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
8643 assert_eq!(room, (1, 20), "out to the neighbour and no further");
8644 assert!(
8645 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
8646 "clamped to the wall, which is where the edge already is"
8647 );
8648 let c = p.clips()[0];
8649 assert_eq!(c.end(), 20, "so nothing moved");
8650 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
8651 // ...and in: half the timeline frames is half the source range.
8652 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
8653 let c = p.clips()[0];
8654 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
8655 assert_eq!(c.end(), 10, "and ten timeline frames of them");
8656 assert!(sorted_disjoint(p.clips()));
8657 }
8658
8659 /// The frames a rate cannot address: at half speed each source frame is on
8660 /// screen twice, and the cut between the two showings is not a cut in the
8661 /// file. Refused, so the two halves always add up to the clip that was cut.
8662 #[test]
8663 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
8664 let mut p = Project::single(FILE, 10);
8665 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8666 .expect("room enough");
8667 assert_eq!(p.timeline_frames(), 20);
8668 assert!(
8669 !p.split(3),
8670 "an odd frame is between two showings of one frame"
8671 );
8672 assert_eq!(p.clips().len(), 1, "and nothing was cut");
8673 assert!(p.split(4), "an even one is a frame boundary");
8674 let halves = p.clips().to_vec();
8675 assert_eq!(
8676 (halves[0].end(), halves[1].start, halves[1].end()),
8677 (4, 4, 20),
8678 "the halves meet, and still end where the clip did"
8679 );
8680 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
8681 assert!(p.regroup(4), "and the inverse puts it back");
8682 assert_eq!(p.clips().len(), 1);
8683 }
8684
8685 /// The same claim, swept: random op sequences off the public surface, the
8686 /// project reloaded after every one of them. A failure prints its seed, and
8687 /// the seed replays the whole sequence.
8688 #[test]
8689 fn random_edit_sequences_reload() {
8690 // Two thousand, not two hundred: the overlap a hole punched into a slow
8691 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
8692 // sequences, and a 200-seed sweep walked straight past it (it took a
8693 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
8694 // has no business being the narrow one.
8695 for seed in 0..2000u64 {
8696 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8697 let mut next = move |n: u32| {
8698 // xorshift64*: no dependency, and the seed replays it exactly.
8699 rng ^= rng << 13;
8700 rng ^= rng >> 7;
8701 rng ^= rng << 17;
8702 (rng >> 33) as u32 % n
8703 };
8704 let mut p = Project::single(FILE, 40);
8705 for step in 0..24 {
8706 let frame = next(44);
8707 // A clipboard copy carries the group id of the take it came from
8708 // -- the input that made a placement duplicate an id -- and, one
8709 // time in three, a rate of its own: a *speeded clip placed over
8710 // a speeded clip* is the shape whose remainders have to be run
8711 // through `Speed::fit`, and it is not a shape the lanes hand out
8712 // on their own often enough to be sure of.
8713 let mut copied = *p
8714 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
8715 .get(next(4) as usize)
8716 .unwrap_or(&clip(0, 0, 5, 0));
8717 if next(3) == 0 {
8718 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
8719 }
8720 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
8721 let idx = next(4) as usize;
8722 let _ = match next(16) {
8723 // A clip dragged along its own lane to wherever the pointer
8724 // let it go: the op that moves a placement without changing
8725 // what it plays, so what it may not do is land on top of the
8726 // neighbour it was dragged at.
8727 15 => p.move_clip(lane, idx, lane, frame),
8728 // ...and a second `place`, so a punch lands inside a clip
8729 // far more often than one op in fourteen would put it there.
8730 14 => p.place(lane, frame, copied),
8731 0 => p.split(frame),
8732 1 => p.regroup(frame),
8733 2 => p.lift(lane, idx),
8734 3 => p.place(lane, frame, copied),
8735 4 => p.paste(frame, copied),
8736 5 => p.ripple_delete(frame, next(9)),
8737 6 => p.delete(idx),
8738 7 => p.undo(),
8739 // An equalizer put on and taken off in the mix: what a clip
8740 // carries has to reload with it, and the entries an undo
8741 // orphans must not come back out of the prune.
8742 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8743 9 => p.set_eq(lane, idx, None),
8744 // ...and a colour grade in the same mix, for the same
8745 // reason: it rides on the clip and its orphans must go.
8746 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
8747 11 => p.set_color(lane, idx, None),
8748 // ...and a rate in with them, which is the one of the three
8749 // that moves *placements*: a clip that grew has to be
8750 // refused rather than overlap, and one that shrank leaves a
8751 // lane that still loads. Both are what `reloads` asks.
8752 12 => p
8753 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8754 .is_ok(),
8755 _ => p.append_clip(0, 1 + next(9)),
8756 };
8757 reloads(&p, &format!("seed {seed}, step {step}"));
8758 }
8759 }
8760 }
8761
8762 /// The save/load round trip a project must survive: the parts a save writes,
8763 /// handed back to the constructor a load goes through -- every lane of them,
8764 /// and the reloaded timeline has to be the same lanes in the same order.
8765 fn reloads(p: &Project, what: &str) {
8766 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
8767 match Project::from_parts(sources, lanes, eq, color, Vec::new()) {
8768 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
8769 Ok(back) => {
8770 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
8771 // Placements, not whole clips: an orphan prune renumbers the
8772 // sources a clip names, which is the point of it.
8773 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
8774 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
8775 };
8776 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
8777 // The prune renumbers the eq table too, so what has to survive
8778 // is the settings themselves, clip by clip.
8779 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
8780 p.lanes()
8781 .into_iter()
8782 .map(|l| {
8783 (0..p.lane(l).len())
8784 .map(|i| p.eq_of(l, i).cloned())
8785 .collect()
8786 })
8787 .collect()
8788 };
8789 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
8790 // The colour table renumbers in the same prune, so the same
8791 // claim: the params a clip names, not the index it names them by.
8792 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
8793 p.lanes()
8794 .into_iter()
8795 .map(|l| {
8796 (0..p.lane(l).len())
8797 .map(|i| p.color_of(l, i).copied())
8798 .collect()
8799 })
8800 .collect()
8801 };
8802 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
8803 }
8804 }
8805 }
8806
8807 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
8808 /// -- each one sorted and disjoint, and one span per group id -- asserted
8809 /// directly, where the point is the invariant rather than the round trip.
8810 fn invariants_hold(p: &Project, what: &str) {
8811 for lane in p.lanes() {
8812 assert!(
8813 sorted_disjoint(p.lane(lane)),
8814 "{what}: {} is out of order or overlaps itself: {:?}",
8815 lane.label(),
8816 p.lane(lane)
8817 );
8818 }
8819 if let Err(e) = links_are_consistent(&p.lanes) {
8820 panic!("{what}: {e}\n{:?}", p.lanes);
8821 }
8822 }
8823
8824 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
8825 /// edited without any other lane hearing about it. A handle naming a lane
8826 /// that is not there reads as empty and refuses to mutate.
8827 #[test]
8828 fn a_third_lane_is_a_peer() {
8829 let mut p = three();
8830 assert_eq!(p.lane_count(LaneKind::Video), 1);
8831 assert_eq!(p.lane_count(LaneKind::Audio), 1);
8832 let v2 = p.add_lane(LaneKind::Video);
8833 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
8834 assert_eq!(v2.label(), "V2");
8835 assert_eq!(p.lane_count(LaneKind::Video), 2);
8836 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8837 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
8838
8839 // A handle for a lane that is not there: empty, and no mutation takes.
8840 let v3 = Lane::new(LaneKind::Video, 2);
8841 assert!(p.lane(v3).is_empty());
8842 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
8843 assert!(!p.lift(v3, 0));
8844 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
8845
8846 // Placing on V2 moves nothing else, and the lane can outrun the rest.
8847 let before = shape(&p);
8848 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
8849 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
8850 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
8851 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8852 assert_eq!(
8853 p.timeline_frames(),
8854 16,
8855 "the last lane to end sets the length"
8856 );
8857 assert_eq!(p.map(v2, 5), Some((0, 21)));
8858 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
8859 assert_eq!(
8860 p.span_at(v2, 0),
8861 Some(Span {
8862 start: 0,
8863 len: 4,
8864 from: None,
8865 speed: Speed::NORMAL
8866 })
8867 );
8868 // Every lane still covers the whole timeline, gaps included.
8869 for l in p.lanes() {
8870 let spans = p.spans_from(l, 0);
8871 assert_eq!(
8872 spans.iter().map(|s| s.len).sum::<u32>(),
8873 16,
8874 "{}",
8875 l.label()
8876 );
8877 }
8878 // ...and playback still reads V1 and A1, whatever else is there.
8879 assert_eq!(p.clips(), p.lane(Lane::V1));
8880 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
8881 let segments = p.segments_from(0, FPS);
8882 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
8883 assert_eq!(
8884 segments[3],
8885 (None, 0.0, 7.0 / FPS),
8886 "A1 keeps the clock counting over the picture V2 added"
8887 );
8888 invariants_hold(&p, "place on V2");
8889
8890 // A lift is that lane's business too, and the lane list undoes.
8891 assert!(p.lift(v2, 0));
8892 assert!(p.lane(v2).is_empty());
8893 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
8894 assert!(p.undo());
8895 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
8896 assert!(p.undo());
8897 assert!(p.lane(v2).is_empty(), "the placement came off V2");
8898 assert!(p.undo(), "and one more step takes the lane itself back");
8899 assert_eq!(p.lane_count(LaneKind::Video), 1);
8900 assert_eq!(shape(&p), shape(&three()));
8901 }
8902
8903 /// The add taken back: an empty lane comes off, a lane holding clips never
8904 /// does (and says which clips), the last lane of a kind never does, the
8905 /// lanes below the one that went move up an `ord`, and one undo puts it
8906 /// back where it stood.
8907 #[test]
8908 fn an_empty_lane_comes_off_again() {
8909 let mut p = three();
8910 let v2 = p.add_lane(LaneKind::Video);
8911 let v3 = p.add_lane(LaneKind::Video);
8912 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
8913 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
8914 let history = p.history.len();
8915
8916 // The last lane of its kind stays: `V1`/`A1` are where an import and a
8917 // paste land, and a project missing one would swallow half of a file
8918 // dropped on it.
8919 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
8920 assert_eq!(
8921 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
8922 "there is no V10 to remove"
8923 );
8924
8925 // A lane with clips on it refuses and names them: a track removal never
8926 // deletes a take.
8927 let refusal = why(p.remove_lane(v3));
8928 assert!(refusal.contains("V3 still holds"), "{refusal}");
8929 assert!(refusal.contains(FILE), "{refusal}");
8930 assert!(refusal.contains("at frame 0"), "{refusal}");
8931 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
8932 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
8933
8934 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
8935 // all.
8936 p.remove_lane(v2).expect("V2 is empty");
8937 assert_eq!(p.lane_count(LaneKind::Video), 2);
8938 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
8939 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
8940 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
8941 invariants_hold(&p, "remove V2");
8942
8943 // ...and one stroke puts the empty lane back above it.
8944 assert!(p.undo());
8945 assert_eq!(p.lane_count(LaneKind::Video), 3);
8946 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
8947 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
8948 }
8949
8950 /// A track dragged to another place in the stack: the whole lane travels --
8951 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
8952 /// a video one, a lane that crosses one of its own kind swaps names with it
8953 /// (and swaps the composite with it), one undo puts the order back, and a
8954 /// save carries it.
8955 #[test]
8956 fn a_track_is_dragged_to_another_place_in_the_stack() {
8957 let mut p = three();
8958 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
8959 let before = shape(&p);
8960 let history = p.history.len();
8961
8962 // A1 over V1: the screen is rearranged and nothing else is. Both keep
8963 // their names -- neither crossed a lane of its own kind -- so every
8964 // handle a front-end holds still names the track it named before.
8965 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
8966 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
8967 assert_eq!(
8968 shape(&p),
8969 vec![before[1].clone(), before[0].clone()],
8970 "each lane's clips travelled with it, and none was remapped"
8971 );
8972 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
8973 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
8974 invariants_hold(&p, "A1 over V1");
8975
8976 // Nothing moves for a lane that is not there, a slot that is not, or a
8977 // lane already standing in the one it was pointed at.
8978 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
8979 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
8980 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
8981 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
8982
8983 // ...and one stroke puts the order back.
8984 assert!(p.undo());
8985 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
8986 assert_eq!(shape(&p), before);
8987
8988 // A second video lane over the first: display order *is* the stack, so
8989 // the last video lane covering a frame is the picture that shows.
8990 let v2 = p.add_lane(LaneKind::Video);
8991 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
8992 let over = shape(&p)[2].clone();
8993 assert_eq!(
8994 p.composite_span_at(0).map(|s| s.len),
8995 Some(5),
8996 "V2's five frames are what frame 0 shows"
8997 );
8998
8999 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
9000 // a position among the lanes of its kind. The picture that wins changes
9001 // with it: the take that was covering is the covered one now.
9002 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
9003 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
9004 assert_eq!(
9005 shape(&p),
9006 vec![over.clone(), before[0].clone(), before[1].clone()],
9007 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
9008 );
9009 assert_eq!(
9010 p.composite_span_at(0).map(|s| s.len),
9011 Some(3),
9012 "the lower video lane wins, and it is the old V1 now"
9013 );
9014 invariants_hold(&p, "V2 over V1");
9015
9016 // A save writes that order and a load takes it back.
9017 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9018 assert_eq!(
9019 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9020 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
9021 );
9022 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
9023 assert_eq!(back.lanes(), p.lanes());
9024 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
9025
9026 assert!(p.undo(), "and the stack goes back to how it stood");
9027 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
9028 }
9029
9030 /// The grouping rule across more than two lanes, under the offset model: a
9031 /// split *keeps* the group on the left halves and hands the right halves of
9032 /// that group one fresh id of their own -- a clip in no group comes out of
9033 /// the cut in none. So a take cut apart is two takes, one per side, and a
9034 /// lane that was never part of it stays out of both.
9035 #[test]
9036 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
9037 let mut p = Project::single(FILE, 9);
9038 let take = p.clips()[0].link.expect("a fresh project is one take");
9039 let v2 = p.add_lane(LaneKind::Video);
9040 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
9041 assert!(p.split(4));
9042 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
9043 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
9044 };
9045 let (left, right) = (side(&p, 0), side(&p, 1));
9046 // The lanes in order are V1, A1, V2: the take's two keep its id on the
9047 // left, and the placed clip never had one for the cut to keep.
9048 assert_eq!(
9049 left,
9050 vec![Some(take), Some(take), None],
9051 "the left halves keep the take"
9052 );
9053 // ...and the right halves of that take are one fresh group.
9054 assert_eq!(right[0], right[1]);
9055 assert_ne!(right[0], Some(take));
9056 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
9057 invariants_hold(&p, "split across three lanes");
9058
9059 // V2 ends early: the left halves still keep what each clip carried --
9060 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
9061 // shared by exactly the take's lanes.
9062 let mut p = Project::single(FILE, 9);
9063 let v2 = p.add_lane(LaneKind::Video);
9064 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
9065 assert!(p.split(3));
9066 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
9067 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
9068 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
9069 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
9070 invariants_hold(&p, "split where one lane ends early");
9071
9072 // The inverse rejoins each lane into the group its left half kept.
9073 assert!(p.regroup(3));
9074 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
9075 assert_eq!(
9076 p.lane(Lane::V1)[0].link,
9077 Some(take),
9078 "the take's id is back, not a fresh one"
9079 );
9080 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
9081 invariants_hold(&p, "regroup across three lanes");
9082 }
9083
9084 /// A group is one placement per lane, on however many lanes carry the id --
9085 /// not a video/audio pair and not a pairing by `ord` -- and the members may
9086 /// cover whatever frames they cover: the offset between them is what a
9087 /// hand-built group keeps. Lanes built by hand, because the rule is checked
9088 /// at the untrusted door and no edit can produce the one thing it refuses.
9089 #[test]
9090 fn a_group_may_span_any_lane() {
9091 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
9092 let one = |start: u32, end: u32, link| Clip {
9093 fade_in: 0,
9094 fade_out: 0,
9095 transition_out: 0,
9096 start,
9097 in_frame: start,
9098 out_frame: end,
9099 source: 0,
9100 link: Some(link),
9101 eq: None,
9102 color: None,
9103 transform: None,
9104 fit: FitPolicy::default(),
9105 speed: Speed::NORMAL,
9106 };
9107 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
9108 let kinds = [
9109 LaneKind::Video,
9110 LaneKind::Audio,
9111 LaneKind::Video,
9112 LaneKind::Audio,
9113 ];
9114 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
9115 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
9116 };
9117 let take = || vec![one(0, 4, 7)];
9118 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
9119 // The same take on V1 + A2 only, the lanes between it empty: legal, the
9120 // way a lifted half is legal.
9121 let across = build([take(), Vec::new(), Vec::new(), take()]);
9122 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
9123 // ...and so is a group whose members disagree about their spans: the
9124 // offset between them is the hand's business, not the loader's.
9125 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
9126 assert!(
9127 links_are_consistent(&apart).is_ok(),
9128 "[0, 4) on V1 and [2, 6) on A2 are one group"
9129 );
9130 // One id twice in one lane is still that lane's error, by name.
9131 let twice = build([
9132 Vec::new(),
9133 Vec::new(),
9134 vec![one(0, 4, 7), one(4, 8, 7)],
9135 Vec::new(),
9136 ]);
9137 assert_eq!(
9138 links_are_consistent(&twice).unwrap_err().to_string(),
9139 "link 7 names two clips in the V2 lane"
9140 );
9141 }
9142
9143 /// Every lane a save writes comes out, in display order and with its kind --
9144 /// an empty one included, since it is state a front-end shows -- and a
9145 /// two-lane project still writes exactly the parts it always did.
9146 #[test]
9147 fn a_save_writes_every_lane_it_has() {
9148 let mut p = three();
9149 let before = p.without_orphan_sources();
9150 assert_eq!(before.1.len(), 2, "V1 and A1");
9151 let v2 = p.add_lane(LaneKind::Video);
9152 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9153 let a2 = p.add_lane(LaneKind::Audio);
9154 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9155 assert_eq!(
9156 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9157 [
9158 LaneKind::Video,
9159 LaneKind::Audio,
9160 LaneKind::Video,
9161 LaneKind::Audio
9162 ],
9163 "display order, not video-then-audio"
9164 );
9165 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
9166 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
9167 // ...and all four load again as the same four.
9168 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
9169 assert_eq!(back.lanes(), p.lanes());
9170 assert_eq!(back.lane(a2), p.lane(a2));
9171
9172 // Taking the lanes back leaves exactly what a two-lane save wrote.
9173 for _ in 0..3 {
9174 assert!(p.undo());
9175 }
9176 assert_eq!(
9177 p.without_orphan_sources(),
9178 before,
9179 "byte for byte the same parts a two-lane save always wrote"
9180 );
9181 }
9182
9183 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
9184 /// three lanes and grows more: every lane's own order and the one
9185 /// span-per-id rule after every op, *and* the reload the v4 format restored
9186 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
9187 /// project of any number of lanes.
9188 #[test]
9189 fn random_edit_sequences_keep_many_lanes_consistent() {
9190 for seed in 0..2000u64 {
9191 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9192 let mut next = move |n: u32| {
9193 rng ^= rng << 13;
9194 rng ^= rng >> 7;
9195 rng ^= rng << 17;
9196 (rng >> 33) as u32 % n
9197 };
9198 let mut p = Project::single(FILE, 40);
9199 let v2 = p.add_lane(LaneKind::Video);
9200 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
9201 let lanes = [Lane::V1, Lane::A1, v2];
9202 for step in 0..24 {
9203 let frame = next(44);
9204 let copied = *p
9205 .lane(lanes[next(3) as usize])
9206 .get(next(4) as usize)
9207 .unwrap_or(&clip(0, 0, 5, 0));
9208 let lane = lanes[next(3) as usize];
9209 let idx = next(4) as usize;
9210 let _ = match next(14) {
9211 // The drag, in the mix: a clip dragged along its own lane
9212 // and onto another one, at a frame the pointer picked --
9213 // which is where the group rule and the sorted+disjoint one
9214 // meet, since every half travels the same distance.
9215 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
9216 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9217 11 => p.set_eq(lane, idx, None),
9218 // A rate, which on many lanes is the group rule as well:
9219 // every clip carrying the link moves together or none of
9220 // them does, and `invariants_hold` is what says so.
9221 12 => p
9222 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9223 .is_ok(),
9224 0 => p.split(frame),
9225 1 => p.regroup(frame),
9226 2 => p.lift(lane, idx),
9227 3 => p.place(lane, frame, copied),
9228 4 => p.paste(frame, copied),
9229 5 => p.ripple_delete(frame, next(9)),
9230 6 => p.delete(idx),
9231 7 => p.undo(),
9232 8 => {
9233 p.add_lane(if next(2) == 0 {
9234 LaneKind::Video
9235 } else {
9236 LaneKind::Audio
9237 });
9238 true
9239 }
9240 _ => p.append_clip(0, 1 + next(9)),
9241 };
9242 invariants_hold(&p, &format!("seed {seed}, step {step}"));
9243 reloads(&p, &format!("seed {seed}, step {step}"));
9244 }
9245 }
9246 }
9247
9248 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
9249 /// there, `V1` shows again on either side of it, and a frame no video lane
9250 /// covers is a gap however many lanes there are.
9251 #[test]
9252 fn the_composite_is_the_topmost_lane_with_a_clip() {
9253 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9254 let lanes = vec![
9255 // V1: the whole 30 frames of source 0.
9256 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9257 // V2: source 1 over the middle third.
9258 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
9259 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9260 ];
9261 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9262 assert_eq!(
9263 p.composite_spans_from(0),
9264 vec![
9265 Span {
9266 start: 0,
9267 len: 10,
9268 from: Some((0, 0)),
9269 speed: Speed::NORMAL
9270 },
9271 Span {
9272 start: 10,
9273 len: 10,
9274 from: Some((1, 5)),
9275 speed: Speed::NORMAL
9276 },
9277 Span {
9278 start: 20,
9279 len: 10,
9280 from: Some((0, 20)),
9281 speed: Speed::NORMAL
9282 },
9283 ],
9284 "V2 takes over for its own span and hands V1 back"
9285 );
9286 // A mid-span ask resolves the same way, which is what a seek does.
9287 assert_eq!(
9288 p.composite_span_at(15),
9289 Some(Span {
9290 start: 15,
9291 len: 5,
9292 from: Some((1, 10)),
9293 speed: Speed::NORMAL
9294 })
9295 );
9296 assert_eq!(p.composite_span_at(30), None, "past the end");
9297
9298 // A hole in V1 under V2's clip: black between the two, and black after
9299 // both run out (the audio lane is still holding the timeline open).
9300 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9301 let holed = vec![
9302 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
9303 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
9304 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9305 ];
9306 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
9307 assert_eq!(
9308 p.composite_spans_from(0),
9309 vec![
9310 Span {
9311 start: 0,
9312 len: 5,
9313 from: Some((0, 0)),
9314 speed: Speed::NORMAL
9315 },
9316 Span {
9317 start: 5,
9318 len: 5,
9319 from: None,
9320 speed: Speed::NORMAL
9321 },
9322 Span {
9323 start: 10,
9324 len: 10,
9325 from: Some((1, 0)),
9326 speed: Speed::NORMAL
9327 },
9328 Span {
9329 start: 20,
9330 len: 10,
9331 from: None,
9332 speed: Speed::NORMAL
9333 },
9334 ]
9335 );
9336
9337 // One video lane: the composite *is* that lane, span for span -- the
9338 // promise every existing two-lane project rests on.
9339 let p = Project::single(FILE, 30);
9340 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
9341 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
9342 }
9343
9344 /// Every audio lane holding something gets a play list, and only those.
9345 #[test]
9346 fn audio_segments_cover_every_lane_that_holds_something() {
9347 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9348 let lanes = vec![
9349 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9350 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9351 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
9352 (LaneKind::Audio, Vec::new()),
9353 ];
9354 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9355 let lists = p.audio_segments_from(0, FPS);
9356 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
9357 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
9358 // A2 is a gap up to frame 15, then the whole of source 1.
9359 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
9360
9361 // No audio lane holds anything: one all-gap list, so such a timeline
9362 // still plays silence against a master clock.
9363 let p = Project::from_parts(
9364 vec![Source::new(FILE, 0)],
9365 vec![
9366 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9367 (LaneKind::Audio, Vec::new()),
9368 ],
9369 vec![],
9370 vec![],
9371 Vec::new(),
9372 )
9373 .expect("valid parts");
9374 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
9375 }
9376}