forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

project.rs9795 lines, 428.0 KiBHistoryRawDownload
1//! Edit list: N ordered lanes of *placed* source ranges. Pure data, no I/O.
2//!
3//! A [`Project`] holds video lanes and audio lanes -- `V1..Vn`, `A1..An`, named
4//! by a [`Lane`] handle of a [`LaneKind`] and a 0-based `ord`. Each lane is a
5//! list of
6//! [`Clip`]s, and a clip says three things: which half-open `[in, out)` range of
7//! *source* frames it plays, which file it plays it from, and -- the whole model
8//! -- where on the timeline it sits ([`Clip::start`]). Clips are placed at an
9//! offset rather than queued end to end, so:
10//!
11//! * a **gap** is not an object, it is the absence of a placement. Nothing has
12//! to be inserted, kept in sync or garbage-collected for a hole to exist, and
13//! a hole cannot disagree with its neighbours about how long it is;
14//! * **moving and trimming are arithmetic** on `start`/`in_frame`, never a
15//! splice of the list;
16//! * the lanes are independent and are peers: deleting audio under a picture is
17//! one lane's business, and the picture does not shift. No lane is special
18//! except by what a *caller* reads -- and what playback and export read is the
19//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21//! lane over to be summed.
22//!
23//! The price is one invariant this module enforces at every mutation and every
24//! constructor: within a lane, clips are **sorted by `start` and never overlap**
25//! ([`sorted_disjoint`]). Everything else -- mapping, spans, segments -- is a
26//! walk over that order.
27//!
28//! Two frame spaces meet here and are never mixed: *source* frames index the
29//! decoded file, *timeline* frames index what the viewer sees. Both are 0-based
30//! (sample ids in the demuxer are 1-based; that conversion stays in `decode`).
31//!
32//! Grouping is [`Clip::link`]: clips carrying the same id were split from the
33//! same take and move together. An id is *not* a pairing of two lanes -- it
34//! names at most one clip per lane and every clip carrying it covers the same
35//! timeline span, on however many lanes ([`links_are_consistent`]).
36//! [`Project::split`] cuts every lane at a timeline frame and hands each side
37//! fresh ids, one per group of lanes whose halves line up; [`Project::regroup`]
38//! is its inverse and rejoins them.
39//!
40//! Editing is metadata only. [`Project::split`] changes no timeline->source
41//! mapping, so a running decoder stays correct across it; everything else does
42//! and the caller must reseek. Every successful edit snapshots every lane, so
43//! [`Project::undo`] is an exact restore -- of the clips *and* of the lane list.
44//!
45//! Words are a third kind of lane ([`LaneKind::Subtitle`]) and not a setting on
46//! the project: a caption is placed, moved, trimmed, cut and rippled by the
47//! very machinery above, and it joins the undo history for free because a
48//! snapshot is the whole lane list. What such a lane holds is a [`SubClip`] --
49//! a `[in_us, out_us)` window of one of the project's subtitle tracks
50//! ([`Project::subtitles`], which stays the *palette* the cues are read into),
51//! placed at a timeline frame like everything else. It holds no [`Clip`] at
52//! all, which is what keeps every media path (the composite, the mix, an
53//! equalizer, a speed) from ever meeting one: they read a lane's clips, and
54//! there are none.
55//!
56//! A clip names its file by *index* into [`Project::sources`], which is
57//! append-only: an index handed out once stays valid forever, so a clip on the
58//! clipboard or inside an undo snapshot can never dangle. An index -- not an
59//! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
60//! plain assignment.
61//!
62//! A clip names its equalizer the same way, by index into a second append-only
63//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
64//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
65//! halves the same settings, a copy carries them, and an undo restores whatever
66//! index the clip had. Only a *save* prunes the table
67//! ([`Project::without_orphan_sources`]), for the reason an undone import
68//! leaves its source entry behind: an index handed out is an index forever.
69//!
70//! Its colour grade is a third such table ([`Clip::color`],
71//! [`Project::set_color`]) and behaves in every way like the equalizer one --
72//! shared by equal settings, inherited by both halves of a split, pruned only at
73//! a save. An index rather than the four floats themselves for the same reason:
74//! twenty clips graded alike name one entry, and the file writes it once.
75
76use crate::map::TimelineMap;
77use std::path::{Path, PathBuf};
78
79use crate::color::ColorParams;
80use crate::transform::TransformParams;
81use crate::eq::EqParams;
82use crate::limiter::{Limiter, db_to_linear};
83use crate::scale::FitPolicy;
84use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
85
86/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
87/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
88/// for every purpose but the honest one, which is that it is still a level and
89/// not a mute.
90pub const MIN_GAIN_DB: f32 = -60.0;
91/// ...and how far up. +12 dB is four times the amplitude, which is as much as
92/// a mix bus can take before the limiter is doing all the work.
93pub const MAX_GAIN_DB: f32 = 12.0;
94
95/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
96/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
97/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
98/// comparable nor exactly writable, and `.edith` has to read back the very
99/// number that was set. A thousandth is finer than any card can drag and coarser
100/// than any rounding anyone can hear.
101///
102/// The rate alone: the audio path time-stretches a speeded clip
103/// (`crate::stretch`), so its pitch stays where it was recorded while its
104/// seconds compress or stretch -- the tape effect this used to be is gone.
105/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
106/// [`Speed::MAX`] four times.
107#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
108pub struct Speed(u16);
109
110/// What [`Project::parts`] hands back: the comparable shape of everything an
111/// edit can change, for the sweep's undo round-trip. Test-only, like every
112/// accessor it exists for: the sweep lives behind `cfg(test)`.
113#[cfg(test)]
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct SweepParts(
116 pub(crate) usize,
117 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
118 pub(crate) Vec<Vec<SubClip>>,
119);
120
121impl Speed {
122 /// Real time -- what every clip is until something says otherwise, and the
123 /// value every path in this engine short-circuits on.
124 pub const NORMAL: Speed = Speed(1000);
125 pub const MIN: Speed = Speed(250);
126 pub const MAX: Speed = Speed(4000);
127
128 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
129 /// unrepresentable rather than merely refused: nothing downstream divides
130 /// by a speed that could be nothing.
131 pub fn from_permille(permille: u16) -> Self {
132 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
133 }
134
135 pub fn permille(self) -> u16 {
136 self.0
137 }
138
139 pub fn is_normal(self) -> bool {
140 self == Self::NORMAL
141 }
142
143 /// As a multiplier, for the sound worker and for a label.
144 pub fn as_f64(self) -> f64 {
145 f64::from(self.0) / 1000.
146 }
147
148 /// How many *timeline* frames `source` source frames occupy at this rate --
149 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
150 /// clip that occupied no frames would be an empty placement, which the lane
151 /// invariant forbids and which nothing could ever click on again.
152 pub fn frames(self, source: u32) -> u32 {
153 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
154 n.clamp(1, u64::from(u32::MAX)) as u32
155 }
156
157 /// The mapping itself: which source frame of a clip the `offset`th timeline
158 /// frame of it plays. Floored, so the first timeline frame is the clip's own
159 /// in-point at every rate.
160 pub fn source_at(self, offset: u32) -> u32 {
161 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
162 }
163
164 /// Its inverse, for a decoder's frames on their way back out: which timeline
165 /// frame of the clip the `offset`th *source* frame of it lands on.
166 ///
167 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
168 /// decoded frame with this and shows the newest whose stamp has come due, so
169 /// what is on screen at timeline offset `d` is the last source frame with
170 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
171 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
172 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
173 /// the two the same way would put the preview a frame off the export at some
174 /// speeds and a whole held frame off at slow ones -- drift that no test of
175 /// either side alone would catch.
176 pub fn timeline_at(self, offset: u32) -> u32 {
177 (u64::from(offset) * 1000)
178 .div_ceil(u64::from(self.0))
179 .min(u64::from(u32::MAX)) as u32
180 }
181
182 /// The longest source range that still *fits* in `frames` timeline frames at
183 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
184 /// any room narrower than the four timeline frames one source frame occupies.
185 ///
186 /// What a trim commits and what a hole-punch leaves behind: rounding could
187 /// otherwise hand back a range wider than the room, and a clip that outgrew
188 /// its room would overlap its neighbour -- the one thing a lane may never do.
189 /// `None` is not an error, it is "no remainder": the caller drops that piece
190 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
191 /// is `frames` itself, so nothing about an unspeeded edit changes.
192 pub fn fit(self, frames: u32) -> Option<u32> {
193 if frames == 0 || self.frames(1) > frames {
194 return None;
195 }
196 let mut src = self.source_at(frames).max(1);
197 // At most a step or two: `frames` is monotone in `src` and the rounding
198 // above can only overshoot by one source frame's worth.
199 while src > 1 && self.frames(src) > frames {
200 src -= 1;
201 }
202 Some(src)
203 }
204
205 /// How many timeline frames `source` source frames of head (or tail) are
206 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
207 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
208 /// empty, but the room in front of one may well be.
209 pub fn room(self, source: u32) -> u32 {
210 match source {
211 0 => 0,
212 n => self.frames(n),
213 }
214 }
215
216 /// How many timeline frames from `offset` on show the **same** source frame:
217 /// one at real time and faster, more when the clip is slowed. What an export
218 /// encodes without decoding the same picture twice, and the count that makes
219 /// its frame walk exactly as long as the span.
220 pub fn repeats(self, offset: u32, len: u32) -> u32 {
221 let want = self.source_at(offset);
222 (offset..len)
223 .take_while(|&t| self.source_at(t) == want)
224 .count() as u32
225 }
226
227 /// Where in the source a cut `offset` timeline frames into a clip of `len`
228 /// source frames falls -- and `None` when this rate cannot address that
229 /// frame at all.
230 ///
231 /// At half speed a clip of ten source frames is twenty timeline frames long
232 /// and every source frame is on screen twice, so a cut between the two
233 /// showings of one frame is not a cut in the *file*: taking it would leave
234 /// two halves whose lengths no longer add up to the clip that was cut --
235 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
236 /// the model stays exact and the front-end can say why. At real time every
237 /// interior frame answers, which is the path a project without speeds is on.
238 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
239 let src = self.source_at(offset);
240 (src > 0
241 && src < len
242 && self.frames(src) == offset
243 && self.frames(len - src) == self.frames(len) - offset)
244 .then_some(src)
245 }
246}
247
248impl Default for Speed {
249 fn default() -> Self {
250 Self::NORMAL
251 }
252}
253
254impl std::fmt::Display for Speed {
255 /// `2.00x` -- what a card prints and what a clip box is marked with.
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 write!(f, "{:.2}x", self.as_f64())
258 }
259}
260
261/// What a file's own frame rate is against the timeline's, as an exact
262/// rational: how many frames of the *file* one frame of the timeline is worth.
263///
264/// Every frame number in this module counts **timeline** frames -- a clip's
265/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
266/// timeline is as many frames long as the seconds it lasts, and every edit
267/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
268/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
269/// opens a worker with it and [`crate::export`] pulls pictures through it. The
270/// file's own numbering exists nowhere else.
271///
272/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
273/// export encodes at a timeline frame has to be the frame playback is holding
274/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
275/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
276///
277/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
278/// stays `800/1001` however far the timeline runs, where a rate rounded to
279/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
280/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
281///
282/// [`PlaybackSession`]: crate::PlaybackSession
283#[derive(Clone, Copy, PartialEq, Eq, Debug)]
284pub struct Rate {
285 /// Frames of the file...
286 source: u32,
287 /// ...per this many frames of the timeline it plays on. Never zero.
288 timeline: u32,
289}
290
291impl Rate {
292 /// A file shot at the timeline's own rate: every conversion below is the
293 /// identity, which is the path a single-rate project is on.
294 pub const REAL_TIME: Self = Self {
295 source: 1,
296 timeline: 1,
297 };
298
299 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
300 /// exactly.
301 ///
302 /// Both rates come out of a container as a division, so neither is ever the
303 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
304 /// already knows how to name one exactly -- it is the same pair the muxer
305 /// counts an export's frames in -- and this is that pair divided by that
306 /// pair, reduced. A rate no timescale can name is an `Err` in that
307 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
308 /// where a file carrying one is refused by name, beside the codec.
309 ///
310 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
311 /// timeline that had ever opened in this editor before mixed rates.
312 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
313 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
314 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
315 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
316 let num = u64::from(src_scale) * u64::from(tl_ticks);
317 let den = u64::from(src_ticks) * u64::from(tl_scale);
318 Ok(Self::reduced(num, den))
319 }
320
321 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
322 fn reduced(num: u64, den: u64) -> Self {
323 let g = gcd(num, den);
324 let (mut num, mut den) = (num / g, den / g);
325 // A ratio no pair of real frame rates produces, but the fields are `u32`
326 // so that every multiplication below fits a `u64` at any frame count.
327 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
328 (num, den) = (num.div_ceil(2), den.div_ceil(2));
329 }
330 Self {
331 source: num.max(1) as u32,
332 timeline: den.max(1) as u32,
333 }
334 }
335
336 /// The same file against a timeline that has itself been retimed: `self` is
337 /// its frames per frame of the old timeline and `k` is old frames per new
338 /// one, so this is its frames per frame of the *new* one -- exactly, without
339 /// going back through an `f64` fps that names neither rate
340 /// ([`crate::PlaybackSession::set_frame_rate`]).
341 pub fn then(self, k: Rate) -> Self {
342 Self::reduced(
343 u64::from(self.source) * u64::from(k.source),
344 u64::from(self.timeline) * u64::from(k.timeline),
345 )
346 }
347
348 pub fn is_real_time(self) -> bool {
349 self.source == self.timeline
350 }
351
352 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
353 /// is, given the timeline's, for a library row that names it.
354 pub fn as_f64(self) -> f64 {
355 f64::from(self.source) / f64::from(self.timeline)
356 }
357
358 /// Which frame of the file the `frame`th timeline-rate frame of it is:
359 /// floored, [`Speed::source_at`]'s half of the pair.
360 pub fn source_at(self, frame: u32) -> u32 {
361 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
362 .min(u64::from(u32::MAX)) as u32
363 }
364
365 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
366 /// timeline-rate frame that shows source frame `source_frame` -- which is
367 /// the stamp playback puts on a decoded picture, and, applied to a file's
368 /// frame *count*, how long that file is in timeline frames.
369 pub fn timeline_at(self, source_frame: u32) -> u32 {
370 (u64::from(source_frame) * u64::from(self.timeline))
371 .div_ceil(u64::from(self.source))
372 .min(u64::from(u32::MAX)) as u32
373 }
374}
375
376/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
377/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
378fn gcd(a: u64, b: u64) -> u64 {
379 match b {
380 0 => a.max(1),
381 b => gcd(b, a % b),
382 }
383}
384
385/// A half-open `[in_frame, out_frame)` range of frames of source
386/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
387/// Never empty.
388///
389/// Counted at the **timeline's** frame rate, not the file's: a source shot at
390/// another rate is converted at the decoder's door ([`Rate`]), so every edit
391/// here is frames of one clock.
392#[derive(Clone, Copy, PartialEq, Eq, Debug)]
393pub struct Clip {
394 /// Timeline frame the clip's first frame is shown at. Meaningless on a
395 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
396 /// with where the caller asked for.
397 pub start: u32,
398 pub in_frame: u32,
399 pub out_frame: u32,
400 /// Index into [`Project::sources`].
401 pub source: usize,
402 /// Group id: clips sharing one were split from the same take. `None` for a
403 /// clip that belongs to no group.
404 pub link: Option<u32>,
405 /// Index into the project's equalizer table
406 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
407 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
408 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
409 /// plain assignment. The table is append-only within a session, so an index
410 /// on a clipboard clip or inside an undo snapshot can never dangle.
411 pub eq: Option<u16>,
412 /// Index into the project's colour table
413 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
414 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
415 /// promises: `Copy`, append-only within a session, never dangling.
416 pub color: Option<u16>,
417 /// Index into the project's transform table
418 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
419 /// clip that plays at its fit policy's own placement. An index for
420 /// [`Clip::color`]'s reason and with the same promises.
421 pub transform: Option<u16>,
422 /// How this clip's picture meets a project canvas of another shape
423 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
424 /// two above: it is one byte with no parameters, so there is nothing for a
425 /// table to share, and a clip that is the project's own size never consults
426 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
427 /// where the aspect does not agree.
428 pub fit: FitPolicy,
429 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
430 /// eq and colour indexes: it is two bytes with nothing to share, and a table
431 /// would put a level of indirection between the mapping and the one number
432 /// every frame of it is divided by.
433 ///
434 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
435 /// the clip plays, so a trim and a split still address the file. What it
436 /// changes is how many *timeline* frames that range is spread over
437 /// ([`Clip::frames`]).
438 pub speed: Speed,
439 /// Timeline frames of ramp-up from silence at the clip's own start, inline
440 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
441 /// number with nothing to share, and every consumer (mixer, exporter) wants
442 /// it sitting right next to the frame range it shapes. Clamped to the
443 /// clip's own length by the setter -- never wider than the clip is long.
444 pub fade_in: u32,
445 /// Timeline frames of ramp-down to silence at the clip's own end. Same
446 /// promises as [`Clip::fade_in`].
447 pub fade_out: u32,
448 /// Timeline frames of cross-dissolve into the clip immediately after this
449 /// one on the same video lane, at this clip's own end -- `0` for a hard
450 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
451 /// reason, and clamped the same way by its setter
452 /// ([`Project::set_transition_out`]): never wider than this clip's own
453 /// length, nor than the successor it dissolves into. Meaningless -- and
454 /// left as whatever it was -- the moment the next clip stops abutting
455 /// this one; a reader that cares checks adjacency itself rather than
456 /// trusting this field alone, exactly as a stored fade is trusted only
457 /// because a clip's own length is checked beside it.
458 pub transition_out: u32,
459}
460
461impl Clip {
462 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
463 /// reads out of its file -- not how long it is on the timeline, which is
464 /// [`Clip::frames`] and differs the moment it is speeded.
465 pub fn len(&self) -> u32 {
466 self.out_frame - self.in_frame
467 }
468
469 /// Timeline frames it occupies: its source range at its own speed, never
470 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
471 /// what it overlaps, how wide its box is -- is asked of this and not of
472 /// [`Clip::len`].
473 pub fn frames(&self) -> u32 {
474 self.speed.frames(self.len())
475 }
476
477 /// One past the last timeline frame it covers.
478 pub fn end(&self) -> u32 {
479 self.start + self.frames()
480 }
481}
482
483/// A file the timeline plays from, and *which* of its audio streams it plays:
484/// a file carrying one track per language is several sources, one per stream,
485/// sharing a path. Two entries differing only in the stream are two sources --
486/// they are what a clip names, and a clip plays exactly one stream.
487///
488/// The path is always canonical ([`Source::new`]), so the same file reached by
489/// two paths is one source.
490#[derive(Clone, Debug, PartialEq, Eq)]
491pub struct Source {
492 pub path: PathBuf,
493 /// Position among the file's audio tracks in file order, the numbering
494 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
495 /// single track, and for a silent one.
496 pub audio_stream: usize,
497}
498
499impl Source {
500 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
501 Self {
502 path: canonical(path.as_ref()),
503 audio_stream,
504 }
505 }
506}
507
508/// What a lane carries, which is what a *gap* in it means: black frames on a
509/// video lane, silence on an audio one, nothing over the picture on a subtitle
510/// one.
511#[derive(Clone, Copy, PartialEq, Eq, Debug)]
512pub enum LaneKind {
513 Video,
514 Audio,
515 /// Words over the picture, placed and trimmed like everything else
516 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
517 /// so a caption is dragged, cut, rippled and undone by the machinery every
518 /// other clip already goes through.
519 ///
520 /// It carries no [`Clip`] at all, and that is what keeps the media paths
521 /// free of it: [`Project::lane`] hands back an empty slice, so every
522 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
523 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
524 /// check it already had, [`Project::composite_span_at`] and
525 /// [`Project::audio_lanes`] never look at it, and the three doors that
526 /// could still put a picture on one -- [`Project::from_parts`],
527 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
528 Subtitle,
529}
530
531/// Which lane an operation acts on: a kind plus a 0-based position among the
532/// lanes of that kind, so [`Lane::V1`] is the first video lane and
533/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
534///
535/// A handle, not the lane itself. It stays meaningful while lanes are added,
536/// and one naming a lane that is not there reads as an empty lane and refuses
537/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
538/// bounds check of its own.
539#[derive(Clone, Copy, PartialEq, Eq, Debug)]
540pub struct Lane {
541 pub kind: LaneKind,
542 pub ord: usize,
543}
544
545impl Lane {
546 /// The first video lane: what a decoder plays and what an export renders.
547 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
548 /// The first audio lane: what the audio worker plays.
549 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
550 /// The first subtitle lane -- the one a project has only once something
551 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
552 /// alone.
553 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
554
555 pub const fn new(kind: LaneKind, ord: usize) -> Self {
556 Self { kind, ord }
557 }
558
559 /// `V1`, `A2`: how a lane is written in a header column and named in an
560 /// error about it.
561 pub fn label(self) -> String {
562 let kind = match self.kind {
563 LaneKind::Video => 'V',
564 LaneKind::Audio => 'A',
565 LaneKind::Subtitle => 'S',
566 };
567 format!("{kind}{}", self.ord + 1)
568 }
569}
570
571/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
572/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
573/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
574/// frames. Never empty at either end.
575///
576/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
577/// actually has, and placed by the same one number: the window is in the
578/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
579/// placement is in timeline frames like everything else on a lane. So the lane
580/// invariant is the lane's ([`subs_sorted_disjoint`] is
581/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
582/// else, and only the two calls that change a *duration* -- a trim, and the
583/// mapping out -- ever need the timeline's rate.
584///
585/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
586/// paste and an undo snapshot are a plain assignment and can never dangle.
587#[derive(Clone, Copy, PartialEq, Eq, Debug)]
588pub struct SubClip {
589 /// Timeline frame its first frame is shown at.
590 pub start: u32,
591 /// How many timeline frames it covers; `>= 1`. Held rather than derived
592 /// from the window because a [`Project`] has no frame rate -- the rate
593 /// enters at the door of the two calls that need it -- and every placement
594 /// question (where it ends, what it overlaps) is asked in frames.
595 pub frames: u32,
596 /// Index into [`Project::subtitles`]: *which* track's words these are.
597 pub track: usize,
598 /// The half-open window of that track it shows, in microseconds from the
599 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
600 /// timed in, so no conversion stands between a cue and the window that
601 /// keeps it.
602 pub in_us: i64,
603 pub out_us: i64,
604 /// Group id: `Some` exactly when a hand put this caption in a group with
605 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
606 /// no group, and what a cut cuts apart loses the one it had
607 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
608 /// clip is what makes the caption move, trim and delete with it.
609 pub link: Option<u32>,
610}
611
612impl SubClip {
613 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
614 /// what every overlap question is asked of.
615 pub fn end(&self) -> u32 {
616 self.start + self.frames
617 }
618
619 /// How much of its track it shows, in microseconds; `>= 1` by the
620 /// never-empty invariant.
621 pub fn window_us(&self) -> i64 {
622 self.out_us - self.in_us
623 }
624
625 /// Where in its window the timeline frame `frame` falls, in microseconds --
626 /// the cut a split, a ripple and a trim all land on.
627 ///
628 /// By proportion and not by the timeline's rate: the window and the frame
629 /// count measure the same stretch of time, so the fraction of the frames
630 /// before `frame` is the fraction of the microseconds before it. That is
631 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
632 /// without either of them learning an fps.
633 fn window_at(&self, frame: u32) -> i64 {
634 let into = i64::from(frame.saturating_sub(self.start));
635 self.in_us + self.window_us() * into / i64::from(self.frames.max(1))
636 }
637}
638
639/// One lane: what it is and what it holds. A struct rather than a bare
640/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
641/// compositing mode, a name -- and it belongs next to the clips it applies to.
642#[derive(Clone, Debug)]
643struct LaneData {
644 kind: LaneKind,
645 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
646 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
647 /// ever seeing a subtitle: they all read this list.
648 clips: Vec<Clip>,
649 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
650 /// empty on a video or audio one. Beside the clips rather than an enum over
651 /// them so that everything a lane *is* -- its place in the stack, its
652 /// label, its undo snapshot, its removal -- stays one code path for all
653 /// three kinds.
654 subs: Vec<SubClip>,
655 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
656 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
657 /// makes it a different thing from a clip's equalizer: it moves everything
658 /// on the track by the same amount, cuts included. Meaningless on a video
659 /// lane, where it is kept at 0 and asked by nothing.
660 gain_db: f32,
661}
662
663impl LaneData {
664 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
665 Self {
666 kind,
667 clips,
668 subs: Vec::new(),
669 gain_db: 0.0,
670 }
671 }
672
673 /// The two lanes a project starts with: `V1` then `A1`, in display order.
674 /// One place, because a freshly opened file is exactly this pair.
675 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
676 vec![
677 LaneData::new(LaneKind::Video, video),
678 LaneData::new(LaneKind::Audio, audio),
679 ]
680 }
681}
682
683/// The placements one group id names, split by the two lists a lane holds:
684/// what a drag, a trim and a delete each have to walk, now that a group may
685/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
686/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
687/// -- so the pairs are `(lane storage index, index into that lane's list)`.
688#[derive(Default)]
689struct Members {
690 clips: Vec<(usize, usize)>,
691 subs: Vec<(usize, usize)>,
692}
693
694impl Members {
695 /// Whether the group is the one placement and no more: what a lift leaves
696 /// behind, and what every whole-group question answers "not one" for.
697 fn alone(&self) -> bool {
698 self.clips.len() + self.subs.len() < 2
699 }
700}
701
702/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
703#[derive(Clone, Copy, PartialEq, Eq, Debug)]
704pub enum Edge {
705 /// Its first timeline frame; moving it changes where in the source the clip
706 /// starts reading, so the picture behind the edge slides with it.
707 Start,
708 /// One past its last timeline frame; moving it only says how much of the
709 /// source to keep.
710 End,
711}
712
713/// What a lane holds over one stretch of the timeline: either a placed clip or
714/// a gap. Returned already trimmed to the position it was asked about, so a
715/// caller can hand `len` straight to a decoder (or to a black-frame generator).
716#[derive(Clone, Copy, PartialEq, Eq, Debug)]
717pub struct Span {
718 /// Timeline frame the span starts at.
719 pub start: u32,
720 /// Frames it covers; `>= 1`.
721 pub len: u32,
722 /// `(source index, first source frame)`, or `None` for a gap -- which the
723 /// engine renders as black frames and as silence.
724 pub from: Option<(usize, u32)>,
725 /// The rate the clip this came off plays at ([`Clip::speed`]);
726 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
727 /// timeline frames whatever it says -- the speed is how many *source* frames
728 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
729 /// come back to the timeline.
730 pub speed: Speed,
731}
732
733impl Span {
734 /// One past the last timeline frame it covers.
735 pub fn end(&self) -> u32 {
736 self.start + self.len
737 }
738
739 /// How many source frames it reads: what a decoder is asked for and how wide
740 /// an audio window is. `len` at real time, and the one arithmetic both the
741 /// picture and the sound go through, so they cannot disagree about where a
742 /// speeded clip ends.
743 pub fn source_len(&self) -> u32 {
744 match self.from {
745 // The last timeline frame's own source frame is the last one needed
746 // -- never one more, which at a slow rate would read a frame the
747 // next clip owns and at a fast one would decode a picture nothing
748 // shows.
749 Some(_) => self.speed.source_at(self.len.saturating_sub(1)) + 1,
750 None => self.len,
751 }
752 }
753
754 /// Where a source frame of this span lands on the timeline: the stamp
755 /// playback puts on a decoded frame, through the ceil half of the pair
756 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
757 /// frame, so a frame before it stamps at the span's start.
758 pub fn timeline_at(&self, source_frame: u32) -> u32 {
759 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
760 self.start + self.speed.timeline_at(source_frame.saturating_sub(base))
761 }
762}
763
764/// What one speeded audio segment asks of the worker: how many source frames to
765/// consume per output frame, and how many seconds of timeline it has to fill.
766/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
767/// resampling at all.
768#[derive(Clone, Copy, PartialEq, Debug)]
769pub struct Stretch {
770 /// Source frames per output frame -- the speed as a multiplier.
771 pub step: f64,
772 /// What the segment owes the timeline, which is what it is padded or
773 /// trimmed to.
774 pub timeline_secs: f64,
775}
776
777/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
778/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
779/// against where in the *clip* -- not the segment, which may start mid-clip
780/// on a seek -- this segment's first frame lands.
781#[derive(Clone, Copy, PartialEq, Eq, Debug)]
782pub struct Fade {
783 /// How many of the clip's own frames already played before this
784 /// segment's first frame: `0` unless playback started mid-clip.
785 pub elapsed: u32,
786 /// The clip's [`Clip::fade_in`].
787 pub fade_in: u32,
788 /// The clip's [`Clip::fade_out`].
789 pub fade_out: u32,
790 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
791 /// which this segment may only cover the tail.
792 pub total: u32,
793}
794
795impl Fade {
796 /// The gain at clip-relative frame `pos`, an equal-power curve on each
797 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
798 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
799 /// ramp, so a fade lands on silence at its very first (or very last)
800 /// frame and reaches unity smoothly rather than at a constant slope --
801 /// the same curve [`Project::crossfade`] relies on to keep two clips'
802 /// sum around one level through the join. Both ramps multiply where a
803 /// clip is short enough for them to overlap.
804 fn gain_at(self, pos: u32) -> f32 {
805 let mut g = 1.0f32;
806 if self.fade_in > 0 && pos < self.fade_in {
807 let t = pos as f32 / self.fade_in as f32;
808 g *= (t * std::f32::consts::FRAC_PI_2).sin();
809 }
810 if self.fade_out > 0 {
811 let out_start = self.total.saturating_sub(self.fade_out);
812 if pos >= out_start {
813 let remaining = self.total.saturating_sub(pos);
814 let t = remaining as f32 / self.fade_out as f32;
815 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
816 }
817 }
818 g
819 }
820
821 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
822 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
823 pub fn apply(self, frames: &mut [f32], channels: usize) {
824 for (i, block) in frames.chunks_mut(channels).enumerate() {
825 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
826 for s in block {
827 *s *= g;
828 }
829 }
830 }
831
832 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
833 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
834 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
835 /// position is in) but [`Self::apply`] multiplies *audio* frames --
836 /// `channels`-wide sample blocks at whatever rate the mix is running at,
837 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
838 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
839 /// few milliseconds into any clip, so a fade-out silenced the rest of the
840 /// clip outright and a fade-in finished before a listener's ear caught up
841 /// -- audible on nothing shorter than a clip a few fps-frames long, which
842 /// is why 338 green tests never once ran the two curves out of step.
843 /// `ratio` is `sample_rate / fps`, applied once where the audio session
844 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
845 pub fn scaled(self, ratio: f64) -> Fade {
846 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
847 Fade {
848 elapsed: conv(self.elapsed),
849 fade_in: conv(self.fade_in),
850 fade_out: conv(self.fade_out),
851 total: conv(self.total),
852 }
853 }
854}
855
856/// What a save writes and a load takes back: the sources, every lane in
857/// display order with its kind, and the equalizer and colour tables their clips
858/// index into -- [`Project::without_orphan_sources`] out,
859/// [`Project::from_parts`] in.
860pub type Parts = (
861 Vec<Source>,
862 Vec<(LaneKind, Vec<Clip>)>,
863 Vec<EqParams>,
864 Vec<ColorParams>,
865 Vec<TransformParams>,
866);
867
868/// How many undo steps a project keeps. One gesture is one step, so 100 is past
869/// any chain a person walks back by hand, and the oldest step is dropped rather
870/// than the history growing without end: a snapshot is the whole lane list, so
871/// on a 1394-clip jumpcut timeline this is a bounded ~10 MB instead of a leak
872/// that grows for as long as the session lasts.
873const HISTORY_CAP: usize = 100;
874
875/// The edit list plus its undo history.
876#[derive(Clone, Debug)]
877pub struct Project {
878 /// Append-only: never popped, never reordered. See the module docs.
879 sources: Vec<Source>,
880 /// In display order, which is the order [`Lane::ord`] counts in: the nth
881 /// lane of a kind here is that kind's `ord` n. Never empty.
882 lanes: Vec<LaneData>,
883 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
884 eq: Vec<EqParams>,
885 /// The same, for [`Clip::color`].
886 color: Vec<ColorParams>,
887 /// The same, for [`Clip::transform`].
888 transform: Vec<TransformParams>,
889 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
890 /// whole lane list, so adding a lane undoes as well. Bounded by
891 /// [`HISTORY_CAP`]: at the cap the oldest step goes.
892 history: Vec<Vec<LaneData>>,
893 /// Lane lists `undo` has stepped past; `redo` pops one. Cleared by
894 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
895 /// the undone steps came from. Not saved to `.edith`, matching `history`.
896 redo: Vec<Vec<LaneData>>,
897 /// Never rolled back by an undo: an id retired by an undone split must not
898 /// come back and group two clips that were never together.
899 next_link: u32,
900 /// The subtitle tracks this timeline shows, in the order they were added.
901 /// Not in the lane list and not in the history snapshots, for the reason
902 /// the limiter is not: which subtitles a project carries is a setting on
903 /// it, and it is saved as a *reference* to the file the cues came out of
904 /// ([`crate::subtitle`]).
905 subtitles: Vec<SubtitleTrack>,
906 /// The master limiter every lane's sound is summed *through*
907 /// ([`Project::limiter`]). Off by default, and not in the lane list, which
908 /// is what the history snapshots hold: it is a setting on the mix, like the
909 /// project's resolution is a setting on the picture, and neither is an undo
910 /// step.
911 limiter: Limiter,
912 /// Which HDR-to-SDR rendition every clip on an HDR curve is shown and
913 /// exported in ([`crate::tonemap::Preset`]). A setting on the picture, like
914 /// the resolution, and not in the lane snapshots for the same reason.
915 tone: crate::tonemap::Preset,
916}
917
918impl Project {
919 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
920 /// grouped -- the state of a freshly opened video, where the timeline is the
921 /// source. `frame_count` of 0 would break the never-empty invariant, so it
922 /// is clamped to one frame.
923 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
924 let clip = Clip {
925 fade_in: 0,
926 fade_out: 0,
927 transition_out: 0,
928 start: 0,
929 in_frame: 0,
930 out_frame: frame_count.max(1),
931 source: 0,
932 link: Some(0),
933 eq: None,
934 color: None,
935 transform: None,
936 fit: FitPolicy::default(),
937 speed: Speed::NORMAL,
938 };
939 Self {
940 // A file is opened on its first audio stream: nothing has picked
941 // one yet, and every file with audio at all has that one.
942 sources: vec![Source::new(path, 0)],
943 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
944 eq: Vec::new(),
945 color: Vec::new(),
946 transform: Vec::new(),
947 history: Vec::new(),
948 redo: Vec::new(),
949 next_link: 1,
950 subtitles: Vec::new(),
951 limiter: Limiter::default(),
952 tone: crate::tonemap::Preset::default(),
953 }
954 }
955
956 /// A project rebuilt from a saved edit list -- the load half of
957 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
958 /// an `ord` is a lane's position among the lanes of that kind, exactly as
959 /// [`Project::lanes`] hands them back. History is *not* saved, so
960 /// [`Project::undo`] is `false` until the first edit of the new session.
961 /// This is the one door untrusted parts come in through, so every invariant
962 /// every other constructor keeps is checked here, by name and in release:
963 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
964 /// or a colour) that is not there, a clip whose end overflows, a lane that is
965 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
966 /// below.
967 ///
968 /// A project whose lanes are all *empty* is not among them: an emptied
969 /// timeline is a project like any other -- it plays black and silent, it
970 /// saves, and it loads back. What a project cannot be is laneless, because
971 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
972 /// handle indexes into.
973 pub fn from_parts(
974 sources: Vec<Source>,
975 lanes: Vec<(LaneKind, Vec<Clip>)>,
976 eq: Vec<EqParams>,
977 color: Vec<ColorParams>,
978 transform: Vec<TransformParams>,
979 ) -> crate::Result<Self> {
980 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
981 return Err(format!("eq {bad} holds a band that is not a finite number").into());
982 }
983 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
984 return Err(format!("color {bad} holds a value that is not a finite number").into());
985 }
986 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
987 return Err(format!("transform {bad} holds a value that is not a finite number").into());
988 }
989 if lanes.is_empty() {
990 return Err("no lanes at all: that is not a project".into());
991 }
992 let lanes: Vec<LaneData> = lanes
993 .into_iter()
994 .map(|(kind, clips)| LaneData::new(kind, clips))
995 .collect();
996 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
997 let name = lane.label();
998 // A subtitle lane carries words and never a picture
999 // ([`LaneKind::Subtitle`]); a file that puts one there names a
1000 // source on a lane that has nothing to play it with, and every
1001 // media path below would then read a clip off a lane it does not
1002 // know about.
1003 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
1004 return Err(format!(
1005 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
1006 data.clips.len()
1007 )
1008 .into());
1009 }
1010 for c in &data.clips {
1011 if c.out_frame <= c.in_frame {
1012 return Err(format!(
1013 "{name} clip at {} plays the empty range [{}, {})",
1014 c.start, c.in_frame, c.out_frame
1015 )
1016 .into());
1017 }
1018 if c.source >= sources.len() {
1019 return Err(format!(
1020 "{name} clip at {} names source {} of {}",
1021 c.start,
1022 c.source,
1023 sources.len()
1024 )
1025 .into());
1026 }
1027 if c.start.checked_add(c.frames()).is_none() {
1028 return Err(format!(
1029 "{name} clip at {} runs past the last frame there is",
1030 c.start
1031 )
1032 .into());
1033 }
1034 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
1035 return Err(format!(
1036 "{name} clip at {} names eq {} of {}",
1037 c.start,
1038 c.eq.unwrap_or_default(),
1039 eq.len()
1040 )
1041 .into());
1042 }
1043 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
1044 return Err(format!(
1045 "{name} clip at {} names color {} of {}",
1046 c.start,
1047 c.color.unwrap_or_default(),
1048 color.len()
1049 )
1050 .into());
1051 }
1052 if c.transform.is_some_and(|i| usize::from(i) >= transform.len()) {
1053 return Err(format!(
1054 "{name} clip at {} names transform {} of {}",
1055 c.start,
1056 c.transform.unwrap_or_default(),
1057 transform.len()
1058 )
1059 .into());
1060 }
1061 }
1062 if !sorted_disjoint(&data.clips) {
1063 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1064 }
1065 }
1066 links_are_consistent(&lanes)?;
1067 // The counter sits past every id the file names, on either of a lane's
1068 // lists: a v16 caption may carry the highest link there is, and a
1069 // re-issued id would silently group it with the next placement that
1070 // asks for one -- the loader refusing a save the editor just wrote.
1071 let next_link = lanes
1072 .iter()
1073 .flat_map(|l| {
1074 let clips = l.clips.iter().filter_map(|c| c.link);
1075 let subs = l.subs.iter().filter_map(|s| s.link);
1076 clips.chain(subs)
1077 })
1078 .max()
1079 // Saturating so a crafted file cannot make the counter wrap: at the
1080 // ceiling ids stop being fresh, which loses grouping, not memory.
1081 .map_or(0, |m| m.saturating_add(1));
1082 Ok(Self {
1083 sources: sources
1084 .iter()
1085 .map(|s| Source::new(&s.path, s.audio_stream))
1086 .collect(),
1087 lanes,
1088 eq,
1089 color,
1090 transform,
1091 history: Vec::new(),
1092 redo: Vec::new(),
1093 next_link,
1094 subtitles: Vec::new(),
1095 limiter: Limiter::default(),
1096 tone: crate::tonemap::Preset::default(),
1097 })
1098 }
1099
1100 /// The first video lane -- what an export renders and what a single-lane
1101 /// caller still means by "the clips".
1102 pub fn clips(&self) -> &[Clip] {
1103 self.lane(Lane::V1)
1104 }
1105
1106 /// The clips of `lane`, or nothing at all for a lane that is not there.
1107 pub fn lane(&self, lane: Lane) -> &[Clip] {
1108 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
1109 }
1110
1111 /// Every lane's handle, in display order -- what a walk over "all lanes"
1112 /// iterates, and what a front-end lays out top to bottom.
1113 pub fn lanes(&self) -> Vec<Lane> {
1114 handles(&self.lanes)
1115 }
1116
1117 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
1118 /// for every `ord` below it, and none at or above it.
1119 pub fn lane_count(&self, kind: LaneKind) -> usize {
1120 self.lanes.iter().filter(|l| l.kind == kind).count()
1121 }
1122
1123 /// Appends an empty lane of `kind` and hands back its handle. One undo
1124 /// step, because the lane list is state a front-end shows: an added lane
1125 /// that could not be taken back would be the one edit with no way out.
1126 /// Nothing plays differently until something is placed on it.
1127 ///
1128 /// An empty lane is a lane like any other -- so is a whole project of them
1129 /// ([`Project::from_parts`]); nothing plays until something is placed.
1130 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1131 self.snapshot();
1132 self.lanes.push(LaneData::new(kind, Vec::new()));
1133 Lane::new(kind, self.lane_count(kind) - 1)
1134 }
1135
1136 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
1137 /// one undo step like it, which restores the lane where it stood.
1138 ///
1139 /// Refused, changing nothing, while the lane holds anything: the refusal
1140 /// names the clips (file and first frame), because a track removal that
1141 /// deleted takes with it would be the one edit nobody sees coming. Refused
1142 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
1143 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
1144 /// kind and *skips* a kind that is not there), so a project without one
1145 /// would swallow half of every file dropped on it, silently.
1146 ///
1147 /// The lanes below it move up one `ord`, so a handle a caller was holding
1148 /// (a selection, an open card) names the lane after it from here on -- the
1149 /// one thing a front-end owes this call.
1150 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1151 let Some(i) = self.index(lane) else {
1152 return Err(format!("there is no {} to remove", lane.label()).into());
1153 };
1154 // A subtitle lane is not in that rule: nothing lands on one by itself
1155 // -- a project starts without any and one is added when a caption is --
1156 // so the last of them comes off like any other empty track.
1157 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
1158 return Err(format!(
1159 "{} is the only {} track: every import lands on it",
1160 lane.label(),
1161 match lane.kind {
1162 LaneKind::Video => "video",
1163 LaneKind::Audio => "audio",
1164 // Unreachable while the guard above lets the last subtitle
1165 // lane go, and its own word here so the sentence stays true
1166 // if that rule is ever relaxed.
1167 LaneKind::Subtitle => "subtitle",
1168 }
1169 )
1170 .into());
1171 }
1172 if !self.lanes[i].subs.is_empty() {
1173 // Three names and a count, exactly as the clips below get: the way
1174 // out of the refusal is the drag, so the words say so.
1175 let named: Vec<String> = self.lanes[i]
1176 .subs
1177 .iter()
1178 .take(3)
1179 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
1180 .collect();
1181 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
1182 0 => String::new(),
1183 n => format!(" and {n} more"),
1184 };
1185 return Err(format!(
1186 "{} still holds {}{rest}: delete those captions (or drag them to \
1187 another track) first",
1188 lane.label(),
1189 named.join(", ")
1190 )
1191 .into());
1192 }
1193 let clips = &self.lanes[i].clips;
1194 if !clips.is_empty() {
1195 // Three names and a count: a lane can hold forty clips and a
1196 // refusal nobody reads to the end says nothing at all.
1197 let named: Vec<String> = clips
1198 .iter()
1199 .take(3)
1200 .map(|c| {
1201 let name = self.sources.get(c.source).map_or_else(
1202 || format!("source {}", c.source),
1203 |s| s.path.display().to_string(),
1204 );
1205 format!("{name} at frame {}", c.start)
1206 })
1207 .collect();
1208 let rest = match clips.len().saturating_sub(named.len()) {
1209 0 => String::new(),
1210 n => format!(" and {n} more"),
1211 };
1212 return Err(format!(
1213 "{} still holds {}{rest}: delete those clips (or drag them to \
1214 another track) first",
1215 lane.label(),
1216 named.join(", ")
1217 )
1218 .into());
1219 }
1220 self.snapshot();
1221 self.lanes.remove(i);
1222 Ok(())
1223 }
1224
1225 /// Moves `lane` to display position `to` -- an index into
1226 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
1227 /// the handle it answers to from now on. `None`, changing nothing and
1228 /// snapshotting nothing, for a lane that is not there, a position that is
1229 /// not, and a lane already standing in it.
1230 ///
1231 /// The whole track travels: its clips, its gain, its kind. Nothing is
1232 /// remapped, so no take changes lane and no group is broken -- this is the
1233 /// *order* of the lanes and nothing else, which is why one call is one undo
1234 /// step like an add or a removal.
1235 ///
1236 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
1237 /// last video lane covering a frame, so moving one video lane past another
1238 /// changes which picture wins, in the preview and in an export alike. The
1239 /// audio lanes are summed and their sum does not care about order, so an
1240 /// audio track moved among the video ones is a rearrangement of the screen
1241 /// alone.
1242 ///
1243 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
1244 /// position among the lanes of that kind), so a lane that crosses one of
1245 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
1246 /// `V1`, clips and all -- while one that crosses only lanes of the other
1247 /// kind keeps its name. That is the returned handle: unchanged means every
1248 /// handle a caller holds still names the track it named before.
1249 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
1250 let i = self.index(lane)?;
1251 if to >= self.lanes.len() || to == i {
1252 return None;
1253 }
1254 self.snapshot();
1255 let data = self.lanes.remove(i);
1256 self.lanes.insert(to, data);
1257 Some(handles(&self.lanes)[to])
1258 }
1259
1260 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
1261 /// not there. The one place a handle becomes a position.
1262 fn index(&self, lane: Lane) -> Option<usize> {
1263 self.lanes
1264 .iter()
1265 .enumerate()
1266 .filter(|(_, l)| l.kind == lane.kind)
1267 .map(|(i, _)| i)
1268 .nth(lane.ord)
1269 }
1270
1271 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
1272 let i = self.index(lane)?;
1273 Some(&mut self.lanes[i].clips)
1274 }
1275
1276 /// The files the clips index into, in import order; index 0 is the file the
1277 /// project was opened with.
1278 pub fn sources(&self) -> &[Source] {
1279 &self.sources
1280 }
1281
1282 /// The same list in the `(path, stream)` shape the audio engine indexes
1283 /// into -- [`crate::AudioSession::open_multi_streams`] and
1284 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
1285 /// was placed with is the stream that plays *and* the stream that exports.
1286 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
1287 self.sources
1288 .iter()
1289 .map(|s| (s.path.clone(), s.audio_stream))
1290 .collect()
1291 }
1292
1293 /// Index for `path` played on `audio_stream`, appending it if it is new.
1294 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
1295 /// by two paths imports once and two streams of one file are two sources.
1296 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
1297 /// no history: a source entry alone changes nothing playable.
1298 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
1299 let source = Source::new(path, audio_stream);
1300 match self.sources.iter().position(|s| *s == source) {
1301 Some(idx) => idx,
1302 None => {
1303 self.sources.push(source);
1304 self.sources.len() - 1
1305 }
1306 }
1307 }
1308
1309 /// Append a whole-file clip of `source` to the end of every *media* lane,
1310 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
1311 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
1312 /// come in through [`Project::add_subtitles`], which is the palette.
1313 ///
1314 /// One history snapshot, so an import is one undo step, and undoing it
1315 /// leaves the (harmless) source entry behind, because indexes are forever.
1316 /// Refused for an unknown source index.
1317 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
1318 if source >= self.sources.len() {
1319 return false;
1320 }
1321 self.snapshot();
1322 let start = self.timeline_frames();
1323 let clip = Clip {
1324 fade_in: 0,
1325 fade_out: 0,
1326 transition_out: 0,
1327 start,
1328 in_frame: 0,
1329 out_frame: frame_count.max(1),
1330 source,
1331 link: Some(self.new_link()),
1332 eq: None,
1333 color: None,
1334 transform: None,
1335 fit: FitPolicy::default(),
1336 speed: Speed::NORMAL,
1337 };
1338 for data in self
1339 .lanes
1340 .iter_mut()
1341 .filter(|l| l.kind != LaneKind::Subtitle)
1342 {
1343 data.clips.push(clip);
1344 }
1345 true
1346 }
1347
1348 /// Drops a source entry -- the file a library row *is* -- and renumbers
1349 /// every clip that indexed past it, which is why this is more than a
1350 /// `Vec::remove`.
1351 ///
1352 /// Refused, changing nothing, while any clip still plays from it: the
1353 /// refusal names the lanes and how many clips each holds, so a caller can
1354 /// say what has to be deleted first. The *last* entry goes like any other
1355 /// -- a project may name no file at all, which is an empty library over an
1356 /// empty timeline (nothing can play, since a clip would have refused the
1357 /// removal). What a front-end does with that is its own decision: `edith`'s
1358 /// window goes back to the empty state it launches in, and
1359 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
1360 /// refuses to write a project that names nothing, because no such file
1361 /// could be opened again.
1362 ///
1363 /// Every index past `idx` moves down by one, so a caller holding a *raw*
1364 /// source index of its own -- a clipboard, which is the one thing outside
1365 /// this type that does -- has to fix it up or drop it, or a paste plays a
1366 /// different file. [`PlaybackSession::remove_source`] hands back the index
1367 /// that went for exactly that.
1368 ///
1369 /// corner-cut: this retires the undo stack. `history` holds lanes alone, so a
1370 /// snapshot older than the removal can name the very source being removed
1371 /// (delete a file's clips, then remove the file) and restoring it would
1372 /// point a clip at an entry that is gone. The upgrade path is snapshotting
1373 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
1374 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
1375 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
1376 /// exists) currently rules out.
1377 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
1378 let Some(source) = self.sources.get(idx) else {
1379 return Err(format!("there is no source {idx} to remove").into());
1380 };
1381 let name = source.path.display().to_string();
1382 let used: Vec<String> = handles(&self.lanes)
1383 .into_iter()
1384 .zip(&self.lanes)
1385 .filter_map(
1386 |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
1387 0 => None,
1388 1 => Some(format!("{} (1 clip)", lane.label())),
1389 n => Some(format!("{} ({n} clips)", lane.label())),
1390 },
1391 )
1392 .collect();
1393 if !used.is_empty() {
1394 return Err(format!("{name} still plays on {}", used.join(", ")).into());
1395 }
1396 self.sources.remove(idx);
1397 for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
1398 if c.source > idx {
1399 c.source -= 1;
1400 }
1401 }
1402 self.history.clear();
1403 Ok(())
1404 }
1405
1406 /// The sources a clip actually names, with the clips reindexed onto them
1407 /// -- what a save writes. Indexes are forever *inside* a session (see
1408 /// [`Project::append_clip`]), so an undone import leaves an orphan source
1409 /// entry behind; writing that orphan to a project file would let a file
1410 /// nothing plays refuse a future load. New indexes are assigned in order of
1411 /// first use -- lane by lane, in display order -- so the same project always
1412 /// emits the same bytes.
1413 ///
1414 /// Every lane comes out, in display order and with its kind: that is what a
1415 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
1416 /// takes back.
1417 ///
1418 /// The equalizer and colour tables are pruned the same way and for the same
1419 /// reason: an undone [`set_eq`](Project::set_eq) or
1420 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
1421 /// and this is the one moment they can go -- the indexes that survive it are
1422 /// only the ones a clip names.
1423 ///
1424 /// One exception, and it is the emptied timeline's: a project no clip plays
1425 /// from still keeps its first source, if it has one. A file is what a
1426 /// reopened project scaffolds itself from -- the frame rate is written
1427 /// nowhere else -- so a save that pruned the last of them would write a
1428 /// project that cannot be loaded back at all.
1429 ///
1430 /// What comes out is *not* ordered by anything a reader may assume: first
1431 /// use, lane by lane, means the entry at index 0 can be a still or a song
1432 /// whatever the session was scaffolded from. `PlaybackSession::open_project`
1433 /// picks its rate and its audio reference by what a source *is*, never by
1434 /// where it sits.
1435 pub fn without_orphan_sources(&self) -> Parts {
1436 let mut moved = vec![None; self.sources.len()];
1437 let mut sources = Vec::new();
1438 let mut moved_eq = vec![None; self.eq.len()];
1439 let mut eq = Vec::new();
1440 let mut moved_color = vec![None; self.color.len()];
1441 let mut color = Vec::new();
1442 let mut moved_transform = vec![None; self.transform.len()];
1443 let mut transform = Vec::new();
1444 let mut lanes = self.lanes.clone();
1445 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
1446 let old = c.source;
1447 c.source = match moved[old] {
1448 Some(new) => new,
1449 None => {
1450 sources.push(self.sources[old].clone());
1451 moved[old] = Some(sources.len() - 1);
1452 sources.len() - 1
1453 }
1454 };
1455 if let Some(old) = c.eq.map(usize::from) {
1456 c.eq = Some(match moved_eq[old] {
1457 Some(new) => new,
1458 None => {
1459 eq.push(self.eq[old].clone());
1460 let new = (eq.len() - 1) as u16;
1461 moved_eq[old] = Some(new);
1462 new
1463 }
1464 });
1465 }
1466 if let Some(old) = c.color.map(usize::from) {
1467 c.color = Some(match moved_color[old] {
1468 Some(new) => new,
1469 None => {
1470 color.push(self.color[old]);
1471 let new = (color.len() - 1) as u16;
1472 moved_color[old] = Some(new);
1473 new
1474 }
1475 });
1476 }
1477 if let Some(old) = c.transform.map(usize::from) {
1478 c.transform = Some(match moved_transform[old] {
1479 Some(new) => new,
1480 None => {
1481 transform.push(self.transform[old]);
1482 let new = (transform.len() - 1) as u16;
1483 moved_transform[old] = Some(new);
1484 new
1485 }
1486 });
1487 }
1488 }
1489 if sources.is_empty() {
1490 sources.extend(self.sources.first().cloned());
1491 }
1492 (
1493 sources,
1494 // Every lane, subtitle ones included: they hold no [`Clip`], so what
1495 // comes out for one is an empty list, and its *place* in the display
1496 // order is what a save writes it for. What is on it travels beside
1497 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
1498 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
1499 eq,
1500 color,
1501 transform,
1502 )
1503 }
1504
1505 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
1506 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
1507 /// track moves by it, which is what makes it a different control from a
1508 /// clip's equalizer (one frequency range of one take) and from the master
1509 /// volume (what this machine monitors at, which no file carries).
1510 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1511 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
1512 }
1513
1514 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
1515 /// One undo step like every other edit -- it is in the lane list, so an
1516 /// undo restores it with the rest. `false`, and no history, for a lane that
1517 /// is not there, for a value that is not finite, and for one already set.
1518 ///
1519 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
1520 /// a value nobody reads: words have no loudness, so a slider that appeared
1521 /// to move one would be a control with no effect. (A video lane's gain is
1522 /// meaningless in the same way but is kept settable: it is the pair `A1`
1523 /// carries for a take, and mixing reads it off the audio lane alone.)
1524 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1525 let Some(i) = self.index(lane) else {
1526 return false;
1527 };
1528 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
1529 return false;
1530 }
1531 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1532 if self.lanes[i].gain_db == db {
1533 return false;
1534 }
1535 self.snapshot();
1536 self.lanes[i].gain_db = db;
1537 true
1538 }
1539
1540 /// Every lane's volume in dB, in display order -- what a save writes,
1541 /// beside the lanes [`Project::without_orphan_sources`] hands back.
1542 ///
1543 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
1544 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
1545 /// one): a save zips the two lists, so a lane that is in one and not the
1546 /// other would hand every track below it the volume of the track above.
1547 pub fn lane_gains(&self) -> Vec<f32> {
1548 self.lanes.iter().map(|l| l.gain_db).collect()
1549 }
1550
1551 /// What is placed on every lane, in display order and in step with
1552 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
1553 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
1554 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
1555 ///
1556 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
1557 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
1558 /// clip's source there is no orphan to prune and no index to move.
1559 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
1560 self.lanes.iter().map(|l| l.subs.clone()).collect()
1561 }
1562
1563 /// The placements a *load* puts back, one list per lane in display order --
1564 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
1565 /// same reason. Called *after*
1566 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
1567 /// names.
1568 ///
1569 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
1570 /// like it, by name and in release, because it is the same untrusted file:
1571 /// a placement on a lane that is not a subtitle lane, an empty span or an
1572 /// empty window, a track the palette does not have, a span running past the
1573 /// last frame there is, and a lane that is out of order or overlaps itself
1574 /// ([`place_sub`] refuses every one of those on the live timeline).
1575 ///
1576 /// [`place_sub`]: Project::place_sub
1577 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
1578 let names = handles(&self.lanes);
1579 let palette = self.subtitles.len();
1580 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
1581 let name = lane.label();
1582 if list.is_empty() {
1583 continue;
1584 }
1585 if data.kind != LaneKind::Subtitle {
1586 return Err(format!(
1587 "{name} is not a subtitle track and holds {} caption(s): words go on a \
1588 subtitle track",
1589 list.len()
1590 )
1591 .into());
1592 }
1593 for s in &list {
1594 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
1595 return Err(format!(
1596 "{name} caption at {} is empty: {} frames of [{}, {})",
1597 s.start, s.frames, s.in_us, s.out_us
1598 )
1599 .into());
1600 }
1601 if s.track >= palette {
1602 return Err(format!(
1603 "{name} caption at {} names subtitle track {} of {palette}",
1604 s.start, s.track
1605 )
1606 .into());
1607 }
1608 if s.start.checked_add(s.frames).is_none() {
1609 return Err(format!(
1610 "{name} caption at {} runs past the last frame there is",
1611 s.start
1612 )
1613 .into());
1614 }
1615 }
1616 if !subs_sorted_disjoint(&list) {
1617 return Err(format!("the {name} lane is out of order or overlaps itself").into());
1618 }
1619 data.subs = list;
1620 // The counter also has to clear the ids these captions carry: this
1621 // is the door a load's placements come through, *after*
1622 // [`from_parts`](Project::from_parts) seeded it from the clips, and
1623 // a hand-grouped caption may carry the highest id in the file.
1624 self.next_link = self.next_link.max(
1625 data.subs
1626 .iter()
1627 .filter_map(|s| s.link)
1628 .max()
1629 .map_or(0, |m| m.saturating_add(1)),
1630 );
1631 }
1632 Ok(self)
1633 }
1634
1635 /// The mix settings a *load* puts back: lane volumes in display order (a
1636 /// short list leaves the rest at unity) and the master limiter, both
1637 /// clamped as their setters clamp them.
1638 ///
1639 /// The load's own door, beside [`from_parts`](Project::from_parts): the
1640 /// setters push an undo step, and a project that arrives one undo away from
1641 /// a state it was never in is a project whose first ctrl+z is a surprise.
1642 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
1643 for (data, &db) in self.lanes.iter_mut().zip(gains) {
1644 if db.is_finite() {
1645 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
1646 }
1647 }
1648 self.limiter = limiter.with_ceiling(limiter.ceiling_db);
1649 self
1650 }
1651
1652 /// The HDR rendition a *load* puts back -- the same door
1653 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
1654 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
1655 self.tone = preset;
1656 self
1657 }
1658
1659 /// Which HDR-to-SDR rendition this project is watched and exported in. A
1660 /// project setting, not a clip's: one picture, one look
1661 /// ([`crate::tonemap::Preset`]).
1662 pub fn tone(&self) -> crate::tonemap::Preset {
1663 self.tone
1664 }
1665
1666 /// Sets it. `false` for the one already in force, which is what keeps a
1667 /// re-pick of the current rendition from costing a reseek.
1668 ///
1669 /// corner-cut: not an undo step, for the reason the limiter and the project
1670 /// resolution are not -- it is not in the lane list the history snapshots.
1671 /// Upgrade path is the same one: a history entry holding the project's own
1672 /// settings beside the lanes.
1673 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1674 if self.tone == preset {
1675 return false;
1676 }
1677 self.tone = preset;
1678 true
1679 }
1680
1681 /// The subtitle tracks a *load* puts back, in the order they were saved --
1682 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
1683 /// the same reason.
1684 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
1685 self.subtitles = tracks;
1686 self
1687 }
1688
1689 /// What this timeline shows over the picture, in the order they were added:
1690 /// what a front-end lists and what a save writes.
1691 pub fn subtitles(&self) -> &[SubtitleTrack] {
1692 &self.subtitles
1693 }
1694
1695 /// Adds a track, unless the very same one -- same file, same track number
1696 /// inside it -- is already on the list. `false` for that repeat: importing
1697 /// the same `.srt` twice is one subtitle track, not two identical ones.
1698 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
1699 if self
1700 .subtitles
1701 .iter()
1702 .any(|t| t.path == track.path && t.track == track.track)
1703 {
1704 return false;
1705 }
1706 self.subtitles.push(track.clone());
1707 true
1708 }
1709
1710 /// Takes the track at `idx` off the list -- what a row's own remove goes
1711 /// through, so whatever an import added can be taken back out. Refused by
1712 /// name for a row this project does not have, rather than a silent no-op:
1713 /// a front-end holding a stale index has picked the wrong row and needs to
1714 /// hear it.
1715 ///
1716 /// Every index past `idx` moves down by one, as [`remove_source`](
1717 /// Project::remove_source)'s do: a caller holding a picked row (an export's
1718 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
1719 /// it, or it names a different track afterwards. The placements on the
1720 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
1721 /// index into this very list, so every one past `idx` is walked down with
1722 /// it here -- the reindex [`remove_source`](Project::remove_source) does
1723 /// for its clips, for its reason.
1724 ///
1725 /// Refused, changing nothing, while anything placed on a subtitle lane
1726 /// plays *this* row: the placement would have to be deleted or retargeted,
1727 /// and either one is an edit nobody asked for. The refusal names the lane
1728 /// and the frame it is at, up to three of them --
1729 /// [`remove_source`](Project::remove_source) refuses the same way for the
1730 /// same silent corruption.
1731 ///
1732 /// corner-cut: not an undo step, for the reason the limiter is not -- the
1733 /// history snapshots hold the lane list and subtitles are not on it
1734 /// ([`Project::subtitles`]). The inverse is putting the file's tracks back
1735 /// on -- [`crate::PlaybackSession::import_subtitles`], the panel's own
1736 /// door, which reads the subtitles of a file and nothing else -- and not a
1737 /// ctrl+z; the upgrade path is the same one the limiter has: a history
1738 /// entry holding the project's own settings beside the lanes. The history
1739 /// is *cleared* rather than kept, as a source removal clears it: the
1740 /// snapshots hold the indexes as they were before the reindex, so an undo
1741 /// into one would put every placement past `idx` on the wrong track.
1742 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1743 if idx >= self.subtitles.len() {
1744 return Err(format!("there is no subtitle track {idx} to remove").into());
1745 }
1746 let placed: Vec<String> = handles(&self.lanes)
1747 .into_iter()
1748 .zip(&self.lanes)
1749 .flat_map(|(lane, data)| {
1750 data.subs
1751 .iter()
1752 .filter(move |s| s.track == idx)
1753 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
1754 })
1755 .take(3)
1756 .collect();
1757 if !placed.is_empty() {
1758 return Err(format!(
1759 "{} is on the timeline ({}): delete those clips first",
1760 self.track_name(idx),
1761 placed.join(", ")
1762 )
1763 .into());
1764 }
1765 self.subtitles.remove(idx);
1766 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
1767 if s.track > idx {
1768 s.track -= 1;
1769 }
1770 }
1771 self.history.clear();
1772 Ok(())
1773 }
1774
1775 /// What a refusal calls a palette row: the name the panel shows, and the
1776 /// index alone for a row that is not there.
1777 fn track_name(&self, track: usize) -> String {
1778 self.subtitles
1779 .get(track)
1780 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
1781 }
1782
1783 /// The subtitle lanes in display order -- what a front-end lays out and
1784 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
1785 /// [`audio_lanes`](Project::audio_lanes).
1786 pub fn subtitle_lanes(&self) -> Vec<Lane> {
1787 self.lanes()
1788 .into_iter()
1789 .filter(|l| l.kind == LaneKind::Subtitle)
1790 .collect()
1791 }
1792
1793 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
1794 /// for a subtitle track, and empty for every other lane and for one that is
1795 /// not there.
1796 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
1797 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
1798 }
1799
1800 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
1801 /// twin, with one deliberate difference: it **refuses** an overlap instead
1802 /// of overwriting what it lands on.
1803 ///
1804 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
1805 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
1806 /// carries is a *window of a track* and where the hand let go, and the
1807 /// second of those is the argument. So a caller builds the placement once
1808 /// (from the palette row it dragged) and drops it at as many frames as it
1809 /// likes without rewriting the field each time.
1810 ///
1811 /// A picture placed over a picture hides it and the hidden one is still
1812 /// there to drag back out; two captions in one frame are two lines nobody
1813 /// asked to stack, and the words that lost are gone from the screen with
1814 /// nothing to show for it. So the refusal names the placement in the way,
1815 /// and the caller picks another frame or another lane -- which is what a
1816 /// second subtitle lane is for.
1817 ///
1818 /// One undo step on success, and none on any refusal: an empty window or an
1819 /// empty span, a track the palette does not have
1820 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
1821 /// subtitle lane, a span that would run past the last frame there is, and
1822 /// the overlap above.
1823 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
1824 if lane.kind != LaneKind::Subtitle {
1825 return Err(format!(
1826 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
1827 the others",
1828 lane.label()
1829 )
1830 .into());
1831 }
1832 let Some(i) = self.index(lane) else {
1833 return Err(format!("there is no {} to place on", lane.label()).into());
1834 };
1835 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
1836 return Err(format!(
1837 "that placement is empty: {} frames of [{}, {})",
1838 sub.frames, sub.in_us, sub.out_us
1839 )
1840 .into());
1841 }
1842 if sub.track >= self.subtitles.len() {
1843 return Err(format!(
1844 "it names subtitle track {} of {}",
1845 sub.track,
1846 self.subtitles.len()
1847 )
1848 .into());
1849 }
1850 // The placement belongs to no group, for [`place`]'s reason: a caption
1851 // dragged out of the palette arrives alone, and grouping it with what
1852 // is under it is a hand's decision ([`Project::group_all`]).
1853 let sub = SubClip {
1854 start: at,
1855 link: None,
1856 ..sub
1857 };
1858 if at.checked_add(sub.frames).is_none() {
1859 return Err(format!("a placement at frame {at} runs past the last frame there is").into());
1860 }
1861 if let Some(other) = self.lanes[i]
1862 .subs
1863 .iter()
1864 .find(|o| o.end() > sub.start && o.start < sub.end())
1865 {
1866 return Err(format!(
1867 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
1868 on another subtitle track",
1869 lane.label(),
1870 other.start,
1871 other.start,
1872 other.end()
1873 )
1874 .into());
1875 }
1876 self.snapshot();
1877 let subs = &mut self.lanes[i].subs;
1878 let idx = subs.partition_point(|o| o.start < sub.start);
1879 subs.insert(idx, sub);
1880 debug_assert!(subs_sorted_disjoint(subs));
1881 Ok(())
1882 }
1883
1884 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
1885 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
1886 /// refused an overlap where that one clamps to it, for
1887 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
1888 /// still and no picture under it that a landing would hide, so "as far as
1889 /// it goes" would silently be a frame nobody named.
1890 ///
1891 /// A caption *in* a group drags the group: one delta for every member --
1892 /// its clips and its other captions -- clamped to the room each of them
1893 /// has, exactly as a clip's drag always has. That is the point of putting
1894 /// a caption in a group: the words go where the picture goes.
1895 ///
1896 /// The window travels untouched: a caption dragged later says the same
1897 /// words later, exactly as a clip dragged later plays the same pictures
1898 /// later.
1899 ///
1900 /// One undo step on success; nothing changed and no step on a refusal --
1901 /// an index that is not there, a lane that is not a subtitle lane or is not
1902 /// there, and (for a caption in no group) an overlap. A drop that changes
1903 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
1904 /// up and put it back has done nothing wrong, and a front-end showing every
1905 /// `Err` would say so.
1906 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
1907 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
1908 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
1909 };
1910 if to.kind != LaneKind::Subtitle {
1911 return Err(format!(
1912 "{} is not a subtitle track: a caption cannot play on it",
1913 to.label()
1914 )
1915 .into());
1916 }
1917 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
1918 return Err(format!("there is no {} to move onto", to.label()).into());
1919 };
1920 if (here, start) == (dest, sub.start) {
1921 // A pick-up-put-back: the drag ended where it began, which is not a
1922 // mistake to name -- `Ok`, and no undo step, because nothing
1923 // changed. A refusal here would toast a hand that did nothing.
1924 return Ok(());
1925 }
1926 if start.checked_add(sub.frames).is_none() {
1927 return Err(
1928 format!("a placement at frame {start} runs past the last frame there is").into(),
1929 );
1930 }
1931 // A grouped caption carries its group, clamped to the room the whole
1932 // group has rather than refused ([`Project::move_room]) -- one drag, one
1933 // delta, one undo step.
1934 let members = self.group_of(from, idx).expect("the subtitle was found");
1935 if !members.alone() {
1936 if members
1937 .subs
1938 .iter()
1939 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
1940 {
1941 return Err(format!(
1942 "a group is one caption per track: {} already carries this group",
1943 to.label()
1944 )
1945 .into());
1946 }
1947 let want = i64::from(start) - i64::from(sub.start);
1948 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start))) else {
1949 return Err(format!(
1950 "another placement already covers those frames on {}",
1951 to.label()
1952 )
1953 .into());
1954 };
1955 let delta = want.clamp(lo, hi);
1956 self.snapshot();
1957 for &(l, i) in &members.clips {
1958 let c = &mut self.lanes[l].clips[i];
1959 c.start = (i64::from(c.start) + delta) as u32;
1960 }
1961 for &(l, i) in &members.subs {
1962 let s = &mut self.lanes[l].subs[i];
1963 s.start = (i64::from(s.start) + delta) as u32;
1964 }
1965 let moved = self.lanes[here].subs.remove(idx);
1966 let subs = &mut self.lanes[dest].subs;
1967 let at = subs.partition_point(|o| o.start < moved.start);
1968 subs.insert(at, moved);
1969 debug_assert!(subs_sorted_disjoint(subs));
1970 debug_assert!(members
1971 .clips
1972 .iter()
1973 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips)));
1974 return Ok(());
1975 }
1976 let moved = SubClip { start, ..sub };
1977 if let Some(other) = self.lanes[dest]
1978 .subs
1979 .iter()
1980 .enumerate()
1981 .find(|&(j, o)| {
1982 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
1983 })
1984 .map(|(_, o)| *o)
1985 {
1986 return Err(format!(
1987 "the {} subtitle at frame {} already covers [{}, {})",
1988 to.label(),
1989 other.start,
1990 other.start,
1991 other.end()
1992 )
1993 .into());
1994 }
1995 self.snapshot();
1996 self.lanes[here].subs.remove(idx);
1997 let subs = &mut self.lanes[dest].subs;
1998 let at = subs.partition_point(|o| o.start < moved.start);
1999 subs.insert(at, moved);
2000 debug_assert!(subs_sorted_disjoint(subs));
2001 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
2002 Ok(())
2003 }
2004
2005 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
2006 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
2007 /// pulling an edge past what is legal means "as far as it goes".
2008 ///
2009 /// The window follows the edge, in the seconds the frames are worth at
2010 /// `fps`: a head pulled in starts the caption later *in its track* (the
2011 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
2012 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
2013 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
2014 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
2015 /// needed here and nowhere else in this file, because a trim is the only
2016 /// edit that changes a *duration*.
2017 ///
2018 /// The walls: one frame always survives, an edge never crosses the
2019 /// neighbouring subtitle on its own lane, a head never walks back past the
2020 /// track's own start (`in_us` of 0), and a tail never runs past the last
2021 /// cue the track has -- which is the source length a media trim needs a
2022 /// caller's table for, and which this one can simply read.
2023 ///
2024 /// `Err`, with nothing changed and no undo step, for an index that is not
2025 /// there and an unusable `fps`. An edge that ends up where it already was
2026 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
2027 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
2028 /// reason: a drag that stops at a wall is not a mistake to report.
2029 pub fn trim_sub(
2030 &mut self,
2031 lane: Lane,
2032 idx: usize,
2033 edge: Edge,
2034 to: u32,
2035 fps: f64,
2036 ) -> crate::Result<()> {
2037 if !(fps.is_finite() && fps > 0.0) {
2038 return Err(format!("{fps} is not a frame rate to trim against").into());
2039 }
2040 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
2041 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2042 };
2043 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
2044 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
2045 };
2046 let to = to.clamp(lo, hi);
2047 let at = match edge {
2048 Edge::Start => sub.start,
2049 Edge::End => sub.end(),
2050 };
2051 if to == at {
2052 // The edge is where it was asked to go -- either the hand did not
2053 // move it, or the clamp above stopped it at a wall it was already
2054 // standing against. Both are a drag that changed nothing: `Ok`, no
2055 // undo step, and no toast for a box that simply stopped moving.
2056 return Ok(());
2057 }
2058 self.snapshot();
2059 let members = self.group_of(lane, idx).expect("the subtitle was found");
2060 let i = self.index(lane).expect("the subtitle was found on it");
2061 let s = &mut self.lanes[i].subs[idx];
2062 match edge {
2063 // The words that stay are the words that were there, so the window
2064 // moves with the head -- a trim, not a slip.
2065 Edge::Start => {
2066 // Clamped to a window that is still a window: the walls above
2067 // are frames and the rounding between the two clocks is not
2068 // exact, and neither is a caller's hand-built placement.
2069 s.in_us = (s.in_us + us_of(i64::from(to) - i64::from(s.start), fps))
2070 .clamp(0, s.out_us - 1);
2071 s.frames = s.end() - to;
2072 s.start = to;
2073 }
2074 Edge::End => {
2075 s.out_us =
2076 (s.out_us + us_of(i64::from(to) - i64::from(s.end()), fps)).max(s.in_us + 1);
2077 s.frames = to - s.start;
2078 }
2079 }
2080 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
2081 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
2082 // A caption in a group drags its group's edge with it, exactly as a
2083 // clip's trim does: one delta, each member clamped to its own room.
2084 // No source table to grow by, which only tightens how far a member may
2085 // follow -- never whether it may.
2086 self.follow_group(&members, &(i, idx), edge, i64::from(to) - i64::from(at), &[]);
2087 Ok(())
2088 }
2089
2090 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2091 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
2092 /// drawing the box during a drag asks. `None` for an index that is not
2093 /// there.
2094 pub fn trim_sub_room(
2095 &self,
2096 lane: Lane,
2097 idx: usize,
2098 edge: Edge,
2099 fps: f64,
2100 ) -> Option<(u32, u32)> {
2101 let subs = self.sub_lane(lane);
2102 let s = *subs.get(idx)?;
2103 // How many timeline frames a stretch of the track is worth, which is
2104 // what turns its two walls -- its own start, and its last cue -- into
2105 // frames. A rate that is not a rate leaves the window where it is.
2106 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
2107 true => ((us as f64) * fps / 1e6).round().max(0.0).min(f64::from(u32::MAX)) as u32,
2108 false => 0,
2109 };
2110 Some(match edge {
2111 Edge::Start => (
2112 s.start
2113 .saturating_sub(frames_of(s.in_us))
2114 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
2115 s.end() - 1,
2116 ),
2117 Edge::End => {
2118 // Out to the end of the track it reads, and never over the
2119 // subtitle behind it. A track the palette no longer has (or one
2120 // with no cues at all) may not grow, exactly as a source with no
2121 // entry in a media trim's table may not.
2122 let track_end = self
2123 .subtitles
2124 .get(s.track)
2125 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
2126 .unwrap_or(s.out_us);
2127 (
2128 s.start + 1,
2129 s.start
2130 .saturating_add(frames_of(track_end - s.in_us).max(1))
2131 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
2132 )
2133 }
2134 })
2135 }
2136
2137 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
2138 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
2139 /// `false` for an index that is not there (which a lane that is not a
2140 /// subtitle lane always is).
2141 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2142 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
2143 return false;
2144 };
2145 self.snapshot();
2146 self.lanes[i].subs.remove(idx);
2147 true
2148 }
2149
2150 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
2151 /// window of its track, clipped to that window and shifted to where the
2152 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
2153 /// carried through the picture's spans -- this is its twin for a track that
2154 /// is placed on a lane of its own, and it is what a preview draws and what
2155 /// an export of the lane would write.
2156 ///
2157 /// Cut, not stretched: a cue half inside the window keeps the half that is
2158 /// inside, and a cue wholly outside it is gone -- the same rule the media
2159 /// spans follow. `fps` is the timeline's rate, needed here because a
2160 /// placement's *position* is in frames while its words are in microseconds.
2161 ///
2162 /// Pure and cheap enough to ask per repaint (a walk of the placements and
2163 /// of their cues, no file opened), which is how a front-end asks it.
2164 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
2165 if !(fps.is_finite() && fps > 0.0) {
2166 return Vec::new();
2167 }
2168 let mut out = Vec::new();
2169 for s in self.sub_lane(lane) {
2170 let Some(track) = self.subtitles.get(s.track) else {
2171 // A placement whose track was taken off the palette
2172 // ([`Project::remove_subtitles`]) shows nothing rather than
2173 // showing another track's words.
2174 continue;
2175 };
2176 // Where the placement's own first microsecond lands on the
2177 // timeline, and how many microseconds of timeline one microsecond
2178 // of the window is worth: the placement's own proportion, which a
2179 // group's re-rate changes (the frames compress, the window does
2180 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
2181 // every cue lands where it always did; at 2x the words cross the
2182 // screen in half the time, cue for cue.
2183 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
2184 let onto = |t: i64| {
2185 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
2186 };
2187 for cue in &track.cues {
2188 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
2189 if b <= a {
2190 continue; // wholly outside the window this placement keeps
2191 }
2192 out.push(SubtitleCue {
2193 start_us: onto(a),
2194 end_us: onto(b),
2195 text: cue.text.clone(),
2196 image: cue.image.clone(),
2197 });
2198 }
2199 }
2200 // The placements come in timeline order, but two lanes' worth (or a
2201 // track whose cues a window reordered) do not.
2202 out.sort_by_key(|cue| cue.start_us);
2203 out
2204 }
2205
2206 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
2207 /// lanes is multiplied by on its way into the mix: the same lanes in the
2208 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
2209 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
2210 /// the bit-exact path.
2211 pub fn audio_gains(&self) -> Vec<f32> {
2212 self.audio_lanes()
2213 .into_iter()
2214 .map(|lane| db_to_linear(self.lane_gain_db(lane)))
2215 .collect()
2216 }
2217
2218 /// The master limiter the mix is summed through. A project setting, not a
2219 /// clip's and not a lane's: there is one mix.
2220 pub fn limiter(&self) -> Limiter {
2221 self.limiter
2222 }
2223
2224 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
2225 /// for a setting already in force.
2226 ///
2227 /// corner-cut: not an undo step, for the reason the project resolution is not
2228 /// one ([`crate::PlaybackSession::set_resolution`]) -- it is not in the
2229 /// lane list the history snapshots. Upgrade path is a history entry that
2230 /// holds the mix settings beside the lanes.
2231 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
2232 let limiter = limiter.with_ceiling(limiter.ceiling_db);
2233 if self.limiter == limiter {
2234 return false;
2235 }
2236 self.limiter = limiter;
2237 true
2238 }
2239
2240 /// What the clip at `idx` of `lane` plays through, or `None` for one that
2241 /// plays flat (and for an index that is not there) -- what a feeder and an
2242 /// export ask before they build an [`crate::eq::EqState`].
2243 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2244 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
2245 }
2246
2247 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
2248 /// take them off. One undo step, like every other edit. `false` -- and no
2249 /// history -- for an index that is not there and for params holding a value
2250 /// that is not finite, which is the one thing the file format could not
2251 /// write and read back.
2252 ///
2253 /// Settings equal to ones already in the table share their entry, so a
2254 /// project that puts the same curve on twenty clips writes it once.
2255 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2256 if idx >= self.lane(lane).len() {
2257 return false;
2258 }
2259 let slot = match params {
2260 None => None,
2261 Some(params) => {
2262 if !finite(&params) {
2263 return false;
2264 }
2265 Some(match self.eq.iter().position(|p| *p == params) {
2266 Some(at) => at as u16,
2267 // corner-cut: the table is append-only within a session (see
2268 // the module docs) and `Clip::eq` is a u16, so the 65535th
2269 // *distinct* setting of one session is refused rather than
2270 // silently aliased. Upgrade path if a UI ever drags a slider
2271 // that far: widen `Clip::eq` to u32 (Clip has the room) or
2272 // snapshot the table into the history and compact it here.
2273 None if self.eq.len() >= usize::from(u16::MAX) => return false,
2274 None => {
2275 self.eq.push(params);
2276 (self.eq.len() - 1) as u16
2277 }
2278 })
2279 }
2280 };
2281 self.snapshot();
2282 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
2283 true
2284 }
2285
2286 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2287 /// ungraded (and for an index that is not there) -- what the renderer and
2288 /// the export ask before they call [`crate::color::apply_yuv`].
2289 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2290 self.color
2291 .get(usize::from(self.lane(lane).get(idx)?.color?))
2292 }
2293
2294 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
2295 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
2296 /// (and no history) for an index that is not there or a value that is not
2297 /// finite, and equal settings share a table entry.
2298 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2299 self.write_color(lane, idx, params, true)
2300 }
2301
2302 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
2303 /// one pointer drag, whose first write (a plain `set_color`) already took the
2304 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
2305 /// not one per pixel -- and undoing it lands where the hand picked it up.
2306 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2307 self.write_color(lane, idx, params, false)
2308 }
2309
2310 fn write_color(
2311 &mut self,
2312 lane: Lane,
2313 idx: usize,
2314 params: Option<ColorParams>,
2315 snapshot: bool,
2316 ) -> bool {
2317 if idx >= self.lane(lane).len() {
2318 return false;
2319 }
2320 let slot = match params {
2321 None => None,
2322 Some(params) => {
2323 if !color_finite(&params) {
2324 return false;
2325 }
2326 Some(match self.color.iter().position(|p| *p == params) {
2327 Some(at) => at as u16,
2328 // corner-cut: the 65535th *distinct* grade of one session is
2329 // refused rather than silently aliased, exactly as `set_eq`
2330 // refuses the 65535th curve; same upgrade path.
2331 None if self.color.len() >= usize::from(u16::MAX) => return false,
2332 None => {
2333 self.color.push(params);
2334 (self.color.len() - 1) as u16
2335 }
2336 })
2337 }
2338 };
2339 if snapshot {
2340 self.snapshot();
2341 }
2342 self.lane_mut(lane).expect("checked above")[idx].color = slot;
2343 true
2344 }
2345
2346 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
2347 /// policy's own placement (and for an index that is not there) -- what the
2348 /// renderer and the export ask before they place its picture.
2349 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2350 self.transform
2351 .get(usize::from(self.lane(lane).get(idx)?.transform?))
2352 }
2353
2354 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
2355 /// step, `false` (and no history) for an index that is not there or a
2356 /// value that is not finite, and equal settings share a table entry.
2357 pub fn set_transform(&mut self, lane: Lane, idx: usize, params: Option<TransformParams>) -> bool {
2358 self.write_transform(lane, idx, params, true)
2359 }
2360
2361 /// [`set_transform`](Self::set_transform) without the undo step, for
2362 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
2363 /// one drag on a position/scale/rotate/crop control are one undo, not one
2364 /// per pixel.
2365 pub fn set_transform_live(
2366 &mut self,
2367 lane: Lane,
2368 idx: usize,
2369 params: Option<TransformParams>,
2370 ) -> bool {
2371 self.write_transform(lane, idx, params, false)
2372 }
2373
2374 fn write_transform(
2375 &mut self,
2376 lane: Lane,
2377 idx: usize,
2378 params: Option<TransformParams>,
2379 snapshot: bool,
2380 ) -> bool {
2381 if idx >= self.lane(lane).len() {
2382 return false;
2383 }
2384 let slot = match params {
2385 None => None,
2386 Some(params) => {
2387 if !transform_finite(&params) {
2388 return false;
2389 }
2390 Some(match self.transform.iter().position(|p| *p == params) {
2391 Some(at) => at as u16,
2392 // corner-cut: the 65535th *distinct* transform of one
2393 // session is refused rather than silently aliased,
2394 // exactly as `write_color` refuses the 65535th grade;
2395 // same upgrade path.
2396 None if self.transform.len() >= usize::from(u16::MAX) => return false,
2397 None => {
2398 self.transform.push(params);
2399 (self.transform.len() - 1) as u16
2400 }
2401 })
2402 }
2403 };
2404 if snapshot {
2405 self.snapshot();
2406 }
2407 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
2408 true
2409 }
2410
2411 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
2412 /// index that is not there, which is what every clip starts at anyway.
2413 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2414 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
2415 }
2416
2417 /// Sets it, for the clip **and its whole group**: a link is one span on
2418 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
2419 /// from its sound would be a group no save could load. One snapshot, so the
2420 /// group's change is one [`Project::undo`].
2421 ///
2422 /// The source range is untouched -- a speed says how many timeline frames
2423 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
2424 /// split still address the file afterwards.
2425 ///
2426 /// Refused, changing nothing and costing no undo step, when the clip would
2427 /// grow into the one after it on its own lane: slowing a clip down makes it
2428 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
2429 /// the way -- by lane and timeline frame -- because "it did not fit" is not
2430 /// something a user can go and fix. Also for an index that is not there.
2431 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2432 self.write_speed(lane, idx, speed, true)
2433 }
2434
2435 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
2436 /// one pointer drag, whose first write (a plain `set_speed`) already took the
2437 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
2438 /// not one per rate it passed through -- exactly as
2439 /// [`set_color_live`](Self::set_color_live) is for a slider.
2440 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2441 self.write_speed(lane, idx, speed, false)
2442 }
2443
2444 fn write_speed(
2445 &mut self,
2446 lane: Lane,
2447 idx: usize,
2448 speed: Speed,
2449 snapshot: bool,
2450 ) -> crate::Result<()> {
2451 let Some(members) = self.group_of(lane, idx) else {
2452 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2453 };
2454 let labels = handles(&self.lanes);
2455 // The clip the hand is holding is the group's clock: everything else
2456 // in the group, caption members included, re-times by the ratio its new
2457 // rate gives its own frames. The clips take the rate itself; a caption
2458 // has none, so it takes the *ratio* -- its span on the timeline
2459 // compresses or stretches about the held clip's head, while the words
2460 // it reads keep their own timing ([`write_sub_edge`]'s law: the
2461 // timeline moves, the track does not).
2462 let Some(held) = self.lane(lane).get(idx).copied() else {
2463 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
2464 };
2465 // The same per-member piece `speeded_playhead` builds for this op,
2466 // asked here instead of read there -- a caption's length comes from
2467 // the map's own ends (`end - start`), never `round(len * ratio)`
2468 // separately, which is what let the two answers drift apart by a
2469 // frame.
2470 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2471 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2472 let retimed = |s: SubClip| {
2473 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
2474 let start = map.apply(s.start);
2475 let end = map.apply(s.end()).max(start.saturating_add(1));
2476 SubClip { start, frames: end - start, ..s }
2477 };
2478 for &(l, i) in &members.clips {
2479 let clips = &self.lanes[l].clips;
2480 let mut moved = clips[i];
2481 moved.speed = speed;
2482 if let Some(next) = clips.get(i + 1)
2483 && moved.end() > next.start
2484 {
2485 let name = labels[l].label();
2486 return Err(format!(
2487 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
2488 move it along, or trim this one first",
2489 moved.end(),
2490 next.start
2491 )
2492 .into());
2493 }
2494 }
2495 // ...and the captions, against their own lanes' captions: a stretch
2496 // that runs one into its neighbour is refused for the clip arm's
2497 // reason -- a lane may not overlap itself -- and by name like it.
2498 let subs: Vec<(usize, usize, SubClip)> = members
2499 .subs
2500 .iter()
2501 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
2502 .collect();
2503 for &(l, i, moved) in &subs {
2504 for (j, other) in self.lanes[l].subs.iter().enumerate() {
2505 if j != i && moved.start < other.end() && other.start < moved.end() {
2506 return Err(format!(
2507 "at {speed} the {} caption at frame {} would run to frame {} and the next \
2508 starts at {}: move it along, or trim this one first",
2509 labels[l].label(),
2510 self.lanes[l].subs[i].start,
2511 moved.end(),
2512 other.start
2513 )
2514 .into());
2515 }
2516 }
2517 }
2518 if snapshot {
2519 self.snapshot();
2520 }
2521 for (l, i) in members.clips {
2522 self.lanes[l].clips[i].speed = speed;
2523 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
2524 }
2525 for (l, i, moved) in subs {
2526 self.lanes[l].subs[i] = moved;
2527 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
2528 }
2529 debug_assert!(links_are_consistent(&self.lanes).is_ok());
2530 Ok(())
2531 }
2532
2533 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
2534 /// playhead standing at `at` -- read off the geometry **before** the
2535 /// write, because the old ends are gone after it. The question a card
2536 /// asks as its bar moves: the picture under the cursor has to stay the
2537 /// picture under the cursor, or the scene changes with the rate.
2538 ///
2539 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
2540 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
2541 /// a clip member keeps its own start and re-fits its length at the new
2542 /// rate -- its **old** rate against the new one, which is what the bar's
2543 /// live samples ask about as much as a first press does; a caption
2544 /// member scales about the held clip's start by the held clip's own
2545 /// proportion; and a playhead outside every member's old extent stays
2546 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
2547 /// (or the room a stretch takes) absorbs the difference, not the
2548 /// playhead. `None` for an index that is not there.
2549 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
2550 let members = self.group_of(lane, idx)?;
2551 let held = self.lane(lane).get(idx).copied()?;
2552 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
2553 for &(l, i) in members.clips.iter().chain(&members.subs) {
2554 let (span, map) = match self
2555 .lanes[l]
2556 .clips
2557 .get(i)
2558 .filter(|_| members.clips.contains(&(l, i)))
2559 {
2560 // The clip's own span, re-fitted at its own old rate: one
2561 // piece of the map, anchored where the clip itself is. The
2562 // new length is the same *source* frames at the new rate --
2563 // len divided by it, never multiplied.
2564 Some(c) => (
2565 (c.start, c.start + c.frames()),
2566 TimelineMap::piece(
2567 (c.start, c.start + c.frames()),
2568 (
2569 c.start,
2570 c.start + (c.len() as f64 / new).round() as u32,
2571 ),
2572 ),
2573 ),
2574 // The caption's span, scaled about the held clip's head by
2575 // the held clip's proportion -- the offset the group keeps.
2576 None => {
2577 let s = self.lanes[l].subs.get(i)?;
2578 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
2579 (
2580 (s.start, s.end()),
2581 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
2582 )
2583 }
2584 };
2585 // The piece owns only its own old span: outside it the playhead
2586 // is another member's question, or nobody's.
2587 if (span.0..span.1).contains(&at) {
2588 return Some(map.apply(at));
2589 }
2590 }
2591 Some(at)
2592 }
2593
2594 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
2595 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
2596 /// every clip starts at anyway.
2597 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
2598 self.lane(lane)
2599 .get(idx)
2600 .map_or(FitPolicy::default(), |c| c.fit)
2601 }
2602
2603 /// Sets it. One undo step like every other edit, and `false` (with no
2604 /// history) for an index that is not there. Unlike an eq or a grade there is
2605 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
2606 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
2607 if idx >= self.lane(lane).len() {
2608 return false;
2609 }
2610 self.snapshot();
2611 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
2612 true
2613 }
2614
2615 /// Timeline frames of ramp-up from silence at the start of the clip at
2616 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
2617 /// that has none.
2618 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
2619 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
2620 }
2621
2622 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
2623 /// can shrink a clip's audible middle to nothing but never ask for more
2624 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
2625 /// and `false` (no history) for an index that is not there.
2626 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2627 if idx >= self.lane(lane).len() {
2628 return false;
2629 }
2630 self.snapshot();
2631 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2632 clip.fade_in = frames.min(clip.frames());
2633 true
2634 }
2635
2636 /// Timeline frames of ramp-down to silence at the end of the clip at
2637 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
2638 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
2639 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
2640 }
2641
2642 /// Sets it. Same promises as [`Project::set_fade_in`].
2643 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2644 if idx >= self.lane(lane).len() {
2645 return false;
2646 }
2647 self.snapshot();
2648 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
2649 clip.fade_out = frames.min(clip.frames());
2650 true
2651 }
2652
2653 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
2654 /// into its successor, at its own end. `0` for an index that is not
2655 /// there, same as a clip that has none.
2656 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
2657 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
2658 }
2659
2660 /// Sets it, clamped to the clip's own length and to how many frames its
2661 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
2662 /// visible middle to nothing but never ask for more than the two clips
2663 /// between them have. `false` -- no history -- unless `lane` is video,
2664 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
2665 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
2666 /// them. One undo step like [`Project::set_fade_out`].
2667 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2668 if lane.kind != LaneKind::Video {
2669 return false;
2670 }
2671 let clips = self.lane(lane);
2672 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2673 return false;
2674 };
2675 if a.end() != b.start {
2676 return false;
2677 }
2678 let cap = a.frames().min(b.frames());
2679 self.snapshot();
2680 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
2681 true
2682 }
2683
2684 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
2685 /// after it, over `frames` timeline frames: sets `idx`'s
2686 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
2687 /// each clamped to its own clip's length. `false` -- no history -- unless
2688 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
2689 /// adjacent: the second's [`Clip::start`] is exactly the first's
2690 /// [`Clip::end`], no gap between them.
2691 ///
2692 /// This is the whole mechanism, not a stand-in for one: a *real*
2693 /// cross-fade -- both takes heard at once, blending -- is what two clips
2694 /// **overlapping** on separate lanes already get for free from the
2695 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
2696 /// This call only shapes the edges of two clips already sitting
2697 /// end-to-end on *one* lane, so the join between them fades like one did.
2698 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
2699 if lane.kind != LaneKind::Audio {
2700 return false;
2701 }
2702 let clips = self.lane(lane);
2703 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
2704 return false;
2705 };
2706 if a.end() != b.start {
2707 return false;
2708 }
2709 self.snapshot();
2710 let clips = self.lane_mut(lane).expect("checked above");
2711 clips[idx].fade_out = frames.min(clips[idx].frames());
2712 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
2713 true
2714 }
2715
2716 /// Every frame number on every lane rewritten onto a timeline counted at
2717 /// another rate: `k` is old timeline frames per new one, `counts` is how
2718 /// long each source is on the *new* timeline (indexed as
2719 /// [`Project::sources`] is), and the edit survives as the same seconds of
2720 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
2721 /// the edit list, and the only thing that touches the frame numbers without
2722 /// being an edit anyone made.
2723 ///
2724 /// Every position -- a clip's start and its end alike -- goes through the
2725 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
2726 /// stays a gap, and a take's picture and its sound land on the same frame on
2727 /// their two lanes: no lane can drift against another. A clip is then only
2728 /// ever made to *fit* the room its own start and end mapped to, never to
2729 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
2730 /// below is the backstop for the one case that could: a slow clip so short
2731 /// that no source range fits its new room at all).
2732 ///
2733 /// corner-cut: not exact both ways. Each rate change re-rounds every boundary
2734 /// onto the new grid, so a rate picked, unpicked and picked again is within
2735 /// a frame of where it started rather than back at it. Upgrade path is
2736 /// keeping the edit list at one reference rate and conforming on the way
2737 /// out, which every frame number in this module would then be measured in.
2738 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
2739 for lane in &mut self.lanes {
2740 let mut cursor = 0;
2741 for clip in &mut lane.clips {
2742 let start = k.timeline_at(clip.start).max(cursor);
2743 // The room its own end mapped to -- never zero, since a clip is
2744 // never empty even on a grid too coarse to hold it.
2745 let room = k.timeline_at(clip.end()).saturating_sub(start).max(1);
2746 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
2747 // Its footage, held inside the file's new length: a clip whose
2748 // out-point was the last frame of its source must not come out
2749 // of this naming a frame past the end -- that is a project that
2750 // would not open again ([`crate::PlaybackSession::open_project`]
2751 // refuses one by name).
2752 let in_frame = k.timeline_at(clip.in_frame).min(count - 1);
2753 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
2754 clip.start = start;
2755 clip.in_frame = in_frame;
2756 clip.out_frame = in_frame + len;
2757 cursor = clip.end();
2758 }
2759 // A subtitle's *window* is in microseconds and a rate change moves
2760 // no seconds, so only where it sits is remapped -- through the same
2761 // [`Rate::timeline_at`] every clip boundary goes through, so a
2762 // caption still starts on the frame its picture does.
2763 let mut cursor = 0;
2764 for sub in &mut lane.subs {
2765 let start = k.timeline_at(sub.start).max(cursor);
2766 sub.frames = k.timeline_at(sub.end()).saturating_sub(start).max(1);
2767 sub.start = start;
2768 cursor = sub.end();
2769 }
2770 }
2771 }
2772
2773 /// Length of the timeline in frames: where the *last* lane runs out. A lane
2774 /// that ends early is a trailing gap in that lane, not a shorter timeline.
2775 ///
2776 /// A subtitle lane counts like any other: a caption placed past the last
2777 /// picture holds the timeline open under it, exactly as an `A2` running
2778 /// past `V1` does, rather than being silently clipped away by the length
2779 /// ([`crate::export::timeline_cues`] clips cues to this).
2780 pub fn timeline_frames(&self) -> u32 {
2781 self.lanes
2782 .iter()
2783 .filter_map(|l| match l.kind {
2784 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
2785 _ => l.clips.last().map(Clip::end),
2786 })
2787 .max()
2788 .unwrap_or(0)
2789 }
2790
2791 /// The same, counting the *media* alone: where the last picture or sound
2792 /// runs out, with the captions over them ignored.
2793 ///
2794 /// What an export actually writes ends here -- the picture loop walks the
2795 /// composite spans and the file stops with them -- so this is the length a
2796 /// cue has to be inside of to be written at all (what
2797 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
2798 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
2799 /// thing is a picture or a sound, which is every timeline that has no
2800 /// caption hanging past the end of both.
2801 pub fn media_frames(&self) -> u32 {
2802 self.lanes
2803 .iter()
2804 .filter(|l| l.kind != LaneKind::Subtitle)
2805 .filter_map(|l| l.clips.last().map(Clip::end))
2806 .max()
2807 .unwrap_or(0)
2808 }
2809
2810 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
2811 /// to lay clips out. Gaps show up as the holes between consecutive entries.
2812 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
2813 self.lane_spans(Lane::V1)
2814 }
2815
2816 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
2817 // Timeline frames, not source ones: a box on a lane is as wide as the
2818 // clip is long *there*, which a speed halves or quadruples.
2819 self.lane(lane)
2820 .iter()
2821 .map(|c| (c.start, c.frames()))
2822 .collect()
2823 }
2824
2825 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
2826 /// and past the end -- [`Project::span_at`] is the version that tells those
2827 /// two apart.
2828 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
2829 let clips = self.lane(lane);
2830 let idx = at(clips, timeline_frame)?;
2831 Some((idx, source_frame(&clips[idx], timeline_frame)))
2832 }
2833
2834 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
2835 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
2836 self.map(Lane::V1, timeline_frame)
2837 }
2838
2839 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
2840 /// it, or the gap running to the next clip (or to the end of the timeline,
2841 /// which is where a lane shorter than its neighbour keeps showing black).
2842 /// `None` at or past the end of the timeline, which is the only "nothing
2843 /// left" there is.
2844 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
2845 let total = self.timeline_frames();
2846 if timeline_frame >= total {
2847 return None;
2848 }
2849 let clips = self.lane(lane);
2850 Some(match at(clips, timeline_frame) {
2851 Some(idx) => Span {
2852 start: timeline_frame,
2853 len: clips[idx].end() - timeline_frame,
2854 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2855 speed: clips[idx].speed,
2856 },
2857 None => Span {
2858 start: timeline_frame,
2859 speed: Speed::NORMAL,
2860 // The next placement, or the end of the timeline: a gap is
2861 // bounded by what comes after it, never by its own bookkeeping.
2862 len: clips
2863 .iter()
2864 .find(|c| c.start > timeline_frame)
2865 .map_or(total, |c| c.start)
2866 - timeline_frame,
2867 from: None,
2868 },
2869 })
2870 }
2871
2872 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
2873 /// gaps included -- the whole play list, which is what an export walks.
2874 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
2875 let mut out = Vec::new();
2876 let mut t = timeline_frame;
2877 while let Some(span) = self.span_at(lane, t) {
2878 t = span.end();
2879 out.push(span);
2880 }
2881 out
2882 }
2883
2884 /// What the *composite* shows from `timeline_frame` on -- the answer
2885 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
2886 /// video lane by one rule: **the topmost lane with a clip there wins**, and
2887 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
2888 /// (the usual overlay convention). A frame no video lane covers is a gap,
2889 /// which is black however many lanes are above or below it.
2890 ///
2891 /// No blending, so exactly one lane is visible at a time and the composite
2892 /// is itself a span list -- which is why one decoder plays it, the same one
2893 /// a single-lane timeline uses, rather than N running at once.
2894 ///
2895 /// The span is cut short wherever a *higher* lane's clip starts, because
2896 /// from that frame on a different lane wins; that is what makes walking
2897 /// [`composite_spans_from`](Project::composite_spans_from) correct.
2898 ///
2899 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
2900 /// lanes would then be visible in one frame and the caller needs a decoder
2901 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
2902 /// (this same walk, per lane) feeding N decoders.
2903 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
2904 let total = self.timeline_frames();
2905 if timeline_frame >= total {
2906 return None;
2907 }
2908 let video = self.video_lanes();
2909 // The last covering lane is the winner; only the lanes above it can
2910 // interrupt what it shows.
2911 let winner = video
2912 .iter()
2913 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
2914 let (from, speed, until) = match winner {
2915 Some(i) => {
2916 let clips = self.lane(video[i]);
2917 let idx = at(clips, timeline_frame).expect("just found above");
2918 (
2919 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
2920 clips[idx].speed,
2921 clips[idx].end(),
2922 )
2923 }
2924 // Nothing covers it: black until something above the floor starts.
2925 None => (None, Speed::NORMAL, total),
2926 };
2927 let takeover = video[winner.map_or(0, |i| i + 1)..]
2928 .iter()
2929 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
2930 .map(|c| c.start)
2931 .min();
2932 Some(Span {
2933 start: timeline_frame,
2934 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
2935 from,
2936 speed,
2937 })
2938 }
2939
2940 /// The video lanes in display order, topmost last -- the order the composite
2941 /// rule counts in.
2942 fn video_lanes(&self) -> Vec<Lane> {
2943 self.lanes()
2944 .into_iter()
2945 .filter(|l| l.kind == LaneKind::Video)
2946 .collect()
2947 }
2948
2949 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
2950 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
2951 /// index on that lane. `None` over a gap and past the end. What a front-end
2952 /// asks to act on "the clip on screen" without re-deriving the rule.
2953 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
2954 let video = self.video_lanes();
2955 let winner = video
2956 .iter()
2957 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
2958 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
2959 }
2960
2961 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
2962 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
2963 /// answers "the clip on screen"; this answers it per lane, which is what
2964 /// walking the lanes for something to select needs.
2965 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
2966 at(self.lane(lane), timeline_frame)
2967 }
2968
2969 /// How the composite is graded at `timeline_frame`, so the picture playback
2970 /// converts and the one an export encodes are graded from one answer.
2971 /// `None` over a gap (black is black) and for a clip nobody has graded,
2972 /// which is the byte-identical path everywhere.
2973 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
2974 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2975 self.color_of(lane, idx)
2976 }
2977
2978 /// [`composite_color_at`](Self::composite_color_at)'s twin for
2979 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
2980 /// policy's own placement.
2981 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
2982 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
2983 self.transform_of(lane, idx)
2984 }
2985
2986 /// How the composite meets the project canvas at `timeline_frame`, so the
2987 /// picture playback composes and the one an export encodes are placed from
2988 /// one answer. `Fit` over a gap, where black is already the canvas.
2989 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
2990 self.composite_clip_at(timeline_frame)
2991 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
2992 }
2993
2994 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
2995 /// viewer sees from `timeline_frame` to the end, in order. What an export
2996 /// encodes and what playback walks at a clip boundary.
2997 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
2998 let mut out = Vec::new();
2999 let mut t = timeline_frame;
3000 while let Some(span) = self.composite_span_at(t) {
3001 t = span.end();
3002 out.push(span);
3003 }
3004 out
3005 }
3006
3007 /// Split every lane at `timeline_frame`, so that frame becomes the first
3008 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
3009 /// (`false`, no change) when no lane has a clip to split there -- at a
3010 /// placement's own start, in a gap, and past the end -- all of which would
3011 /// produce an empty clip or nothing at all.
3012 ///
3013 /// Lanes' halves share an id only where they are the *same* span: the lanes
3014 /// are edited apart, so the clip being cut here may start (or end)
3015 /// somewhere else on another lane, and a group id whose clips disagree
3016 /// about their span is not one take (see [`links_are_consistent`], which
3017 /// refuses to load one).
3018 ///
3019 /// Metadata only: no mapping changes, in any lane.
3020 pub fn split(&mut self, timeline_frame: u32) -> bool {
3021 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
3022 }
3023
3024 /// [`split`](Project::split), with the snapshot optional and the lanes
3025 /// named: a batch that has already taken a snapshot
3026 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
3027 /// region and must still be one undo press, and a *scoped* batch must not
3028 /// cut a lane it was told to leave alone.
3029 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
3030 let cut: Vec<Option<Clip>> = self
3031 .lanes
3032 .iter()
3033 .enumerate()
3034 .map(|(i, l)| {
3035 on.contains(&i)
3036 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx]))
3037 .flatten()
3038 })
3039 .collect();
3040 // The same question on the subtitle lanes, in their own arithmetic: a
3041 // razor cuts the captions with the picture, and a frame where only a
3042 // caption can be cut is still a cut.
3043 let cut_subs: Vec<bool> = self
3044 .lanes
3045 .iter()
3046 .enumerate()
3047 .map(|(i, l)| {
3048 on.contains(&i) && l.subs.iter().any(|s| s.start < timeline_frame && timeline_frame < s.end())
3049 })
3050 .collect();
3051 // The links the captions carry, read before the room is opened below
3052 // -- `sub_open_room` takes the id off both halves, exactly as
3053 // `open_room` does for a clip, and the split hands the halves theirs
3054 // back afterwards.
3055 let sub_orig: Vec<Option<u32>> = self
3056 .lanes
3057 .iter()
3058 .zip(&cut_subs)
3059 .map(|(l, &cut)| {
3060 cut.then(|| {
3061 l.subs
3062 .iter()
3063 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
3064 .and_then(|s| s.link)
3065 })
3066 .flatten()
3067 })
3068 .collect();
3069 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
3070 return false;
3071 }
3072 if snapshot {
3073 self.snapshot();
3074 }
3075 for (data, _) in self
3076 .lanes
3077 .iter_mut()
3078 .zip(&cut_subs)
3079 .filter(|&(_, &cut)| cut)
3080 {
3081 // A split is room of no width: the halves keep their windows by
3082 // proportion and nothing moves.
3083 sub_open_room(&mut data.subs, timeline_frame, 0);
3084 debug_assert!(subs_sorted_disjoint(&data.subs));
3085 }
3086 // Each side is its own question, and the answer is the group the clip
3087 // already carried: the left half *keeps* its take's id -- the take the
3088 // frames before the cut still are -- and the right halves of one take
3089 // share one fresh id of their own, clips and captions alike. A lane
3090 // holding no group (a `place`ment, a caption nobody grouped) comes out
3091 // of the cut holding none, which is what it went in with. The captions'
3092 // own links were drawn above, before the room opened.
3093 let orig: Vec<Option<u32>> = cut.iter().map(|c| c.and_then(|c| c.link)).collect();
3094 let mut distinct: Vec<u32> = Vec::new();
3095 for id in orig.iter().chain(&sub_orig).flatten() {
3096 if !distinct.contains(id) {
3097 distinct.push(*id);
3098 }
3099 }
3100 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
3101 let right_of =
3102 |link: Option<u32>| link.and_then(|id| distinct.iter().position(|&d| d == id)).map(|at| fresh[at]);
3103 for (l, data) in self.lanes.iter_mut().enumerate() {
3104 if !cut_subs[l] {
3105 continue;
3106 }
3107 // The pair the razor just made: they touch at the frame it cut.
3108 if let Some(idx) = data
3109 .subs
3110 .iter()
3111 .position(|s| s.end() == timeline_frame)
3112 .filter(|&idx| data.subs.get(idx + 1).is_some_and(|n| n.start == timeline_frame))
3113 {
3114 data.subs[idx].link = sub_orig[l];
3115 data.subs[idx + 1].link = right_of(sub_orig[l]);
3116 }
3117 }
3118 for (data_i, data) in self.lanes.iter_mut().enumerate() {
3119 // The lanes this call was not scoped to are not cut, whatever their
3120 // own clips would allow.
3121 let Some(idx) = splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some()) else {
3122 continue;
3123 };
3124 let mut tail = data.clips[idx];
3125 // Where the cut lands *in the file*, which is the clip's own rate
3126 // away from where it lands on the timeline. Both halves keep the
3127 // speed, and `splittable` has already refused any frame at which
3128 // the two would not add up to the one being cut.
3129 tail.in_frame = split_source(&tail, timeline_frame).expect("splittable said so");
3130 tail.start = timeline_frame;
3131 tail.link = right_of(orig[data_i]);
3132 // A split makes a new edge for each half, and a fade is a promise
3133 // about an edge: only the half that *kept* the original edge
3134 // keeps that fade, re-clamped to its own now-shorter length (a
3135 // cut inside the ramp shortens it, never leaves it pointing past
3136 // the clip it is on); the edge the cut itself made starts, or
3137 // ends, flat -- there was no silence there to ramp out of.
3138 tail.fade_in = 0;
3139 tail.fade_out = tail.fade_out.min(tail.frames());
3140 // A dissolve is a promise about the *end* edge, same as
3141 // `fade_out`: only the half that kept the clip's original end
3142 // (the tail) keeps it, re-clamped to its own now-shorter length;
3143 // the head's new end is the cut the razor just made, which starts
3144 // flat -- there was no successor to dissolve into there.
3145 tail.transition_out = tail.transition_out.min(tail.frames());
3146 data.clips[idx].out_frame = tail.in_frame;
3147 data.clips[idx].link = orig[data_i];
3148 data.clips[idx].fade_out = 0;
3149 data.clips[idx].transition_out = 0;
3150 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
3151 data.clips.insert(idx + 1, tail);
3152 }
3153 true
3154 }
3155
3156 /// The inverse of [`split`](Project::split): rejoin the placements that meet
3157 /// at `timeline_frame` in every lane and put the result back in one group.
3158 /// Only what a split could have produced is rejoined -- the two sides must
3159 /// touch on the timeline *and* be consecutive frames of the same source --
3160 /// so the clip list comes back exactly as it was and traversal with it.
3161 /// `false` when no lane has such a pair. The rejoined placement keeps the
3162 /// **left** half's id, which is the take the split left on it: rejoining a
3163 /// cut take puts the take back, id and all.
3164 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
3165 // What each lane would end up covering, if it joins here at all.
3166 let joined: Vec<Option<(u32, u32)>> = self
3167 .lanes
3168 .iter()
3169 .map(|l| {
3170 joinable(&l.clips, timeline_frame)
3171 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
3172 })
3173 .collect();
3174 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
3175 let join_subs: Vec<Option<usize>> = self
3176 .lanes
3177 .iter()
3178 .map(|l| sub_joinable(&l.subs, timeline_frame))
3179 .collect();
3180 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
3181 return false;
3182 }
3183 self.snapshot();
3184 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
3185 if let Some(idx) = sub {
3186 data.subs[idx].frames += data.subs[idx + 1].frames;
3187 data.subs[idx].out_us = data.subs[idx + 1].out_us;
3188 data.subs.remove(idx + 1);
3189 debug_assert!(subs_sorted_disjoint(&data.subs));
3190 }
3191 let Some(idx) = joinable(&data.clips, timeline_frame) else {
3192 continue;
3193 };
3194 data.clips[idx].out_frame = data.clips[idx + 1].out_frame;
3195 data.clips.remove(idx + 1);
3196 }
3197 true
3198 }
3199
3200 /// Take the placement at `idx` of `lane` out of its group: every clip and
3201 /// every caption carrying its id -- on however many lanes -- is handed an
3202 /// id of its own, so from here on each half moves, trims and is deleted
3203 /// alone. The music video whose sound is to be cut against its picture
3204 /// starts here, and so does the caption that has to come off the picture it
3205 /// was pinned to.
3206 ///
3207 /// An id of its own rather than none at all: a half no other lane is grouped
3208 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
3209 /// (see [`links_are_consistent`]), and it is what a front-end already draws
3210 /// as detached. `None` would instead say "was never part of a take", which
3211 /// is what a one-lane [`place`](Project::place) means.
3212 ///
3213 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
3214 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
3215 /// the group back. Refused (`false`, nothing changed) for an index that is
3216 /// not there, a placement in no group at all, and one whose group has no
3217 /// other half -- that one is already detached, and a refusal must not cost
3218 /// an undo step.
3219 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3220 let Some(members) = self.group_of(lane, idx) else {
3221 return false;
3222 };
3223 if members.alone() {
3224 return false;
3225 }
3226 let Some(id) = self
3227 .lane(lane)
3228 .get(idx)
3229 .and_then(|c| c.link)
3230 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
3231 else {
3232 return false;
3233 };
3234 self.snapshot();
3235 // Drawn before the walk: `new_link` takes the whole project, and the
3236 // walk holds the lanes.
3237 let count = members.clips.len() + members.subs.len();
3238 let mut fresh = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
3239 for data in &mut self.lanes {
3240 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
3241 c.link = fresh.pop();
3242 }
3243 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
3244 s.link = fresh.pop();
3245 }
3246 }
3247 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3248 true
3249 }
3250
3251 /// Put two clips on two lanes into one group, so what moves one moves the
3252 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
3253 /// how a picture is regrouped with sound it was never opened with. Whatever
3254 /// either of them was grouped with comes along: those clips cover this same
3255 /// span already, so the result is one group and not two overlapping ones.
3256 ///
3257 /// Same frames or nothing: a group id names **one span** on however many
3258 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
3259 /// clips that do not cover the same frames cannot be one take, and the
3260 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
3261 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
3262 /// mean, not the rule.
3263 ///
3264 /// Metadata only, one snapshot. The error says what is wrong, because
3265 /// `false` would not: a bad index, one lane twice (a group is at most one
3266 /// clip per lane), spans that disagree, and a pair that is already one take
3267 /// -- nothing changes, and none of them costs an undo step.
3268 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3269 if a == b {
3270 return Err(format!(
3271 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
3272 a.label()
3273 )
3274 .into());
3275 }
3276 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
3277 p.lane(lane)
3278 .get(idx)
3279 .copied()
3280 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
3281 };
3282 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
3283 if (x.start, x.end()) != (y.start, y.end()) {
3284 return Err(format!(
3285 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
3286 a.label(),
3287 x.start,
3288 x.end(),
3289 b.label(),
3290 y.start,
3291 y.end()
3292 )
3293 .into());
3294 }
3295 if x.link.is_some() && x.link == y.link {
3296 return Err("those two are one take already".into());
3297 }
3298 self.snapshot();
3299 let id = self.new_link();
3300 // Every clip either of them was grouped with, by the same rule: all of
3301 // them cover this span, so one id over the lot stays consistent.
3302 let old = [x.link, y.link];
3303 for data in &mut self.lanes {
3304 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
3305 if old.contains(&c.link) {
3306 c.link = Some(id);
3307 }
3308 }
3309 }
3310 // And the two themselves, which a `place` may have left in no group.
3311 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
3312 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
3313 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3314 Ok(())
3315 }
3316
3317 /// Put every placement the picks name into one group -- the group a hand
3318 /// builds with ctrl-click and a menu: the picture, its sound and the
3319 /// caption over it, on as many lanes as the picks name. What any of them
3320 /// was already grouped with rides along (one group, not two sharing a
3321 /// member), and the members keep their own spans: a group is one id over
3322 /// one placement per lane, and the offsets between them are what the group
3323 /// preserves -- a drag, a trim and a delete all move the members *by the
3324 /// same distance*, not to the same frames.
3325 ///
3326 /// No two picks may name one lane -- that is the one clip-per-lane rule,
3327 /// and the refusal says which lane -- and a pick that names nothing is
3328 /// refused with its own words. At least two picks, or there is nothing to
3329 /// group.
3330 ///
3331 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
3332 /// apart again. None of the refusals changes anything or costs an undo
3333 /// step.
3334 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3335 if picks.len() < 2 {
3336 return Err("a group is two placements or more: pick another one first".into());
3337 }
3338 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
3339 for &(lane, idx) in picks {
3340 if seen.contains(&lane) {
3341 return Err(format!(
3342 "a group is one placement per lane: {} is picked twice -- keep one clip per \
3343 track",
3344 lane.label()
3345 )
3346 .into());
3347 }
3348 seen.push(lane);
3349 let there = if lane.kind == LaneKind::Subtitle {
3350 idx < self.sub_lane(lane).len()
3351 } else {
3352 idx < self.lane(lane).len()
3353 };
3354 if !there {
3355 let what = if lane.kind == LaneKind::Subtitle {
3356 "subtitle"
3357 } else {
3358 "clip"
3359 };
3360 return Err(
3361 format!("there is no {what} {idx} on {}", lane.label()).into()
3362 );
3363 }
3364 }
3365 let links: Vec<Option<u32>> = picks
3366 .iter()
3367 .map(|&(lane, idx)| {
3368 if lane.kind == LaneKind::Subtitle {
3369 self.sub_lane(lane)[idx].link
3370 } else {
3371 self.lane(lane)[idx].link
3372 }
3373 })
3374 .collect();
3375 // The picks are already one per lane (`seen`, above), but a pick's
3376 // *existing* group can carry a second member onto a lane another
3377 // pick (or another existing group in the merge) already occupies --
3378 // two captions on one sub lane, say, each grouped with a different
3379 // clip before this call. Merging both in would leave that lane with
3380 // two members of one id, which `links_are_consistent` may never see:
3381 // refused by name, before anything moves, rather than a group closed
3382 // broken.
3383 let labels = handles(&self.lanes);
3384 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
3385 for (li, data) in self.lanes.iter().enumerate() {
3386 let n = data.clips.iter().filter(|c| c.link.is_some() && links.contains(&c.link)).count()
3387 + data.subs.iter().filter(|s| s.link.is_some() && links.contains(&s.link)).count();
3388 if n > 0 {
3389 per_lane.insert(li, n as u32);
3390 }
3391 }
3392 // A pick that carries no link of its own is invisible to the scan
3393 // above (there is no `Some` to match): it still claims its lane.
3394 for &(lane, _) in picks {
3395 let li = self.index(lane).expect("checked above");
3396 per_lane.entry(li).or_insert(0);
3397 if !self.lanes[li]
3398 .clips
3399 .iter()
3400 .any(|c| c.link.is_some() && links.contains(&c.link))
3401 && !self.lanes[li]
3402 .subs
3403 .iter()
3404 .any(|s| s.link.is_some() && links.contains(&s.link))
3405 {
3406 *per_lane.get_mut(&li).expect("just inserted") += 1;
3407 }
3408 }
3409 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
3410 return Err(format!(
3411 "a group is one placement per lane: merging these groups would put two on {}",
3412 labels[li].label()
3413 )
3414 .into());
3415 }
3416 self.snapshot();
3417 let id = self.new_link();
3418 // Whatever any pick was grouped with comes along, for [`group`]'s
3419 // reason -- one id over the lot, not two groups sharing a member.
3420 for data in &mut self.lanes {
3421 for c in data.clips.iter_mut() {
3422 if c.link.is_some() && links.contains(&c.link) {
3423 c.link = Some(id);
3424 }
3425 }
3426 for s in data.subs.iter_mut() {
3427 if s.link.is_some() && links.contains(&s.link) {
3428 s.link = Some(id);
3429 }
3430 }
3431 }
3432 // And the picks themselves, which a `place` may have left in no group.
3433 // The lane seats are read before the walk, which holds the lanes.
3434 let seats: Vec<(usize, bool)> = picks
3435 .iter()
3436 .map(|&(lane, _)| {
3437 (
3438 self.index(lane).expect("checked above"),
3439 lane.kind == LaneKind::Subtitle,
3440 )
3441 })
3442 .collect();
3443 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
3444 let _ = lane;
3445 if sub {
3446 self.lanes[at].subs[idx].link = Some(id);
3447 } else {
3448 self.lanes[at].clips[idx].link = Some(id);
3449 }
3450 }
3451 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3452 Ok(())
3453 }
3454
3455 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
3456 /// lands on and leaving every other clip exactly where it is -- the
3457 /// per-lane paste. Anything already there is trimmed away (and split in two
3458 /// if `clip` lands inside it), which is what keeps the lane sorted and
3459 /// disjoint; nothing ripples, so a gap before the placement simply stays a
3460 /// gap. Refused only for an empty `clip`.
3461 ///
3462 /// The placement belongs to no group: a clipboard clip carries the link id
3463 /// of the take it was copied from, and placing it twice -- or placing a copy
3464 /// back over the clip it came from -- would put that id on two clips of one
3465 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
3466 /// `None` rather than a fresh id because a one-lane placement has nothing on
3467 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
3468 /// become a group again.
3469 ///
3470 /// Refused for an empty `clip`, for a lane that is not there, and for a
3471 /// subtitle lane, which carries no picture and no sound
3472 /// ([`Project::place_sub`] is its door).
3473 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3474 if clip.out_frame <= clip.in_frame
3475 || lane.kind == LaneKind::Subtitle
3476 || self.index(lane).is_none()
3477 {
3478 return false;
3479 }
3480 self.snapshot();
3481 let clip = Clip {
3482 fade_in: 0,
3483 fade_out: 0,
3484 transition_out: 0,
3485 start: timeline_frame,
3486 link: None,
3487 ..clip
3488 };
3489 self.insert_over(lane, clip);
3490 true
3491 }
3492
3493 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
3494 /// one grouped take -- what a picture let go over a further video track
3495 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
3496 /// if it is not there yet (the `+ V` button adds a video row alone). Without
3497 /// this half a file with sound landed on a layer silent, and the only way to
3498 /// hear it was to drop it a second time on an audio lane.
3499 ///
3500 /// Both halves overwrite what they land on and neither ripples, exactly as
3501 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
3502 /// nothing under it moves. One history snapshot for the pair, the added lane
3503 /// included, so one [`Project::undo`] takes the whole placement back. The two
3504 /// carry one link, which is what makes them one take to a drag, a trim and a
3505 /// save.
3506 ///
3507 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
3508 /// there or is not a video lane: sound placed alone is
3509 /// [`place`](Project::place)'s door, and a still has no sound to pair.
3510 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
3511 if clip.out_frame <= clip.in_frame
3512 || lane.kind != LaneKind::Video
3513 || self.index(lane).is_none()
3514 {
3515 return false;
3516 }
3517 self.snapshot();
3518 // `A2` for `V2` -- and the rows between it and the last audio lane, since
3519 // an ord names a lane only while every ord below it does.
3520 while self.lane_count(LaneKind::Audio) <= lane.ord {
3521 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
3522 }
3523 let clip = Clip {
3524 fade_in: 0,
3525 fade_out: 0,
3526 transition_out: 0,
3527 start: timeline_frame,
3528 link: Some(self.new_link()),
3529 ..clip
3530 };
3531 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
3532 self.insert_over(half, clip);
3533 }
3534 debug_assert!(links_are_consistent(&self.lanes).is_ok());
3535 true
3536 }
3537
3538 /// `clip` into `lane` at its own start, over whatever it lands on: the
3539 /// insert both placement doors make, which is what keeps a lane sorted and
3540 /// disjoint. The caller has checked that the lane is there.
3541 fn insert_over(&mut self, lane: Lane, clip: Clip) {
3542 let clips = self.lane_mut(lane).expect("the caller checked the lane");
3543 clear(clips, clip.start, clip.end());
3544 let idx = clips.partition_point(|c| c.start < clip.start);
3545 clips.insert(idx, clip);
3546 debug_assert!(sorted_disjoint(clips));
3547 }
3548
3549 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
3550 /// frame `start`: the drag that rearranges takes, along a track and across
3551 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
3552 /// was. `start` at the clip's own is the pure lane change.
3553 ///
3554 /// The whole group travels the same distance, each half on the lane it
3555 /// already sits on -- a link means "these cover one span on however many
3556 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
3557 /// sound would be a group no save could load. Only the dragged half changes
3558 /// lane, and that is not a desync: a link names no lane at all.
3559 ///
3560 /// `start` is **clamped**, never refused, to the room the group has: no
3561 /// member crosses a neighbour on the lane it lands on, exactly as
3562 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
3563 /// dragging past a neighbour means "as far as it goes", and butting up
3564 /// against the take next door is how clips are laid end to end. The
3565 /// tightest member's wall wins, so a sound half boxed in between two others
3566 /// holds its picture still.
3567 ///
3568 /// Refused, changing nothing and costing no undo step, for a lane that is
3569 /// not there, an index that is not there, a move across *kinds* (a picture
3570 /// cannot play on an audio lane, and the save it wrote would not open
3571 /// again), a head let go *inside* another clip or into a gap too narrow to
3572 /// hold this one -- a move that overwrote what it landed on would destroy a
3573 /// take the pointer never named, which is what [`place`](Project::place)
3574 /// may do and a drag may not -- a half let go onto the lane its own partner
3575 /// is on, and a drop that changes neither lane nor frame, which is a clip
3576 /// picked up and put back down, i.e. a click.
3577 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
3578 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else {
3579 return false;
3580 };
3581 if from.kind != to.kind {
3582 return false;
3583 }
3584 let members = self.group_of(from, idx).expect("the clip was found");
3585 let held = self.index(from).expect("the clip was found on it");
3586 // The two halves of one group would land on one span of one lane, which
3587 // is the one thing a link may never mean. Refused rather than clamped:
3588 // the partner moves the same distance, so there is no room for it
3589 // anywhere on that lane.
3590 if dest != held
3591 && members
3592 .clips
3593 .iter()
3594 .chain(&members.subs)
3595 .any(|&(l, _)| l == dest)
3596 {
3597 return false;
3598 }
3599 let want = i64::from(start) - i64::from(clip.start);
3600 // How far the group may travel, in timeline frames and signed: every
3601 // member -- the clips and any caption grouped with them -- narrows it
3602 // to the gap it is landing in, and what is left is what the pointer is
3603 // clamped to.
3604 let Some((lo, hi)) = self.move_room(&members, Some((held, idx, dest, start))) else {
3605 return false;
3606 };
3607 if lo > hi {
3608 return false;
3609 }
3610 let delta = want.clamp(lo, hi);
3611 if delta == 0 && dest == held {
3612 return false;
3613 }
3614 self.snapshot();
3615 for &(l, i) in &members.clips {
3616 let c = &mut self.lanes[l].clips[i];
3617 // In range by the walls above, which are `u32` frames throughout.
3618 c.start = (i64::from(c.start) + delta) as u32;
3619 }
3620 for &(l, i) in &members.subs {
3621 let s = &mut self.lanes[l].subs[i];
3622 s.start = (i64::from(s.start) + delta) as u32;
3623 }
3624 if dest != held {
3625 let clip = self.lanes[held].clips.remove(idx);
3626 let clips = &mut self.lanes[dest].clips;
3627 let at = clips.partition_point(|c| c.start < clip.start);
3628 clips.insert(at, clip);
3629 }
3630 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
3631 debug_assert!(members
3632 .clips
3633 .iter()
3634 .chain(&members.subs)
3635 .all(|&(l, _)| {
3636 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
3637 }));
3638 true
3639 }
3640
3641 /// How far a group drag may travel, `(least, most)` in timeline frames and
3642 /// signed: every member narrows the range to the gap it is landing in --
3643 /// the clips against their lanes' clips and the captions against their
3644 /// lanes' captions -- and what is left is what the pointer is clamped to.
3645 /// `travelling` names the one member that changes lane, if any: the clip a
3646 /// hand is carrying onto another track, whose walls are read on the lane it
3647 /// is let go over at the frame the pointer named. `None` when a member has
3648 /// no gap to land in at all.
3649 fn move_room(
3650 &self,
3651 members: &Members,
3652 travelling: Option<(usize, usize, usize, u32)>,
3653 ) -> Option<(i64, i64)> {
3654 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
3655 for &(l, i) in members.clips.iter().chain(&members.subs) {
3656 let sub = members.subs.contains(&(l, i));
3657 let (start, frames) = match self.lanes[l]
3658 .clips
3659 .get(i)
3660 .filter(|_| !sub)
3661 .map(|c| (c.start, c.frames()))
3662 {
3663 Some(pair) => pair,
3664 None => {
3665 let s = self.lanes[l].subs.get(i)?;
3666 (s.start, s.frames)
3667 }
3668 };
3669 let land = travelling
3670 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
3671 .map_or(l, |(_, _, dest, _)| dest);
3672 // Which gap this member's walls are read off: its own place on the
3673 // lane it stays on, and the frame the pointer named on the lane it
3674 // is let go over. A clip's neighbours are the clips of the lane it
3675 // lands on and a caption's are its captions -- the two lists of one
3676 // lane never meet.
3677 let at = match travelling {
3678 Some((fl, fi, _, asked)) if (fl, fi) == (l, i) && land != l => asked,
3679 _ => start,
3680 };
3681 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
3682 let neighbours: Vec<(u32, u32)> = if sub {
3683 self.lanes[land]
3684 .subs
3685 .iter()
3686 .map(|s| (s.start, s.end()))
3687 .collect()
3688 } else {
3689 self.lanes[land]
3690 .clips
3691 .iter()
3692 .map(|c| (c.start, c.end()))
3693 .collect()
3694 };
3695 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
3696 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
3697 continue;
3698 }
3699 if *other_start <= at && at < *other_end {
3700 // A head let go inside another placement, which a clamp
3701 // has no answer for: the drop is refused.
3702 return None;
3703 }
3704 match other_end <= &at {
3705 true => wall_lo = wall_lo.max(*other_end),
3706 false => wall_hi = wall_hi.min(*other_start),
3707 }
3708 }
3709 if wall_hi - wall_lo < frames {
3710 return None;
3711 }
3712 lo = lo.max(i64::from(wall_lo) - i64::from(start));
3713 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
3714 }
3715 Some((lo, hi))
3716 }
3717
3718 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
3719 /// the drag on a clip's end that makes it play more or less of its source.
3720 /// The rest of the lane stays exactly where it is (nothing ripples), so what
3721 /// a shortened clip leaves behind is a gap and what a lengthened one takes
3722 /// is room that was already empty. One snapshot, so a whole drag is one
3723 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
3724 /// sample. Changes the timeline->source mapping: the caller must reseek.
3725 ///
3726 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
3727 /// exactly what they played before, which is what makes this a trim and not
3728 /// a slip.
3729 ///
3730 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
3731 /// legal means "as far as it goes", and stopping the box there is the
3732 /// affordance. The walls are: one frame of clip always survives, an edge
3733 /// never crosses the neighbouring clip on its own lane, an in-point never
3734 /// walks back past the source's first frame, and an out-point never runs
3735 /// past `source_frames[clip.source]` -- the caller's table of how long each
3736 /// source actually is ([`Project`] does not know, and a clip ending past its
3737 /// file's last frame is a save that will not open again; see
3738 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
3739 /// there may not grow at all.
3740 ///
3741 /// Linked placements trim *together*, by one delta: every member's same
3742 /// edge moves the distance the dragged one did, clamped to the room its
3743 /// own walls leave -- offsets between the members of a hand-built group
3744 /// survive the trim, exactly as they survive a drag.
3745 ///
3746 /// `false`, changing nothing and costing no undo step, for an index that is
3747 /// not there and for an edge that is already where it was asked to go.
3748 pub fn trim(
3749 &mut self,
3750 lane: Lane,
3751 idx: usize,
3752 edge: Edge,
3753 to: u32,
3754 source_frames: &[u32],
3755 ) -> bool {
3756 let (Some((lo, hi)), Some(clip)) = (
3757 self.trim_room(lane, idx, edge, source_frames),
3758 self.lane(lane).get(idx).copied(),
3759 ) else {
3760 return false;
3761 };
3762 let to = to.clamp(lo, hi);
3763 let at = match edge {
3764 Edge::Start => clip.start,
3765 Edge::End => clip.end(),
3766 };
3767 if to == at {
3768 return false;
3769 }
3770 // Worked out before anything moves: at a slow rate a room can be too
3771 // narrow to hold even one source frame ([`Speed::fit`]), and the
3772 // dragged clip refusing to fit must refuse the whole gesture rather
3773 // than be given a range wider than its room -- which is the overlap
3774 // the lane invariant exists to forbid. The walls below leave that room,
3775 // so this is the backstop for a project that came in through another
3776 // door.
3777 let room = match edge {
3778 // The frames that stay play what they played, so what survives is
3779 // measured from the *end*.
3780 Edge::Start => clip.end() - to,
3781 Edge::End => to - clip.start,
3782 };
3783 let Some(keep) = clip.speed.fit(room) else {
3784 return false;
3785 };
3786 let members = self.group_of(lane, idx).expect("checked above");
3787 self.snapshot();
3788 let still = self.is_still(&clip);
3789 let held = self.index(lane).expect("checked above");
3790 let c = &mut self.lanes[held].clips[idx];
3791 match edge {
3792 // A still has no earlier frame to walk an in-point back to --
3793 // every frame of it is the same picture -- so its head grows
3794 // *forward*: the range it plays is however long the new room is,
3795 // anchored at the source's frame 0. Bounded by `lo`, which is where
3796 // the cap in `source_frames` is applied.
3797 Edge::Start if still => {
3798 c.in_frame = 0;
3799 c.out_frame = keep;
3800 c.start = to;
3801 }
3802 Edge::Start => {
3803 // Non-negative by `lo`, which is what keeps the in-point on the
3804 // source.
3805 c.in_frame = c.out_frame - keep.min(c.out_frame);
3806 c.start = to;
3807 }
3808 // Never wider than the room the edge was clamped to: see
3809 // [`Speed::fit`].
3810 Edge::End => c.out_frame = c.in_frame + keep,
3811 }
3812 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
3813 self.follow_group(&members, &(held, idx), edge, i64::from(to) - i64::from(at), source_frames);
3814 true
3815 }
3816
3817 /// The rest of a group after one member's `edge` has moved by `delta`:
3818 /// every other member's same edge moves the same distance, clamped to the
3819 /// room its own walls leave -- a clip's against its lane and its source,
3820 /// a caption's against its own lane, its window following by the
3821 /// placement's own proportion. The undo step is the caller's: this is the
3822 // second half of one edit, not an edit of its own.
3823 fn follow_group(
3824 &mut self,
3825 members: &Members,
3826 dragged: &(usize, usize),
3827 edge: Edge,
3828 delta: i64,
3829 source_frames: &[u32],
3830 ) {
3831 for &(l, i) in &members.clips {
3832 if (l, i) == *dragged {
3833 continue;
3834 }
3835 let c = self.lanes[l].clips[i];
3836 let at = match edge {
3837 Edge::Start => c.start,
3838 Edge::End => c.end(),
3839 };
3840 let (lo, hi) = self.clip_room(l, i, edge, source_frames);
3841 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3842 if to == at {
3843 continue;
3844 }
3845 let room = match edge {
3846 Edge::Start => c.end() - to,
3847 Edge::End => to - c.start,
3848 };
3849 let Some(keep) = c.speed.fit(room) else {
3850 continue;
3851 };
3852 let still = self.is_still(&self.lanes[l].clips[i]);
3853 let c = &mut self.lanes[l].clips[i];
3854 match edge {
3855 Edge::Start if still => {
3856 c.in_frame = 0;
3857 c.out_frame = keep;
3858 c.start = to;
3859 }
3860 Edge::Start => {
3861 c.in_frame = c.out_frame - keep.min(c.out_frame);
3862 c.start = to;
3863 }
3864 Edge::End => c.out_frame = c.in_frame + keep,
3865 }
3866 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
3867 }
3868 for &(l, i) in &members.subs {
3869 if (l, i) == *dragged {
3870 continue;
3871 }
3872 let s = self.lanes[l].subs[i];
3873 let at = match edge {
3874 Edge::Start => s.start,
3875 Edge::End => s.end(),
3876 };
3877 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
3878 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
3879 if to == at {
3880 continue;
3881 }
3882 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
3883 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
3884 }
3885 }
3886
3887 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
3888 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
3889 /// What a front-end drawing the box *during* a drag asks, so the live width
3890 /// is the width the release will commit and an edge stops under the pointer
3891 /// rather than snapping back. The **clip's own** walls: the rest of its
3892 /// group follows by the same delta within their own ([`follow_group`]), so
3893 /// what is drawn for the dragged edge is what its own clip will commit.
3894 /// `None` for an index that is not there.
3895 pub fn trim_room(
3896 &self,
3897 lane: Lane,
3898 idx: usize,
3899 edge: Edge,
3900 source_frames: &[u32],
3901 ) -> Option<(u32, u32)> {
3902 let l = self.index(lane)?;
3903 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, source_frames))
3904 }
3905
3906 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
3907 /// its lane's storage index: the one wall computation, asked for the clip
3908 /// itself and for each member a group trim carries.
3909 fn clip_room(
3910 &self,
3911 l: usize,
3912 i: usize,
3913 edge: Edge,
3914 source_frames: &[u32],
3915 ) -> (u32, u32) {
3916 let clips = &self.lanes[l].clips;
3917 let c = clips[i];
3918 let (lo, hi) = match edge {
3919 Edge::Start => (
3920 // Back to the source's own first frame -- as many *timeline*
3921 // frames as that head is worth at the clip's rate, which at
3922 // real time is the head itself -- and never over the clip in
3923 // front of it. Saturating because a clip may hold *more*
3924 // head than the timeline has room for -- a ripple delete
3925 // slides a clip back to frame 0 with its in-point wherever
3926 // the cut left it -- and frame 0 is the other wall.
3927 //
3928 // A still is measured from its *tail* instead: it has no
3929 // in-point worth the name (every frame the same picture), so
3930 // its head reaches exactly as far as its tail does -- out to
3931 // the length the caller's table gives it, whole. Measured
3932 // from the in-point it would have no head room at all, which
3933 // is a placed picture whose left edge cannot be dragged out.
3934 // No entry in the table means no growth, as it does at the
3935 // other end.
3936 if self.is_still(&c) {
3937 c.end().saturating_sub(
3938 c.speed
3939 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
3940 )
3941 } else {
3942 c.start.saturating_sub(c.speed.room(c.in_frame))
3943 }
3944 .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
3945 // One *frame of clip* always survives, and at a rate below
3946 // real time one frame of clip is several frames of timeline
3947 // ([`Speed::room`]): an edge dragged closer than that would
3948 // ask for a range no source frame fits in. At real time this
3949 // is `end - 1`, unchanged.
3950 c.end() - c.speed.room(1),
3951 ),
3952 Edge::End => (
3953 // ...and the same wall from the other end: the shortest this
3954 // clip can be is the room one source frame of it takes.
3955 c.start + c.speed.room(1),
3956 // Out to whatever is left of the source -- again in timeline
3957 // frames, at this clip's rate -- and never over the clip
3958 // behind it.
3959 c.start
3960 .saturating_add(
3961 c.speed.room(
3962 source_frames
3963 .get(c.source)
3964 .copied()
3965 .unwrap_or(c.out_frame)
3966 .saturating_sub(c.in_frame),
3967 ),
3968 )
3969 .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
3970 ),
3971 };
3972 // `hi.max(lo)`: for a clip the invariants hold for, the range always
3973 // contains the edge's own place, and a caller's wrong `source_frames`
3974 // must not become an empty range (or a panicking `clamp`) here.
3975 (lo, hi.max(lo))
3976 }
3977
3978 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
3979 /// every frame is the same picture, so which frame of it a clip's in-point
3980 /// names is not a question -- what [`Project::trim`] lets grow at either
3981 /// end. `false` for a source that is not there.
3982 fn is_still(&self, clip: &Clip) -> bool {
3983 self.sources
3984 .get(clip.source)
3985 .is_some_and(|s| crate::is_image(&s.path))
3986 }
3987
3988 /// The placements that move as one with the one at `idx` of `lane` --
3989 /// itself and whatever carries its link, on the media lanes and the
3990 /// subtitle ones alike. `None` for an index that is not there.
3991 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
3992 let sub = lane.kind == LaneKind::Subtitle;
3993 let link = if sub {
3994 self.sub_lane(lane).get(idx)?.link
3995 } else {
3996 self.lane(lane).get(idx)?.link
3997 };
3998 let mut members = Members::default();
3999 match link {
4000 Some(link) => {
4001 for (l, data) in self.lanes.iter().enumerate() {
4002 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
4003 members.clips.push((l, i));
4004 }
4005 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
4006 members.subs.push((l, i));
4007 }
4008 }
4009 }
4010 None => {
4011 let l = self.index(lane).expect("the placement was found on it");
4012 if sub {
4013 members.subs.push((l, idx));
4014 } else {
4015 members.clips.push((l, idx));
4016 }
4017 }
4018 }
4019 Some(members)
4020 }
4021
4022 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
4023 /// new group, pushing everything from there on later by its length in
4024 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
4025 /// the clip it lands in is split around it; past the end of the timeline it
4026 /// goes down where it was asked for, with black in front of it -- which is
4027 /// what a library row let go on the open bed means, and what the ghost under
4028 /// the pointer promised. A clipboard means "put it here", not "here and
4029 /// black in front", and clamps to the end at its own door
4030 /// ([`crate::PlaybackSession::paste_at`]).
4031 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
4032 ///
4033 /// `V1` and `A1` and no other lane, because a take is one picture and one
4034 /// sound: copying it onto every lane there is would play the same audio
4035 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
4036 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
4037 /// video lane it is a clip that decodes to nothing, and a save carrying one
4038 /// does not open again -- and a still image ([`crate::is_image`]) reaches
4039 /// `V1` only, for the mirror of that reason. The room is still opened on
4040 /// every media lane, or the lanes it was not inserted into would slide out
4041 /// of step with the ones it was -- and the subtitle lanes are left alone:
4042 /// the words keep their own clock, and a caption that should travel with a
4043 /// clip is what a group is for.
4044 ///
4045 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
4046 /// Changes the timeline->source mapping: the caller must reseek. Refused for
4047 /// an empty `clip` and for one naming a source that is not there (both of
4048 /// which the public fields let a caller build), and for a paste whose ripple
4049 /// would push a clip past the last frame there is -- nothing is changed by
4050 /// any of them.
4051 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
4052 let Some(source) = self.sources.get(clip.source) else {
4053 return false;
4054 };
4055 if clip.out_frame <= clip.in_frame {
4056 return false;
4057 }
4058 let audio_only = crate::is_audio(&source.path);
4059 // ...and its mirror: a still is a picture and no sound, so a copy of one
4060 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
4061 // worker tries to demux -- which silences the *whole session*, not just
4062 // that clip -- and a save the engine's own `open_project` then refuses.
4063 let picture_only = crate::is_image(&source.path);
4064 // The frame it was asked for and no other: a row let go on the empty
4065 // bed past the last clip lands *there*, under the ghost that promised
4066 // it, with black in front. Clamping to the end here made every drop on
4067 // open bed an append -- the clipboard's rule, applied to a hand that
4068 // had named a place.
4069 let at = timeline_frame;
4070 // The room it takes on the timeline, which its speed decides -- not the
4071 // source range it reads.
4072 let len = clip.frames();
4073 // Room for it: `open_room` adds `len` to every start from `at` on, and a
4074 // hand-written file may hold a clip that ends at the very last frame
4075 // (`edith::check` permits `start + len == u32::MAX`). Refused here
4076 // rather than wrapped there -- a wrapped start lands *behind* the clip
4077 // it belongs after, which is an overlap no save will read back.
4078 if at.checked_add(len).is_none()
4079 || self
4080 .lanes
4081 .iter()
4082 .flat_map(|l| &l.clips)
4083 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
4084 {
4085 return false;
4086 }
4087 // ...and room *to open*: the paste splits whatever it lands inside of,
4088 // and a speeded clip can only be cut where its own rate has a source
4089 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
4090 // of one, which is the overlap a lane may never hold. At real time every
4091 // frame answers, so this cannot refuse an unspeeded paste.
4092 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
4093 if self
4094 .lanes
4095 .iter()
4096 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
4097 {
4098 return false;
4099 }
4100 self.snapshot();
4101 let clip = Clip {
4102 fade_in: 0,
4103 fade_out: 0,
4104 transition_out: 0,
4105 start: at,
4106 link: Some(self.new_link()),
4107 ..clip
4108 };
4109 // Only lanes that can play the source: a file with no picture belongs on
4110 // an audio lane and nowhere else, exactly as `place_stream_at` decides
4111 // it for an import. On a video lane it would decode to nothing, and the
4112 // save it wrote would not open again.
4113 let kinds: &[LaneKind] = match (audio_only, picture_only) {
4114 (true, _) => &[LaneKind::Audio],
4115 (_, true) => &[LaneKind::Video],
4116 _ => &[LaneKind::Video, LaneKind::Audio],
4117 };
4118 let takes: Vec<usize> = kinds
4119 .iter()
4120 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
4121 .collect();
4122 for (i, data) in self.lanes.iter_mut().enumerate() {
4123 open_room(&mut data.clips, at, len);
4124 // The subtitle lanes are NOT touched: a paste inserts media, and
4125 // the words keep their own clock. Opening room here used to split
4126 // a caption the paste landed inside and slide the rest behind it
4127 // -- "a caption that stayed put while the picture moved on no
4128 // longer says the same thing" -- but a caption pinned to nothing
4129 // (and a video arriving on a timeline of words alone) has no
4130 // picture to follow, and the split did to the words what no hand
4131 // asked for. A caption that should travel with a clip is what a
4132 // group is for, and a group moves as one.
4133 if takes.contains(&i) {
4134 let idx = data.clips.partition_point(|c| c.start < at);
4135 data.clips.insert(idx, clip);
4136 }
4137 debug_assert!(sorted_disjoint(&data.clips));
4138 debug_assert!(subs_sorted_disjoint(&data.subs));
4139 }
4140 true
4141 }
4142
4143 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
4144 /// silence, and nothing else moves. Refused only for an out-of-range index
4145 /// (which a lane that is not there always is) -- lifting the last placement
4146 /// there is leaves an *empty* timeline, which is a state the project holds
4147 /// like any other and an undo brings back.
4148 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
4149 if idx >= self.lane(lane).len() {
4150 return false;
4151 }
4152 self.snapshot();
4153 self.lane_mut(lane).expect("checked above").remove(idx);
4154 true
4155 }
4156
4157 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
4158 /// the hole: everything after slides back by `len`. The rippling delete --
4159 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
4160 /// empty range; a delete that leaves nothing behind empties the timeline,
4161 /// which is a state like any other and one undo away.
4162 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
4163 if len == 0 {
4164 return false;
4165 }
4166 // Nothing reaches past `at`: there is nothing to cut and nothing to
4167 // slide back, and a delete that changes nothing must not cost an undo
4168 // step (see [`snapshot`](Project::snapshot)).
4169 if !self
4170 .lanes
4171 .iter()
4172 .flat_map(|l| &l.clips)
4173 .any(|c| c.end() > at)
4174 {
4175 return false;
4176 }
4177 self.snapshot();
4178 let on = all_lanes(&self.lanes);
4179 ripple(&mut self.lanes, &on, at, len);
4180 true
4181 }
4182
4183 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
4184 /// a right-click on empty bench space names before offering to close it.
4185 /// `None` when `frame` sits inside a clip, or past the last one: the open
4186 /// end of a lane is not a gap, since there is nothing after it to slide
4187 /// back ([`gap`]).
4188 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
4189 gap(self.lane(lane), frame)
4190 }
4191
4192 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4193 /// together to keep sync -- what a right-click on empty bench space asks
4194 /// before the menu offers to close it, and what widens
4195 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
4196 /// named to the whole take the gap might be half of.
4197 ///
4198 /// A clip bordering the gap on `lane` -- the one ending where it starts,
4199 /// the one starting where it ends -- carries a link when it is one take
4200 /// with a clip on another lane. That lane joins the scope only when the
4201 /// *exact same* stretch is empty there too (same start, same length): the
4202 /// ripple then removes nothing but silence, on every lane it touches, and
4203 /// both halves stay the length they always were. A link whose partner
4204 /// lane is not empty there -- a gap of a different length, or none at all
4205 /// -- is named back to the caller rather than silently widened past
4206 /// (which would cut real media out of a lane nothing asked to touch) or
4207 /// silently left out (which is the defect this closes: a per-lane ripple
4208 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
4209 /// to refuse it after the fact, on the very half this could have carried
4210 /// along).
4211 ///
4212 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
4213 /// partner clip sits on another lane -- the unlinked case, untouched.
4214 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4215 let Some(li) = self.index(lane) else {
4216 return Err("no track to work on".into());
4217 };
4218 let labels = handles(&self.lanes);
4219 let end = start + frames;
4220 let mut scope = vec![lane];
4221 for c in self.lanes[li]
4222 .clips
4223 .iter()
4224 .filter(|c| c.end() == start || c.start == end)
4225 {
4226 let Some(id) = c.link else { continue };
4227 for (j, data) in self.lanes.iter().enumerate() {
4228 if j == li {
4229 continue;
4230 }
4231 let Some(half) = data.clips.iter().find(|o| o.link == Some(id)) else {
4232 continue;
4233 };
4234 match gap(&data.clips, start) {
4235 Some((s, f)) if s == start && f == frames => {
4236 let other = labels[j];
4237 if !scope.contains(&other) {
4238 scope.push(other);
4239 }
4240 }
4241 _ => {
4242 return Err(format!(
4243 "the {} clip at frame {} is one take with the {} clip at frame {}: \
4244 closing this gap alone would pull the take out of sync -- close {}'s \
4245 gap there too, or detach them first",
4246 labels[li].label(),
4247 c.start,
4248 labels[j].label(),
4249 half.start,
4250 labels[j].label()
4251 )
4252 .into());
4253 }
4254 }
4255 }
4256 }
4257 Ok(scope)
4258 }
4259
4260 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4261 /// out of the lanes in `scope` and close each hole, as one edit: the
4262 /// jumpcut a silence scan asks for ([`crate::silence`]).
4263 ///
4264 /// A lane that is not in `scope` **does not move**, which is the whole
4265 /// point of the parameter: the silences of a podcast track come out
4266 /// without the music track under it sliding. `scope` is an arbitrary set of
4267 /// lanes and not a kind or a range, so a caller with its own idea of what
4268 /// is selected (a take, a track, everything) says it in lanes and nothing
4269 /// here has to learn about selection.
4270 ///
4271 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4272 /// reason this exists rather than a caller's loop over
4273 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4274 /// undo press, not forty. Cut back to front, so a region's frames still
4275 /// mean what the caller measured while the ones before it are cut.
4276 ///
4277 /// The list is sorted and overlapping entries are merged before anything is
4278 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4279 /// other's frames. Refused, with no undo step, for an empty list, for a
4280 /// scope naming no lane that is there, and -- by name -- when the scope
4281 /// would take one half of a take with it
4282 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4283 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4284 let regions = tidy(regions);
4285 let on = self.scoped(scope)?;
4286 let Some(&(first, _)) = regions.first() else {
4287 return Err("nothing to cut".into());
4288 };
4289 self.scope_holds_takes_whole(&on, first)?;
4290 self.snapshot();
4291 for &(at, len) in regions.iter().rev() {
4292 ripple(&mut self.lanes, &on, at, len);
4293 }
4294 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4295 Ok(())
4296 }
4297
4298 /// The storage indices of `scope`, which is what every batch below walks.
4299 /// `Err` for a scope that names nothing there rather than a silent no-op:
4300 /// an edit asked for on a lane that is not there did not happen, and the
4301 /// caller has to hear so.
4302 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4303 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4304 match on.is_empty() {
4305 true => Err("no track to work on".into()),
4306 false => Ok(on),
4307 }
4308 }
4309
4310 /// The law a scoped ripple lives under: **a group travels as one**, so a
4311 /// batch that moves one half of a take and not the other would leave the
4312 /// halves disagreeing about where they stand -- an offset no hand asked
4313 /// for, and the reason the take's lanes have to be scoped together.
4314 ///
4315 /// Refused by name rather than widened silently. Widening would edit a
4316 /// track the user did not scope, which is exactly the surprise scoping
4317 /// exists to end; a front-end that wants the take is free to *say* the
4318 /// take's lanes, and to name them in what it tells the user afterwards.
4319 ///
4320 /// Only from `from` on: a take sitting entirely before the first cut does
4321 /// not move, so it is not this rule's business.
4322 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4323 let labels = handles(&self.lanes);
4324 // The halves of a group are on either of a lane's lists, and the
4325 // refusal names whichever sits outside the scope -- a clip like it
4326 // always has, and a caption now that a group may hold one.
4327 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4328 let Some(id) = link else {
4329 return Ok(());
4330 };
4331 for (j, data) in self.lanes.iter().enumerate() {
4332 if on.contains(&j) {
4333 continue;
4334 }
4335 let clip = data.clips.iter().find(|o| o.link == Some(id));
4336 let sub = data.subs.iter().find(|s| s.link == Some(id));
4337 if let Some(half) = clip {
4338 return Err(format!(
4339 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4340 moving one track of a take would pull it apart -- take the whole take, \
4341 or detach them first",
4342 labels[j].label(),
4343 half.start
4344 )
4345 .into());
4346 }
4347 if let Some(half) = sub {
4348 return Err(format!(
4349 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4350 moving one track of a take would pull it apart -- take the whole take, \
4351 or detach them first",
4352 labels[j].label(),
4353 half.start
4354 )
4355 .into());
4356 }
4357 }
4358 Ok(())
4359 };
4360 for &i in on {
4361 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4362 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4363 }
4364 // A caption before the first cut does not move, so it is not this
4365 // rule's business -- exactly the clip test's own line.
4366 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4367 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4368 }
4369 }
4370 Ok(())
4371 }
4372
4373 /// Play every one of `regions` at `speed` instead of cutting it: each is
4374 /// split out of whatever covers it, re-rated, and the room it no longer
4375 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4376 /// does not ripple, and a hole where a silence shrank is the one thing this
4377 /// must not leave. One snapshot for the lot, like
4378 /// [`cut_regions`](Project::cut_regions).
4379 ///
4380 /// The rate is **absolute**, not a multiplier on what is there: running it
4381 /// twice over the same stretch leaves it at `speed`, not at `speed`
4382 /// squared, so a second pass over an already-cut timeline changes nothing.
4383 ///
4384 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4385 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4386 ///
4387 /// Refused by name, with nothing changed and no undo step, when:
4388 ///
4389 /// * the scope would take one half of a take with it
4390 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4391 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4392 /// shrink by different amounts and the ripple would pull them apart,
4393 /// which is what cutting does not suffer and why delete mode has no such
4394 /// refusal;
4395 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4396 /// piece could not be split out exactly;
4397 /// * two lanes' pieces would end up different lengths, which is a group
4398 /// whose halves disagree about their span (the refusal
4399 /// [`write_speed`](Project::write_speed) already makes, in its words);
4400 /// * the region would grow rather than shrink, i.e. it already plays faster
4401 /// than `speed`.
4402 pub fn speed_regions(
4403 &mut self,
4404 regions: &[(u32, u32)],
4405 speed: Speed,
4406 scope: &[Lane],
4407 ) -> crate::Result<()> {
4408 let regions = tidy(regions);
4409 let on = self.scoped(scope)?;
4410 let Some(&(first, _)) = regions.first() else {
4411 return Err("nothing to speed up".into());
4412 };
4413 self.scope_holds_takes_whole(&on, first)?;
4414 let labels = handles(&self.lanes);
4415 // Before anything is touched, because this is the refusal a person can
4416 // act on: a clip that laps over the edge of a silence has to be trimmed
4417 // (or the silences cut instead), and saying so after a rollback would
4418 // be saying it about a timeline that already looks different.
4419 for &(at, len) in &regions {
4420 for &l in &on {
4421 for c in &self.lanes[l].clips {
4422 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4423 {
4424 return Err(format!(
4425 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4426 speeding it up would pull the lanes apart -- trim it first, or cut the \
4427 silences out instead",
4428 labels[l].label(),
4429 c.start,
4430 at + len
4431 )
4432 .into());
4433 }
4434 }
4435 }
4436 }
4437 // The rest is checked as it is built: a split's own arithmetic is what
4438 // says whether a rate can address an edge. So the snapshot is taken
4439 // first and *rolled back* on a refusal -- one undo either way, and a
4440 // refusal still costs no step (`undo` pops the one just pushed).
4441 self.snapshot();
4442 for &(at, len) in regions.iter().rev() {
4443 self.write_split(at, false, &on);
4444 self.write_split(at + len, false, &on);
4445 let mut room: Option<(Lane, u32)> = None;
4446 let mut refused = None;
4447 for &l in &on {
4448 let clips = &self.lanes[l].clips;
4449 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4450 if (c.start, c.end()) != (at, at + len) {
4451 // *Which* edge did not come off: a rate that cannot
4452 // address the end of the silence is not a rate that
4453 // cannot address its start, and naming the wrong frame
4454 // sends the user looking in the wrong place.
4455 let edge = match c.start == at {
4456 true => at + len,
4457 false => at,
4458 };
4459 refused = Some(format!(
4460 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4461 detach it, or put it back to 1.00x first",
4462 labels[l].label(),
4463 c.start,
4464 c.speed
4465 ));
4466 continue;
4467 }
4468 let after = speed.frames(c.len());
4469 match room {
4470 None => room = Some((labels[l], after)),
4471 Some((first, n)) if n != after => {
4472 refused = Some(format!(
4473 "at {speed} the {} half of the silence at frame {at} would cover \
4474 {after} frames and the {} half {n}: they are one take and a take \
4475 is one span -- detach them first",
4476 labels[l].label(),
4477 first.label()
4478 ));
4479 }
4480 Some(_) => {}
4481 }
4482 }
4483 }
4484 let shrunk = match (refused, room) {
4485 (Some(e), _) => {
4486 self.undo();
4487 return Err(e.into());
4488 }
4489 // A gap on every lane: nothing to re-rate, and nothing to close.
4490 (None, None) => continue,
4491 (None, Some((_, after))) => after,
4492 };
4493 // The region's new length, on every scoped lane alike.
4494 let after = shrunk;
4495 let Some(delta) = len.checked_sub(shrunk) else {
4496 self.undo();
4497 return Err(format!(
4498 "the silence at frame {at} already plays faster than {speed}: \
4499 at that rate it would be {shrunk} frames instead of {len}"
4500 )
4501 .into());
4502 };
4503 for &l in &on {
4504 for c in &mut self.lanes[l].clips {
4505 if c.start == at && c.end() == at + len {
4506 c.speed = speed;
4507 } else if c.start >= at + len {
4508 c.start -= delta;
4509 }
4510 }
4511 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4512 // The captions on a scoped lane travel with the region's time:
4513 // a piece inside it plays in `after` frames instead of `len`
4514 // -- same words on less timeline, its window untouched, for
4515 // [`write_speed`]'s reason -- and everything behind the region
4516 // slides up by what the region gave back.
4517 //
4518 // The pieces inside re-time by their *boundaries*, not each
4519 // on its own: rounding one piece's start and its neighbour's
4520 // start apart can land both on the same frame (two one-frame
4521 // cues of a thirty-frame region at 2x both want frame 15), so
4522 // the mapped boundaries are walked in order and forced apart
4523 // -- each piece at least one frame, none past the region's own
4524 // new end, where the first follower lands exactly. A rounding
4525 // artifact is clamped, not refused: nothing about the words
4526 // asked for an overlap.
4527 let share = f64::from(after) / f64::from(len).max(1.);
4528 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4529 let mut prev = at;
4530 let subs = &mut self.lanes[l].subs;
4531 for i in 0..subs.len() {
4532 let s = subs[i];
4533 if s.start >= at + len {
4534 subs[i].start = s.start - delta;
4535 } else if s.start >= at && s.end() <= at + len {
4536 let mut start = map(s.start).max(prev);
4537 let end = map(s.end()).max(start + 1).min(at + after);
4538 start = start.min(end - 1);
4539 subs[i].start = start;
4540 subs[i].frames = end - start;
4541 prev = end;
4542 }
4543 }
4544 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4545 }
4546 }
4547 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4548 Ok(())
4549 }
4550
4551 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4552 /// -- the whole-group delete a single-lane front-end means. `false` for a
4553 /// bad index. Changes the mapping: the caller must reseek.
4554 pub fn delete(&mut self, idx: usize) -> bool {
4555 self.delete_in(Lane::V1, idx)
4556 }
4557
4558 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4559 /// in no group (or a group of one, which is the same thing to a delete) is
4560 /// what it always was: its own span cut out of *every* lane, so the
4561 /// timeline closes up under it. A clip in a group takes the group with it,
4562 /// each member by its **own** span and on its **own** lane -- the members
4563 /// keep their offsets, so their spans may disagree, and the lanes may end
4564 /// up out of step with each other, which is inherent to a hand-built group
4565 /// and one undo away. Every member -- clips and captions alike -- goes by
4566 /// the same law: its own span out of its own lane, hole closed; a caption
4567 /// in no group keeps the lift that leaves a gap, which is its own door's
4568 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4569 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4570 /// index, and for a lane that is not there. Changes the mapping: the
4571 /// caller must reseek.
4572 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4573 let Some(members) = self.group_of(lane, idx) else {
4574 return false;
4575 };
4576 if !members.alone() {
4577 return self.delete_members(&members);
4578 }
4579 let Some(clip) = self.lane(lane).get(idx).copied() else {
4580 return false;
4581 };
4582 self.ripple_delete(clip.start, clip.frames())
4583 }
4584
4585 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4586 /// caption in no group lifts, exactly as its own key always made it
4587 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4588 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4589 /// span out of its own lane, hole closed, captions and clips alike.
4590 /// `false` for a bad index.
4591 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4592 let Some(members) = self.group_of(lane, idx) else {
4593 return false;
4594 };
4595 if !members.alone() {
4596 return self.delete_members(&members);
4597 }
4598 self.lift_sub(lane, idx)
4599 }
4600
4601 /// The one whole-group delete both doors land in: every member's own span
4602 /// cut out of its own lane and the hole closed there -- clips and
4603 /// captions by the same law -- and nothing else on another lane moves,
4604 /// which is what keeps one member's ripple from dragging another
4605 /// member's lane out from under it. One snapshot, one undo step.
4606 fn delete_members(&mut self, members: &Members) -> bool {
4607 self.snapshot();
4608 for &(l, i) in &members.clips {
4609 let c = self.lanes[l].clips[i];
4610 ripple(&mut self.lanes, &[l], c.start, c.frames());
4611 }
4612 // The captions go by the same law their clip siblings do -- the span
4613 // out of its own lane, the hole closed -- and not by the lift a
4614 // *lone* caption's delete is: deleted with its group, the words after
4615 // it slide up with everything else, or the lane the group emptied is
4616 // the one lane the delete left a hole in. `ripple` is the one
4617 // mechanism (it clears the span and shifts the rest, clips and
4618 // captions alike); a sub lane holds no clips, so its other list is
4619 // untouched.
4620 for &(l, i) in &members.subs {
4621 let s = self.lanes[l].subs[i];
4622 ripple(&mut self.lanes, &[l], s.start, s.frames);
4623 }
4624 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4625 true
4626 }
4627
4628 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4629 #[cfg(test)]
4630 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4631 self.lane(lane)
4632 }
4633
4634 /// How many undo steps are stacked: what the sweep asks so "one op, one
4635 /// snapshot" is a count and not a guess.
4636 #[cfg(test)]
4637 pub(crate) fn history_len(&self) -> usize {
4638 self.history.len()
4639 }
4640
4641 /// How many redo steps are stacked: what the sweep asks to check `undo`
4642 /// left a branch behind, and that a fresh edit clears it.
4643 #[cfg(test)]
4644 pub(crate) fn redo_len(&self) -> usize {
4645 self.redo.len()
4646 }
4647
4648 /// Every part of the project that an edit can change, as comparable
4649 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4650 #[cfg(test)]
4651 pub(crate) fn parts(&self) -> SweepParts {
4652 SweepParts(
4653 self.sources.len(),
4654 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4655 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4656 )
4657 }
4658
4659 /// Restore every lane from before the last successful edit -- the clips and
4660 /// the lane list both. `false` when there is nothing left to undo. Pushes
4661 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4662 /// forward again.
4663 pub fn undo(&mut self) -> bool {
4664 match self.history.pop() {
4665 Some(prev) => {
4666 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4667 true
4668 }
4669 None => false,
4670 }
4671 }
4672
4673 /// Restore every lane from before the last [`Project::undo`] -- the
4674 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4675 /// is nothing left to redo, which is also true after any fresh edit: a
4676 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4677 pub fn redo(&mut self) -> bool {
4678 match self.redo.pop() {
4679 Some(next) => {
4680 self.history.push(std::mem::replace(&mut self.lanes, next));
4681 true
4682 }
4683 None => false,
4684 }
4685 }
4686
4687 /// The project an export renders from: everything a render reads, with the
4688 /// undo history left behind. An export never walks the history back, and
4689 /// cloning it costs a copy of every lane list in the session -- this is
4690 /// taken on the UI thread, so it clones the lanes and the sources alone.
4691 pub fn export_snapshot(&self) -> Self {
4692 Self {
4693 sources: self.sources.clone(),
4694 lanes: self.lanes.clone(),
4695 eq: self.eq.clone(),
4696 color: self.color.clone(),
4697 transform: self.transform.clone(),
4698 history: Vec::new(),
4699 redo: Vec::new(),
4700 next_link: self.next_link,
4701 subtitles: self.subtitles.clone(),
4702 limiter: self.limiter,
4703 tone: self.tone,
4704 }
4705 }
4706
4707 /// Half-open `(source, start, end)` segments in *source* seconds, from
4708 /// `timeline_frame` to the end of the timeline -- the play list for the
4709 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4710 /// worker synthesises that many seconds of silence, which is what keeps the
4711 /// audio master clock counting across a hole instead of stalling on it.
4712 /// The first entry is partial when the position is mid-clip. Empty when the
4713 /// position is past the end or `fps` is not usable.
4714 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4715 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4716 }
4717
4718 /// [`segments_from`](Project::segments_from) for a named lane.
4719 pub fn lane_segments_from(
4720 &self,
4721 lane: Lane,
4722 timeline_frame: u32,
4723 fps: f64,
4724 ) -> Vec<(Option<usize>, f64, f64)> {
4725 if !(fps.is_finite() && fps > 0.0) {
4726 return Vec::new();
4727 }
4728 self.spans_from(lane, timeline_frame)
4729 .iter()
4730 .map(|span| match span.from {
4731 // A clip's window is in *source* seconds: where in the file it
4732 // reads from, which a delete before it never shifts. How many
4733 // source frames that is, is the span's own arithmetic -- at a
4734 // speed it is not the timeline length ([`Span::source_len`]).
4735 Some((source, in_frame)) => (
4736 Some(source),
4737 f64::from(in_frame) / fps,
4738 f64::from(in_frame + span.source_len()) / fps,
4739 ),
4740 // A gap has no file, so all it can say is how long it is.
4741 None => (None, 0.0, f64::from(span.len) / fps),
4742 })
4743 .collect()
4744 }
4745
4746 /// One play list per audio lane that *holds* something, in display order --
4747 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4748 /// what an export asks how many lanes it would have to mix.
4749 ///
4750 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4751 /// audio lane at all) still yields one all-gap list, so it plays silence
4752 /// against a master clock exactly as it did before there were lanes to
4753 /// count. Lanes with nothing on them are left out rather than mixed in as
4754 /// silence: they would cost a decode thread each and add zero.
4755 pub fn audio_segments_from(
4756 &self,
4757 timeline_frame: u32,
4758 fps: f64,
4759 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4760 self.audio_lanes()
4761 .into_iter()
4762 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4763 .collect()
4764 }
4765
4766 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4767 /// builds a play list for, in the same order. Public because everything
4768 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4769 /// which lane an mp4 export would copy -- has to read the very list the
4770 /// sound comes off, or the two answers drift apart (which is exactly how an
4771 /// `A2`-only project once exported silently, ledger).
4772 pub fn audio_lanes(&self) -> Vec<Lane> {
4773 let lanes: Vec<Lane> = self
4774 .lanes()
4775 .into_iter()
4776 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4777 .collect();
4778 match lanes.is_empty() {
4779 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4780 // no sound still plays silence against the master clock.
4781 true => vec![Lane::A1],
4782 false => lanes,
4783 }
4784 }
4785
4786 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4787 /// segments plays at, and how long the timeline gives it: the same lanes in
4788 /// the same order, one entry per segment, `None` for a segment at real time
4789 /// -- which is every segment of a project nobody has speeded, and the path
4790 /// the audio worker leaves bit-identical.
4791 ///
4792 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4793 /// the segment tuple is what every opener and a dozen tests speak, and a
4794 /// rate is not part of *which samples* a segment names.
4795 ///
4796 /// The seconds are what makes a resample exact: a segment's own window
4797 /// resolves to whole source frames, and dividing that by the rate would
4798 /// leave each clip a fraction of a frame short or long -- a drift that grows
4799 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4800 /// the last few samples of each segment instead, so the sound stays locked
4801 /// to the picture however many speeded cuts it walks through.
4802 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4803 self.audio_lanes()
4804 .into_iter()
4805 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4806 .collect()
4807 }
4808
4809 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4810 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4811 /// same walk, same `fps` refusal.
4812 pub fn lane_speeds_from(
4813 &self,
4814 lane: Lane,
4815 timeline_frame: u32,
4816 fps: f64,
4817 ) -> Vec<Option<Stretch>> {
4818 if !(fps.is_finite() && fps > 0.0) {
4819 return Vec::new();
4820 }
4821 self.spans_from(lane, timeline_frame)
4822 .iter()
4823 .map(|span| {
4824 (!span.speed.is_normal()).then(|| Stretch {
4825 step: span.speed.as_f64(),
4826 timeline_secs: f64::from(span.len) / fps,
4827 })
4828 })
4829 .collect()
4830 }
4831
4832 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4833 /// segments plays through: the same lanes in the same order, one entry per
4834 /// segment, `None` where the segment is a gap or its clip plays flat.
4835 ///
4836 /// A parallel list rather than a fourth element of the segment tuple: that
4837 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4838 /// and an effect is not part of *which samples* a segment names. A short
4839 /// list therefore means "flat from here on" rather than a length mismatch --
4840 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4841 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4842 self.audio_lanes()
4843 .into_iter()
4844 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4845 .collect()
4846 }
4847
4848 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4849 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4850 /// same walk, same `fps` refusal, so the two lists cannot come out different
4851 /// lengths.
4852 pub fn lane_eqs_from(
4853 &self,
4854 lane: Lane,
4855 timeline_frame: u32,
4856 fps: f64,
4857 ) -> Vec<Option<EqParams>> {
4858 if !(fps.is_finite() && fps > 0.0) {
4859 return Vec::new();
4860 }
4861 self.spans_from(lane, timeline_frame)
4862 .iter()
4863 // A span off a clip covers that clip's frames and no others, so its
4864 // own start names the clip -- the index a [`Span`] does not carry.
4865 .map(|span| {
4866 self.map(lane, span.start)
4867 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4868 })
4869 .collect()
4870 }
4871
4872 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
4873 /// segments plays through: the same lanes in the same order, one entry per
4874 /// segment, `None` where the segment is a gap or its clip has neither a
4875 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
4876 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
4877 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
4878 self.audio_lanes()
4879 .into_iter()
4880 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
4881 .collect()
4882 }
4883
4884 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
4885 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
4886 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
4887 if !(fps.is_finite() && fps > 0.0) {
4888 return Vec::new();
4889 }
4890 self.spans_from(lane, timeline_frame)
4891 .iter()
4892 .map(|span| {
4893 let (idx, _) = self.map(lane, span.start)?;
4894 let clip = self.lane(lane).get(idx)?;
4895 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
4896 // `span.len` is the clip's own remaining frames from
4897 // `span.start` on -- shorter than `clip.frames()` only
4898 // when this is the first span of a seek mid-clip.
4899 elapsed: clip.frames().saturating_sub(span.len),
4900 fade_in: clip.fade_in,
4901 fade_out: clip.fade_out,
4902 total: clip.frames(),
4903 })
4904 })
4905 .collect()
4906 }
4907
4908 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4909 /// it has decided it will succeed -- a refusal must not cost an undo step.
4910 /// Clears the redo stack: a fresh edit branches off from here, so whatever
4911 /// `undo` had left to redo is no longer where this edit leads back to.
4912 fn snapshot(&mut self) {
4913 if self.history.len() == HISTORY_CAP {
4914 self.history.remove(0);
4915 }
4916 self.history.push(self.lanes.clone());
4917 self.redo.clear();
4918 }
4919
4920 fn new_link(&mut self) -> u32 {
4921 let id = self.next_link;
4922 self.next_link = self.next_link.saturating_add(1);
4923 id
4924 }
4925
4926}
4927
4928/// The handle of every lane, in storage order -- the one definition of what
4929/// [`Lane::ord`] counts.
4930fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4931 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4932 lanes
4933 .iter()
4934 .map(|l| match l.kind {
4935 LaneKind::Video => {
4936 video += 1;
4937 Lane::new(LaneKind::Video, video - 1)
4938 }
4939 LaneKind::Audio => {
4940 audio += 1;
4941 Lane::new(LaneKind::Audio, audio - 1)
4942 }
4943 LaneKind::Subtitle => {
4944 subtitle += 1;
4945 Lane::new(LaneKind::Subtitle, subtitle - 1)
4946 }
4947 })
4948 .collect()
4949}
4950
4951/// The one law a caption re-time scales by: frame `f` moves about the held
4952/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4953/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4954/// [`TimelineMap`] piece from this single answer so the two cannot drift
4955/// apart by a frame the way they once did.
4956fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4957 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4958 .round()
4959 .clamp(0., f64::from(u32::MAX)) as u32
4960}
4961
4962/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4963/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4964/// a speed cannot be applied twice or forgotten in one of them.
4965fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4966 // Clamped inside the clip's own range: rounding at a slow rate can put the
4967 // last timeline frame of a clip a frame past its out-point, and a source
4968 // frame outside the range is one the next clip owns.
4969 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4970}
4971
4972/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4973/// Binary search: the sorted-disjoint invariant is what makes it legal.
4974fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4975 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4976 (frame < clips[idx].end()).then_some(idx)
4977}
4978
4979/// The empty stretch of `clips` covering `frame`, as `(start, len)` -- `None`
4980/// when `frame` is inside a clip, or past the last one. Sorted-disjoint
4981/// invariant like [`at`]: the first clip whose start is past `frame` is the
4982/// far wall, and the last one that ends at or before `frame` (or the
4983/// timeline's own head, `0`, when there is none) is the near one.
4984fn gap(clips: &[Clip], frame: u32) -> Option<(u32, u32)> {
4985 if at(clips, frame).is_some() {
4986 return None;
4987 }
4988 let idx = clips.partition_point(|c| c.start <= frame);
4989 let next = clips.get(idx)?;
4990 let start = idx.checked_sub(1).map_or(0, |i| clips[i].end());
4991 Some((start, next.start - start))
4992}
4993
4994/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4995/// there would cut in two. A placement's own first frame is not inside it.
4996fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4997 let idx = at(clips, frame)?;
4998 // ...and, on a speeded clip, one its rate can actually address
4999 // ([`Speed::split_at`]): a cut between two showings of one source frame
5000 // would leave halves that no longer add up to the clip that was cut.
5001 (frame > clips[idx].start)
5002 .then_some(idx)
5003 .filter(|&idx| split_source(&clips[idx], frame).is_some())
5004}
5005
5006/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
5007/// rate cannot address that frame.
5008fn split_source(c: &Clip, frame: u32) -> Option<u32> {
5009 c.speed
5010 .split_at(c.len(), frame - c.start)
5011 .map(|src| c.in_frame + src)
5012}
5013
5014/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
5015/// rejoin: they must touch there, and be consecutive frames of one source.
5016fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
5017 let idx = clips.iter().position(|c| c.end() == frame)?;
5018 let next = clips.get(idx + 1)?;
5019 let joined = clips[idx].len() + next.len();
5020 (next.start == frame
5021 && next.source == clips[idx].source
5022 && next.in_frame == clips[idx].out_frame
5023 // ...at one rate, and one that puts the rejoined clip back in exactly
5024 // the room the two took up: what a split could have produced, which is
5025 // all this undoes.
5026 && next.speed == clips[idx].speed
5027 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
5028 .then_some(idx)
5029}
5030
5031/// The lane invariant: sorted by `start`, no two placements overlapping, no
5032/// empty placement. Checked at every constructor and asserted after every
5033/// mutation -- the offset model is only tractable while it holds.
5034/// The one thing an equalizer setting may not be: a value the text format
5035/// cannot write and read back as itself. Checked wherever params come in, so
5036/// what an edit produces is always what a save writes and a load reads.
5037fn finite(params: &EqParams) -> bool {
5038 params
5039 .bands
5040 .iter()
5041 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
5042}
5043
5044/// The same for a colour grade: [`crate::color`] itself falls back to identity
5045/// on a non-finite value, but a value that cannot be written and read back as
5046/// itself has no business reaching the model.
5047fn color_finite(p: &ColorParams) -> bool {
5048 p.brightness.is_finite()
5049 && p.contrast.is_finite()
5050 && p.saturation.is_finite()
5051 && p.tint.is_finite()
5052}
5053
5054/// The same for a transform: [`crate::scale`] clamps a non-finite value to
5055/// identity at read time, but a value that cannot round-trip has no business
5056/// reaching the model.
5057fn transform_finite(p: &TransformParams) -> bool {
5058 p.pos_x.is_finite()
5059 && p.pos_y.is_finite()
5060 && p.scale.is_finite()
5061 && p.rotate.is_finite()
5062 && p.crop_l.is_finite()
5063 && p.crop_r.is_finite()
5064 && p.crop_t.is_finite()
5065 && p.crop_b.is_finite()
5066}
5067
5068fn sorted_disjoint(clips: &[Clip]) -> bool {
5069 clips.iter().all(|c| c.out_frame > c.in_frame)
5070 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
5071}
5072
5073/// The very same invariant on a subtitle lane, in that lane's own two units:
5074/// sorted by `start`, no two placements overlapping, no empty placement at
5075/// either end. Asserted after every mutation, exactly as its twin is.
5076fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
5077 subs.iter()
5078 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
5079 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
5080}
5081
5082/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
5083/// the one conversion between a lane's clock and a cue's, and `0` for a rate
5084/// that is not one (every caller of this has already refused such a rate).
5085fn us_of(frames: i64, fps: f64) -> i64 {
5086 match fps.is_finite() && fps > 0.0 {
5087 true => ((frames as f64) / fps * 1e6).round() as i64,
5088 false => 0,
5089 }
5090}
5091
5092/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5093/// dropping what is inside the hole, splitting what straddles it and trimming
5094/// what overlaps an edge. The windows follow the cut by proportion
5095/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5096fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5097 let mut out = Vec::with_capacity(subs.len() + 1);
5098 for s in subs.drain(..) {
5099 if s.end() <= start || s.start >= end {
5100 out.push(s);
5101 continue;
5102 }
5103 if s.start < start {
5104 out.push(SubClip {
5105 frames: start - s.start,
5106 out_us: s.window_at(start),
5107 // Both pieces lose the group id, for [`clear`]'s reason: one
5108 // id on two boxes of one lane is the one thing it may never
5109 // mean.
5110 link: None,
5111 ..s
5112 });
5113 }
5114 if s.end() > end {
5115 out.push(SubClip {
5116 start: end,
5117 frames: s.end() - end,
5118 in_us: s.window_at(end),
5119 link: None,
5120 ..s
5121 });
5122 }
5123 }
5124 *subs = out;
5125}
5126
5127/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5128/// `len`, splitting a placement that straddles `at` so the two halves end up on
5129/// either side of the hole. A `len` of 0 is that split alone, which is what a
5130/// [`Project::split`] over a subtitle lane is.
5131fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5132 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5133 let s = subs[idx];
5134 let cut = s.window_at(at);
5135 subs[idx] = SubClip {
5136 frames: at - s.start,
5137 out_us: cut,
5138 link: None,
5139 ..s
5140 };
5141 subs.insert(
5142 idx + 1,
5143 SubClip {
5144 start: at,
5145 frames: s.end() - at,
5146 in_us: cut,
5147 link: None,
5148 ..s
5149 },
5150 );
5151 }
5152 for s in subs.iter_mut().filter(|s| s.start >= at) {
5153 s.start += len;
5154 }
5155}
5156
5157/// [`joinable`] for a subtitle lane: the first of the two placements a
5158/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5159/// produced and nothing else -- they touch on the timeline, they read the same
5160/// track, and the second one's window carries on where the first's stopped.
5161fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5162 let idx = subs.iter().position(|s| s.end() == frame)?;
5163 let next = subs.get(idx + 1)?;
5164 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5165 .then_some(idx)
5166}
5167
5168/// How far one `edge` of the caption at `idx` may travel against its own lane's
5169/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5170/// rate, which a caption *following* a group's trim does not have to be exact
5171/// about -- its own walls, its own one surviving frame, and nothing that needs
5172/// a clock.
5173fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5174 let s = &subs[idx];
5175 match edge {
5176 Edge::Start => (
5177 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5178 s.end() - 1,
5179 ),
5180 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5181 }
5182}
5183
5184/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5185/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5186/// forwards and backwards. The caption a group's trim is carrying has no rate
5187/// of its own and needs none: what one frame of it is worth in microseconds is
5188/// the window it already shows over the frames it already takes.
5189fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5190 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5191 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5192 match edge {
5193 Edge::Start => {
5194 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5195 s.frames = s.end() - to;
5196 s.start = to;
5197 }
5198 Edge::End => {
5199 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5200 s.frames = to - s.start;
5201 }
5202 }
5203 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5204}
5205
5206/// The grouping invariant, checked in release at [`Project::from_parts`] and
5207/// asserted by the tests after every edit: a link id names **at most one**
5208/// placement per lane -- a clip on a media lane or a caption on a subtitle
5209/// one, whichever carries it. That is all "these move together" can mean now
5210/// that a group is assembled by hand: the members keep their own spans and
5211/// their own offsets, and what binds them is the id alone.
5212///
5213/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5214/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5215/// placements of one group may cover different frames -- the offset-preserving
5216/// group a hand builds with [`Project::group_all`], which a drag moves by one
5217/// delta rather than by one span.
5218///
5219/// A link no other lane carries is legal and is not an error: lifting one half
5220/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5221/// timeline has to load again.
5222/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5223/// asked by the sweep suite's universal law.
5224#[cfg(test)]
5225pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5226 links_are_consistent(&p.lanes)
5227}
5228
5229fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5230 let handles = handles(lanes);
5231 for (data, lane) in lanes.iter().zip(&handles) {
5232 for (i, c) in data.clips.iter().enumerate() {
5233 let Some(id) = c.link else { continue };
5234 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5235 return Err(
5236 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5237 );
5238 }
5239 }
5240 // ...and the same for the captions, in their own list on the same lane:
5241 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5242 // id could be doubled on.
5243 for (i, s) in data.subs.iter().enumerate() {
5244 let Some(id) = s.link else { continue };
5245 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5246 return Err(format!(
5247 "link {id} names two captions in the {} lane",
5248 lane.label()
5249 )
5250 .into());
5251 }
5252 }
5253 }
5254 Ok(())
5255}
5256
5257/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5258/// it go, one straddling it is split in two, one overlapping an edge is
5259/// trimmed. Source frames follow the trim, so what is left plays what it always
5260/// played. Leaves the lane sorted and disjoint.
5261///
5262/// A piece the hole cut is no longer the take its group id names -- and both
5263/// halves of a straddled placement carrying that id would be the same id twice
5264/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5265fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5266 let mut out = Vec::with_capacity(clips.len() + 1);
5267 for c in clips.drain(..) {
5268 // Disjoint from the hole: untouched.
5269 if c.end() <= start || c.start >= end {
5270 out.push(c);
5271 continue;
5272 }
5273 // The head that survives in front of the hole -- as much source as fits
5274 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5275 // which at real time is that room itself. Never *more*: a head that
5276 // outgrew its room would reach into the hole it is being cut out of,
5277 // which is exactly the overlap a slow clip punched at a frame its rate
5278 // cannot address used to leave (at 0.25x a single source frame is four
5279 // timeline frames, and three frames of room hold none of it). `None`
5280 // there means no remainder at all, and the piece simply goes.
5281 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5282 && c.start < start
5283 {
5284 out.push(Clip {
5285 fade_in: 0,
5286 fade_out: 0,
5287 transition_out: 0,
5288 out_frame: c.in_frame + keep.min(c.len()),
5289 link: None,
5290 ..c
5291 });
5292 }
5293 // ...and the tail behind it, which keeps reading up to where it would
5294 // have: measured from its out-point for the head's reason, so what it
5295 // occupies still ends where the whole clip did -- and dropped whole on
5296 // the same `None`.
5297 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5298 && c.end() > end
5299 {
5300 out.push(Clip {
5301 fade_in: 0,
5302 fade_out: 0,
5303 transition_out: 0,
5304 start: end,
5305 in_frame: c.out_frame - keep.min(c.len()),
5306 link: None,
5307 ..c
5308 });
5309 }
5310 }
5311 *clips = out;
5312}
5313
5314/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5315/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5316/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5317/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5318/// the caller.
5319fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5320 for &i in on {
5321 let clips = &mut lanes[i].clips;
5322 clear(clips, at, at + len);
5323 for c in clips.iter_mut().filter(|c| c.start >= at) {
5324 c.start -= len;
5325 }
5326 debug_assert!(sorted_disjoint(clips));
5327 // The subtitle lanes close the hole with everything else: a caption
5328 // left standing where the picture it belongs to was cut out is the
5329 // desync a lane model exists to make impossible.
5330 let subs = &mut lanes[i].subs;
5331 sub_clear(subs, at, at + len);
5332 for s in subs.iter_mut().filter(|s| s.start >= at) {
5333 s.start -= len;
5334 }
5335 debug_assert!(subs_sorted_disjoint(subs));
5336 }
5337}
5338
5339/// Every lane, as the index list the two above take: what "the whole timeline"
5340/// is spelled as, and the scope [`Project::ripple_delete`] and
5341/// [`Project::split`] have always had.
5342fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5343 (0..lanes.len()).collect()
5344}
5345
5346/// A caller's region list as a batch may use it: sorted by start, empty entries
5347/// dropped, and touching or overlapping entries merged into one.
5348///
5349/// Overlapping regions are the one thing a batch cannot take -- cutting the
5350/// second would cut frames the first already moved -- and a detector handing
5351/// back two that touch means one silence, not two cuts. Merged rather than
5352/// refused: this is arithmetic on a preview, not a user's mistake.
5353fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5354 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5355 sorted.sort_by_key(|&(at, _)| at);
5356 let mut out: Vec<(u32, u32)> = Vec::new();
5357 for (at, len) in sorted {
5358 let end = at.saturating_add(len);
5359 match out.last_mut() {
5360 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5361 _ => out.push((at, len)),
5362 }
5363 }
5364 out
5365}
5366
5367/// Slides everything from `at` on later by `len`, splitting a placement that
5368/// straddles `at` so the two halves end up on either side of the hole. The
5369/// insert half of a rippling paste. The two halves lose the group id for the
5370/// reason [`clear`] gives.
5371fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5372 if let Some(idx) = splittable(clips, at) {
5373 let mut tail = clips[idx];
5374 // The cut in *source* frames, at the clip's own rate. `splittable` has
5375 // already refused a frame the rate cannot address, which is why
5376 // [`Project::paste`] refuses one too rather than opening room inside a
5377 // clip that cannot be cut there.
5378 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5379 tail.start = at;
5380 tail.link = None;
5381 clips[idx].out_frame = tail.in_frame;
5382 clips[idx].link = None;
5383 clips.insert(idx + 1, tail);
5384 }
5385 for c in clips.iter_mut().filter(|c| c.start >= at) {
5386 c.start += len;
5387 }
5388}
5389
5390/// Absolute, symlink-resolved when the file is reachable; the path as given
5391/// when it is not -- an unreadable path still deserves an index, it simply
5392/// dedups by spelling.
5393pub(crate) fn canonical(path: &Path) -> PathBuf {
5394 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5395}
5396
5397#[cfg(test)]
5398mod tests {
5399 use super::*;
5400
5401 const FPS: f64 = 30.0;
5402 /// Never opened -- `Project` is pure data, so a path that does not exist is
5403 /// simply a path that dedups by spelling.
5404 const FILE: &str = "/nonexistent/a.mp4";
5405 const FILE2: &str = "/nonexistent/b.mp4";
5406
5407 /// A contiguous placement, group id ignored: what most assertions compare.
5408 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5409 Clip {
5410 fade_in: 0,
5411 fade_out: 0,
5412 transition_out: 0,
5413 start,
5414 in_frame,
5415 out_frame,
5416 source,
5417 link: None,
5418 eq: None,
5419 color: None,
5420 transform: None,
5421 fit: FitPolicy::default(),
5422 speed: Speed::NORMAL,
5423 }
5424 }
5425
5426 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5427 /// apart -- which is what makes the table's dedup and its prune visible.
5428 fn band_at(n: u32) -> EqParams {
5429 EqParams {
5430 bands: vec![crate::eq::Band {
5431 freq_hz: 1000.0,
5432 gain_db: f64::from(n) as f32 * 1.5,
5433 q: 0.707,
5434 kind: crate::eq::BandKind::Peak,
5435 }],
5436 }
5437 }
5438
5439 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5440 /// for the colour table.
5441 fn grade_at(n: u32) -> ColorParams {
5442 ColorParams {
5443 brightness: f64::from(n) as f32 * 0.05,
5444 ..Default::default()
5445 }
5446 }
5447
5448 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5449 /// twin for the transform table.
5450 fn transform_at(n: u32) -> TransformParams {
5451 TransformParams {
5452 pos_x: f64::from(n) as f32 * 0.05,
5453 ..Default::default()
5454 }
5455 }
5456
5457 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5458 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5459 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5460 }
5461
5462 /// Every lane with its group ids blanked, for comparing shape.
5463 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5464 p.lanes()
5465 .into_iter()
5466 .map(|l| {
5467 p.lane(l)
5468 .iter()
5469 .map(|c| Clip { link: None, ..*c })
5470 .collect()
5471 })
5472 .collect()
5473 }
5474
5475 /// The *source frame* every timeline frame reads, per lane -- the traversal
5476 /// a player performs. Deliberately not the clip index: a split changes which
5477 /// clip a frame belongs to, and nothing else.
5478 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5479 (0..p.timeline_frames() + 2)
5480 .map(|f| {
5481 p.lanes()
5482 .into_iter()
5483 .map(|l| p.map(l, f).map(|(_, source)| source))
5484 .collect()
5485 })
5486 .collect()
5487 }
5488
5489 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5490 /// fixture. Built through `split` so the constructor path is exercised too.
5491 fn three() -> Project {
5492 let mut p = Project::single(FILE, 9);
5493 assert!(p.split(3));
5494 assert!(p.split(5));
5495 assert_eq!(
5496 shape(&p),
5497 [
5498 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5499 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5500 ]
5501 );
5502 p
5503 }
5504
5505 #[test]
5506 fn single_is_the_whole_file_on_both_lanes() {
5507 let p = Project::single(FILE, 150);
5508 assert_eq!(p.clips().len(), 1);
5509 assert_eq!(p.lane(Lane::A1).len(), 1);
5510 assert_eq!(p.timeline_frames(), 150);
5511 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5512 // grouped: video and audio carry the same link
5513 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5514 assert!(p.clips()[0].link.is_some());
5515 // degenerate mapping: timeline == source
5516 assert_eq!(p.map_timeline(0), Some((0, 0)));
5517 assert_eq!(p.map_timeline(149), Some((0, 149)));
5518 assert_eq!(p.map_timeline(150), None);
5519 // never-empty invariant survives a bogus frame count
5520 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5521 }
5522
5523 #[test]
5524 fn split_cuts_every_lane_and_regroups_it_back() {
5525 let mut p = Project::single(FILE, 9);
5526 let before = traversal(&p);
5527 let before_shape = shape(&p);
5528
5529 assert!(p.split(4));
5530 for l in p.lanes() {
5531 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5532 }
5533 // The two sides are two groups, one per side, matching across the lanes.
5534 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5535 assert_eq!(v[0].link, a[0].link);
5536 assert_eq!(v[1].link, a[1].link);
5537 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5538 // A split changes no mapping, in either lane.
5539 assert_eq!(traversal(&p), before, "a split moves nothing");
5540
5541 assert!(p.regroup(4), "the inverse rejoins them");
5542 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5543 assert_eq!(traversal(&p), before);
5544 assert_eq!(
5545 p.lane(Lane::V1)[0].link,
5546 p.lane(Lane::A1)[0].link,
5547 "and the rejoined clip is one group again"
5548 );
5549 }
5550
5551 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
5552 /// the very first frame of a fade-in, unity at its last, equal-power
5553 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
5554 /// at all.
5555 #[test]
5556 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
5557 let f = Fade {
5558 elapsed: 0,
5559 fade_in: 10,
5560 fade_out: 10,
5561 total: 40,
5562 };
5563 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
5564 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
5565 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
5566 assert!(
5567 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
5568 "equal-power midpoint is sin(pi/4)"
5569 );
5570 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
5571 // The fade-out is the same curve, mirrored, counting down from the
5572 // clip's end: unity at the frame the ramp starts, the same
5573 // equal-power midpoint, and -- since `total` itself is one past the
5574 // clip's last valid frame -- the very last frame is one step short of
5575 // the silence a fade-in's own frame `0` lands on exactly.
5576 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
5577 assert!(
5578 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
5579 "the fade-out's own equal-power midpoint"
5580 );
5581 assert!(
5582 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
5583 "one step short of silence at the clip's last playable frame"
5584 );
5585 }
5586
5587 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
5588 /// not adjacent, and otherwise sets the shared edge's fades and nothing
5589 /// else.
5590 #[test]
5591 fn crossfade_only_joins_adjacent_audio_clips() {
5592 let mut p = Project::single(FILE, 20);
5593 assert!(p.split(10));
5594 assert!(
5595 !p.crossfade(Lane::V1, 0, 5),
5596 "video is not an audio lane"
5597 );
5598 assert!(
5599 !p.crossfade(Lane::A1, 1, 5),
5600 "there is no clip after idx 1"
5601 );
5602 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
5603 let a = p.lane(Lane::A1);
5604 assert_eq!(a[0].fade_out, 5);
5605 assert_eq!(a[1].fade_in, 5);
5606 assert_eq!(a[0].fade_in, 0);
5607 assert_eq!(a[1].fade_out, 0);
5608
5609 // A gap between two clips is not adjacency, even on an audio lane.
5610 let mut p2 = Project::single(FILE, 1);
5611 let a2 = p2.add_lane(LaneKind::Audio);
5612 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
5613 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5614 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
5615 }
5616
5617 /// The rule [`Project::write_split`] follows for the edge the razor makes:
5618 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
5619 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
5620 /// mirror image.
5621 #[test]
5622 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
5623 let mut p = Project::single(FILE, 20);
5624 assert!(p.set_fade_in(Lane::V1, 0, 15));
5625 assert!(p.set_fade_out(Lane::V1, 0, 15));
5626 assert!(p.split(5));
5627 let v = p.lane(Lane::V1);
5628 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
5629 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
5630 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
5631 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
5632 }
5633
5634 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
5635 /// no successor, and two clips that do not touch, and otherwise clamps
5636 /// the dissolve to the shorter of the two clips it spans.
5637 #[test]
5638 fn set_transition_out_only_dissolves_adjacent_video_clips() {
5639 let mut p = Project::single(FILE, 20);
5640 assert!(p.split(15), "a short 5-frame tail to clamp against");
5641 assert!(
5642 !p.set_transition_out(Lane::A1, 0, 5),
5643 "audio is not a video lane"
5644 );
5645 assert!(
5646 !p.set_transition_out(Lane::V1, 1, 5),
5647 "there is no clip after idx 1"
5648 );
5649 assert!(
5650 p.set_transition_out(Lane::V1, 0, 100),
5651 "the two halves are adjacent"
5652 );
5653 assert_eq!(
5654 p.transition_out_of(Lane::V1, 0),
5655 5,
5656 "clamped to the shorter neighbour's 5 frames"
5657 );
5658
5659 // A gap between two clips is not adjacency, even on the video lane.
5660 let mut p2 = Project::single(FILE, 1);
5661 let v2 = p2.add_lane(LaneKind::Video);
5662 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
5663 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5664 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
5665 }
5666
5667 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
5668 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
5669 /// only the half that kept the clip's original *end* keeps the dissolve,
5670 /// re-clamped to its own now-shorter length; the head the cut just made
5671 /// has no successor to dissolve into and starts flat.
5672 #[test]
5673 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
5674 let mut p = Project::single(FILE, 20);
5675 assert!(
5676 !p.set_transition_out(Lane::V1, 0, 0),
5677 "one clip on the lane, no successor to dissolve into yet"
5678 );
5679 // Give the clip a dissolve by hand, then cut it in two.
5680 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
5681 assert!(p.split(5));
5682 let v = p.lane(Lane::V1);
5683 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
5684 assert_eq!(
5685 v[1].transition_out, 15,
5686 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
5687 );
5688 }
5689
5690 /// The music video's own path: the take comes apart into halves that carry
5691 /// ids of their own, one undo puts it back, and two clips over the same
5692 /// frames become one take again by hand.
5693 #[test]
5694 fn a_take_comes_apart_and_goes_back_together() {
5695 let mut p = Project::single(FILE, 9);
5696 let one = p.clips()[0].link.expect("a fresh project is one take");
5697 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5698
5699 // A third lane in the same group -- and the merge case with it: a
5700 // placement is in no group, and grouping it in leaves *one* group.
5701 let v2 = p.add_lane(LaneKind::Video);
5702 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5703 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5704 p.group(Lane::V1, 0, v2, 0)
5705 .expect("the same frames, one lane over");
5706 let id = p.clips()[0].link.expect("still a group");
5707 assert!(
5708 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5709 "one id over the three, not two groups sharing a span"
5710 );
5711 links_are_consistent(&p.lanes).expect("one id, one span");
5712
5713 // Detached by the sound: every half of the group, not only the two.
5714 assert!(p.ungroup(Lane::A1, 0));
5715 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5716 assert!(
5717 ids.iter().all(Option::is_some),
5718 "a half keeps an id of its own"
5719 );
5720 assert!(
5721 ids.iter()
5722 .enumerate()
5723 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5724 "and no two halves are the same group any more: {ids:?}"
5725 );
5726 links_are_consistent(&p.lanes).expect("a lone id is legal");
5727
5728 // One snapshot for the whole detach.
5729 assert!(p.undo());
5730 assert!(
5731 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5732 "one undo puts the whole group back"
5733 );
5734
5735 // And back together by hand: the two the pointer named, and only them.
5736 assert!(p.ungroup(Lane::V1, 0));
5737 p.group(Lane::V1, 0, Lane::A1, 0)
5738 .expect("both cover [0, 9)");
5739 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5740 assert_ne!(
5741 p.lane(v2)[0].link,
5742 p.lane(Lane::V1)[0].link,
5743 "the third half stayed detached"
5744 );
5745 links_are_consistent(&p.lanes).expect("one id, one span");
5746 }
5747
5748 /// What a group may not be, and what a detach has nothing to take apart --
5749 /// none of which may cost an undo step.
5750 #[test]
5751 fn a_group_is_one_span_and_one_clip_per_lane() {
5752 let mut p = three();
5753 let before = shape(&p);
5754 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5755
5756 assert!(
5757 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5758 "two clips of one lane are never one take"
5759 );
5760 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5761 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5762 assert!(
5763 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5764 "{spans}"
5765 );
5766 assert!(
5767 spans.contains("trim them to matching bounds first"),
5768 "{spans}"
5769 );
5770 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5771
5772 // A half nothing else is grouped with is already detached, a placement
5773 // is in no group at all, and an index that is not there has nothing to
5774 // detach either.
5775 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5776 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5777 assert!(p.lift(Lane::A1, 0));
5778 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5779 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5780
5781 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5782 assert!(p.undo());
5783 assert!(p.undo());
5784 assert_eq!(shape(&p), before);
5785 }
5786
5787 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5788 /// scene under the cursor, measured the way a viewer would -- the source
5789 /// frame playing at the playhead is the same frame after the write, at
5790 /// every playhead position the re-rate can catch one.
5791 #[test]
5792 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5793 let caption = |start: u32, frames: u32| SubClip {
5794 start,
5795 frames,
5796 track: 0,
5797 in_us: 0,
5798 out_us: i64::from(frames) * 1_000_000,
5799 link: None,
5800 };
5801 let track = || SubtitleTrack {
5802 path: FILE.into(),
5803 track: None,
5804 language: "eng".into(),
5805 name: String::new(),
5806 label: "eng".into(),
5807 cues: Vec::new(),
5808 bitmap: false,
5809 refused: None,
5810 };
5811 // A group of a 300-frame clip and a caption offset 30 frames into it.
5812 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5813 let s1 = p.add_lane(LaneKind::Subtitle);
5814 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5815 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5816
5817 // The frame playing at `at`: which clip, and which source frame of it.
5818 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5819 p.span_at(Lane::V1, at)
5820 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5821 };
5822
5823 // Inside the held clip: the source frame under the playhead is the
5824 // same one after the re-rate, at 2x and at half speed both.
5825 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5826 let at = 120;
5827 let before = playing(&p, at).expect("a clip under the playhead");
5828 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5829 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5830 .expect("room for it");
5831 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5832 assert_eq!(before, after, "{what}: the same source frame plays");
5833 // ...and the write itself is untouched by the question.
5834 assert!(p.undo(), "{what}: one step back");
5835 }
5836
5837 // Past the group -- the clip ends at 300 and the caption at 270, so
5838 // from 300 on nothing is re-timed under the playhead: unmoved.
5839 for at in [300u32, 301, 1_000] {
5840 assert_eq!(
5841 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5842 Some(at),
5843 "at {at}: outside every member, unmoved"
5844 );
5845 }
5846 // The boundary is exact: the held clip's own last frame (299) maps
5847 // to its new one (149 -- the last frame inside [0, 150), where the
5848 // shrunken clip's last source frame plays), and its first stays put.
5849 assert_eq!(
5850 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5851 Some(149)
5852 );
5853 assert_eq!(
5854 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5855 Some(0)
5856 );
5857 // A spot the caption shares with the clip maps by the clip (it is
5858 // what is *playing* there): the held clip's own proportion, which on
5859 // this fixture is also its head.
5860 assert_eq!(
5861 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5862 Some(45),
5863 "the clip under the caption owns the spot"
5864 );
5865 }
5866
5867 /// A playhead inside another clip member of the group: that member keeps
5868 /// its own head, so the mapping is by its proportion and not the held
5869 /// clip's -- and the frame under the cursor is still the frame that was.
5870 #[test]
5871 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5872 let mut p = Project::single(FILE, 300);
5873 // A second clip, grouped with the first but starting 300 later: the
5874 // head the group shares and its own differ by exactly that.
5875 let v2 = p.add_lane(LaneKind::Video);
5876 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5877 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5878 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5879
5880 let at = 450; // inside the second member, 150 past its head
5881 let before = p.span_at(v2, at).and_then(|s| s.from);
5882 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5883 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5884 .expect("room for it");
5885 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5886 assert_eq!(before, after, "the second member's own frame plays");
5887 // ...and the mapping itself: 150 past its head halves, the head stays.
5888 assert_eq!(mapped, Some(375));
5889 }
5890
5891 /// The link counter a load seeds sits past every id the file names,
5892 /// captions included: a hand-grouped caption may carry the highest id there
5893 /// is, and a counter that read the clips alone would hand it to the next
5894 /// group that asked -- silently grouping the caption with clips it never
5895 /// met.
5896 #[test]
5897 fn the_link_counter_sits_past_a_caption_only_id() {
5898 let track = || SubtitleTrack {
5899 path: FILE.into(),
5900 track: None,
5901 language: "eng".into(),
5902 name: String::new(),
5903 label: "eng".into(),
5904 cues: Vec::new(),
5905 bitmap: false,
5906 refused: None,
5907 };
5908 let mut p = Project::single(FILE, 9);
5909 p.add_lane(LaneKind::Subtitle);
5910 let caption = SubClip {
5911 start: 0,
5912 frames: 6,
5913 track: 0,
5914 in_us: 0,
5915 out_us: 6_000_000,
5916 // The highest id in the file, and only a caption carries it.
5917 link: Some(1),
5918 };
5919 let mut p = p
5920 .with_subtitles(vec![track()])
5921 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5922 .expect("a caption may carry the file's highest id");
5923
5924 // A new group on lanes the caption is not on mints the next id -- which
5925 // must not be the caption's.
5926 let v2 = p.add_lane(LaneKind::Video);
5927 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5928 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5929 .expect("the clips group");
5930 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5931 assert_ne!(
5932 minted,
5933 1,
5934 "the caption's id is not re-issued to clips"
5935 );
5936 assert_eq!(
5937 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5938 Some(1),
5939 "the caption keeps its own group"
5940 );
5941 assert!(links_are_consistent(&p.lanes).is_ok());
5942 }
5943
5944 /// A rate re-times the caption members of the group by the ratio it gives
5945 /// the held clip: the span on the timeline compresses about the held clip's
5946 /// head, the words' own window untouched -- and one undo puts it back.
5947 #[test]
5948 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5949 let caption = |start: u32, frames: u32| SubClip {
5950 start,
5951 frames,
5952 track: 0,
5953 in_us: 0,
5954 out_us: i64::from(frames) * 1_000_000,
5955 link: None,
5956 };
5957 let track = || SubtitleTrack {
5958 path: FILE.into(),
5959 track: None,
5960 language: "eng".into(),
5961 name: String::new(),
5962 label: "eng".into(),
5963 cues: Vec::new(),
5964 bitmap: false,
5965 refused: None,
5966 };
5967 let grouped = || {
5968 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5969 let s1 = p.add_lane(LaneKind::Subtitle);
5970 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5971 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5972 (p, s1)
5973 };
5974
5975 // An aligned take, doubled: the caption plays in half the frames.
5976 let (mut p, s1) = grouped();
5977 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5978 .expect("room for it");
5979 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5980 let s = p.sub_lane(s1)[0];
5981 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5982 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5983 assert!(links_are_consistent(&p.lanes).is_ok());
5984 assert!(p.undo());
5985 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5986
5987 // An offset group, slowed to half: the caption's *offset from the held
5988 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5989 // 0.5x, and still ends where the clip does.
5990 let (mut p, s1) = grouped();
5991 p.lift_sub(s1, 0);
5992 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5993 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5994 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5995 .expect("room for it");
5996 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5997 let s = p.sub_lane(s1)[0];
5998 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5999 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
6000
6001 // A stretch that runs the caption into its neighbour is refused, by
6002 // lane and frame, and costs no undo step.
6003 let (mut p, s1) = grouped();
6004 p.lift_sub(s1, 0);
6005 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6006 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
6007 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6008 let history = p.history.len();
6009 let err = p
6010 .set_speed(Lane::V1, 0, Speed::from_permille(500))
6011 .unwrap_err()
6012 .to_string();
6013 assert!(
6014 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
6015 "{err}"
6016 );
6017 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
6018 }
6019
6020 /// The silence scan's speed-up re-times the captions on a scoped lane with
6021 /// everything else: the piece inside the region plays in the region's new
6022 /// frames, and what sits behind the region slides up with the clips.
6023 #[test]
6024 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
6025 let caption = |start: u32, frames: u32| SubClip {
6026 start,
6027 frames,
6028 track: 0,
6029 in_us: 0,
6030 out_us: i64::from(frames) * 1_000_000,
6031 link: None,
6032 };
6033 let track = || SubtitleTrack {
6034 path: FILE.into(),
6035 track: None,
6036 language: "eng".into(),
6037 name: String::new(),
6038 label: "eng".into(),
6039 cues: Vec::new(),
6040 bitmap: false,
6041 refused: None,
6042 };
6043 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6044 let s1 = p.add_lane(LaneKind::Subtitle);
6045 // Words over the region [30, 60) and words behind it.
6046 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6047 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
6048
6049 // The region [30, 60) plays at 4x: 30 frames become 8, everything
6050 // behind slides up 22.
6051 // The scope is what the card's Take row says, caption lane included.
6052 p.speed_regions(
6053 &[(30, 30)],
6054 Speed::from_permille(4000),
6055 &[Lane::V1, Lane::A1, s1],
6056 )
6057 .expect("the region speeds up");
6058 let subs = p.sub_lane(s1);
6059 assert_eq!(
6060 (subs[0].start, subs[0].frames),
6061 (30, 8),
6062 "the piece inside plays in the region's new frames"
6063 );
6064 assert_eq!(
6065 (subs[1].start, subs[1].frames),
6066 (38, 30),
6067 "the piece behind slides up by what the region gave back"
6068 );
6069 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
6070 }
6071
6072 /// [`Project::speeded_playhead`]'s caption arm fires only when the
6073 /// playhead is inside a caption member and outside every clip member --
6074 /// a shape every other fixture avoids by keeping its caption inside the
6075 /// held clip. Here the caption overhangs the clip's tail, and the
6076 /// playhead standing in that overhang is answered by the caption's own
6077 /// piece: it scales about the held clip's head by the held clip's own
6078 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
6079 #[test]
6080 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
6081 let caption = |start: u32, frames: u32| SubClip {
6082 start,
6083 frames,
6084 track: 0,
6085 in_us: 0,
6086 out_us: i64::from(frames) * 1_000_000,
6087 link: None,
6088 };
6089 let track = || SubtitleTrack {
6090 path: FILE.into(),
6091 track: None,
6092 language: "eng".into(),
6093 name: String::new(),
6094 label: "eng".into(),
6095 cues: Vec::new(),
6096 bitmap: false,
6097 refused: None,
6098 };
6099 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6100 let s1 = p.add_lane(LaneKind::Subtitle);
6101 // The caption spans [80, 100) -- ten frames past the clip's own end
6102 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6103 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6104 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6105 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6106 // no clip member's old span reaches, is the caption's own question:
6107 // half of 95 is 47.5, rounded to 48.
6108 assert_eq!(
6109 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6110 Some(48),
6111 "the overhang frame answers through the caption's own piece"
6112 );
6113 }
6114
6115 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6116 /// map ([`map`]'s architecture law): a caption's landed span comes from
6117 /// the map's own ends, and the playhead standing at the caption's own
6118 /// last frame before the write has to land exactly where the write put
6119 /// it -- across clip lengths and rates that round differently, and an
6120 /// odd-length caption straddling the clip's own tail edge, the corner
6121 /// where `write_speed` used to answer a frame short.
6122 #[test]
6123 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6124 let caption = |start: u32, frames: u32| SubClip {
6125 start,
6126 frames,
6127 track: 0,
6128 in_us: 0,
6129 out_us: i64::from(frames) * 1_000_000,
6130 link: None,
6131 };
6132 let track = || SubtitleTrack {
6133 path: FILE.into(),
6134 track: None,
6135 language: "eng".into(),
6136 name: String::new(),
6137 label: "eng".into(),
6138 cues: Vec::new(),
6139 bitmap: false,
6140 refused: None,
6141 };
6142 for &len in &[90u32, 91, 177, 300, 301] {
6143 for &permille in &[500u16, 2000, 2500, 3000] {
6144 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6145 let s1 = p.add_lane(LaneKind::Subtitle);
6146 // An odd-length caption straddling the clip's tail edge: its
6147 // own last frame lands past the held clip.
6148 let c_start = len.saturating_sub(3);
6149 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6150 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6151 let speed = Speed::from_permille(permille);
6152 let last = c_start + 7 - 1;
6153 let mapped = p
6154 .speeded_playhead(Lane::V1, 0, speed, last)
6155 .expect("the caption is there");
6156 if p.set_speed(Lane::V1, 0, speed).is_err() {
6157 continue; // a refusal changes nothing: not this law's cell
6158 }
6159 let landed = p.sub_lane(s1)[0];
6160 if permille >= 1000 {
6161 // A speed-up compresses the timeline: many old frames
6162 // share one new frame, so the caption's own last old
6163 // frame lands flush with the write's own boundary --
6164 // the exact law [`write_speed`]'s worked drift-fix case
6165 // is stated against.
6166 assert_eq!(
6167 mapped,
6168 landed.end() - 1,
6169 "len {len} permille {permille}: the playhead at the caption's own \
6170 last frame lands where the write actually put it"
6171 );
6172 } else {
6173 // A slow-down expands it: one old frame becomes several
6174 // new ones, and `apply` answers where that frame's own
6175 // block *starts*, not where the caption's last new
6176 // frame (the end of that same block) sits -- a
6177 // one-frame gap inherent to the piece's own semantics,
6178 // not a drift between the two callers. Both still have
6179 // to agree the answer sits inside the caption the write
6180 // actually landed.
6181 assert!(
6182 (landed.start..landed.end()).contains(&mapped),
6183 "len {len} permille {permille}: the playhead lands inside the \
6184 caption the write actually put ({landed:?}), got {mapped}"
6185 );
6186 }
6187 }
6188 }
6189 }
6190
6191 /// A grouped caption's cues re-time with its clip: the placement's window
6192 /// crossed the timeline at its own proportion before any rate, and a
6193 /// re-rate changes that proportion (the frames compress, the window does
6194 /// not). A cue eight seconds into a window played at 2x crosses the screen
6195 /// four seconds in -- and at unity every cue lands exactly where it always
6196 /// did, byte for byte.
6197 #[test]
6198 fn a_grouped_captions_cues_re_time_with_its_clip() {
6199 let track = SubtitleTrack {
6200 path: FILE.into(),
6201 track: None,
6202 language: "eng".into(),
6203 name: String::new(),
6204 label: "eng".into(),
6205 cues: vec![crate::subtitle::Cue {
6206 start_us: 8_000_000,
6207 end_us: 9_000_000,
6208 text: "late line".into(),
6209 image: None,
6210 }],
6211 bitmap: false,
6212 refused: None,
6213 };
6214 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6215 let s1 = p.add_lane(LaneKind::Subtitle);
6216 // Ten seconds of the track over ten seconds of timeline: unity.
6217 p.place_sub(
6218 s1,
6219 0,
6220 SubClip {
6221 start: 0,
6222 frames: 300,
6223 track: 0,
6224 in_us: 0,
6225 out_us: 10_000_000,
6226 link: None,
6227 },
6228 )
6229 .expect("placed");
6230
6231 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6232 let unity = p.sub_lane_cues(s1, FPS);
6233 assert_eq!(
6234 unity
6235 .iter()
6236 .map(|c| (c.start_us, c.end_us, &*c.text))
6237 .collect::<Vec<_>>(),
6238 [(8_000_000, 9_000_000, "late line")],
6239 "a unity placement maps exactly as it always did"
6240 );
6241
6242 // Grouped with the clip and re-rated to 2x: the same window now crosses
6243 // in half the time, so the cue at 8s of it lands 4s in.
6244 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6245 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6246 .expect("room for it");
6247 let re_timed = p.sub_lane_cues(s1, FPS);
6248 assert_eq!(
6249 re_timed
6250 .iter()
6251 .map(|c| (c.start_us, c.end_us))
6252 .collect::<Vec<_>>(),
6253 [(4_000_000, 4_500_000)],
6254 "the cue crosses with the clip's new rate"
6255 );
6256 }
6257
6258 /// A video arriving on a timeline of words mutates none of them: the
6259 /// import's rippling insert used to open room on the subtitle lanes too,
6260 /// splitting a caption it landed inside and sliding the rest behind the
6261 /// video -- the hand asked for an add, and got a cut it never made. The
6262 /// words keep their own clock; co-travel is what a group is for.
6263 #[test]
6264 fn an_arriving_clip_never_touches_the_captions() {
6265 let caption = |start: u32, frames: u32| SubClip {
6266 start,
6267 frames,
6268 track: 0,
6269 in_us: i64::from(start) * 1_000_000 / 30,
6270 out_us: i64::from(start + frames) * 1_000_000 / 30,
6271 link: None,
6272 };
6273 let track = || SubtitleTrack {
6274 path: FILE.into(),
6275 track: None,
6276 language: "eng".into(),
6277 name: String::new(),
6278 label: "eng".into(),
6279 cues: Vec::new(),
6280 bitmap: false,
6281 refused: None,
6282 };
6283 // A timeline of words alone: 60 frames of caption, no media clips.
6284 let mut p = Project::single(FILE, 60)
6285 .with_subtitles(vec![track()]);
6286 for l in [Lane::V1, Lane::A1] {
6287 while !p.lane(l).is_empty() {
6288 p.lift(l, 0);
6289 }
6290 }
6291 let s1 = p.add_lane(LaneKind::Subtitle);
6292 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6293 let before = p.sub_lane(s1).to_vec();
6294
6295 // The video lands BEFORE the caption's span: nothing moves.
6296 let vid = clip(0, 0, 30, 0);
6297 assert!(p.paste(0, vid), "the video goes down at the head");
6298 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6299
6300 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6301 // byte the placement the hand made.
6302 assert!(p.paste(15, vid), "a second video lands inside the caption");
6303 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6304 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6305 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6306 assert!(links_are_consistent(&p.lanes).is_ok());
6307 }
6308
6309 /// The region's caption pieces re-time by mapped boundaries forced apart:
6310 /// rounding start and length independently can land two cues on one frame,
6311 /// and the artifact is clamped -- one frame each, in order, none past the
6312 /// region's new end -- never an overlap on the lane.
6313 #[test]
6314 fn a_regions_caption_pieces_never_round_onto_one_another() {
6315 let caption = |start: u32, frames: u32| SubClip {
6316 start,
6317 frames,
6318 track: 0,
6319 in_us: 0,
6320 out_us: i64::from(frames) * 1_000_000,
6321 link: None,
6322 };
6323 let track = |n| SubtitleTrack {
6324 path: FILE.into(),
6325 track: None,
6326 language: "eng".into(),
6327 name: String::new(),
6328 label: format!("eng{n}"),
6329 cues: Vec::new(),
6330 bitmap: false,
6331 refused: None,
6332 };
6333 // Three lanes, one repro shape each: adjacent one-frame cues, a
6334 // three-frame pair, and the region's last cue against the first
6335 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6336 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6337 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6338 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6339 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6340 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6341 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6342 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6343 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6344
6345 let mut scope = vec![Lane::V1, Lane::A1];
6346 scope.extend(lanes.iter().copied());
6347 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6348 .expect("the region speeds up");
6349 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6350 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6351 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6352 };
6353 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6354 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6355 // and the walk pushes the second to where the first ends.
6356 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6357 // The last cue of the region ends exactly where the region now does
6358 // (frame 15), and the caption behind it lands on that same frame:
6359 // touching, never overlapping.
6360 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6361 for &lane in &lanes {
6362 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6363 }
6364 }
6365
6366 /// The scope law names a caption half too: a scoped cut that would move one
6367 // track of a group whose caption sits outside the scope is refused.
6368 #[test]
6369 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6370 let caption = |start: u32, frames: u32| SubClip {
6371 start,
6372 frames,
6373 track: 0,
6374 in_us: 0,
6375 out_us: i64::from(frames) * 1_000_000,
6376 link: None,
6377 };
6378 let track = || SubtitleTrack {
6379 path: FILE.into(),
6380 track: None,
6381 language: "eng".into(),
6382 name: String::new(),
6383 label: "eng".into(),
6384 cues: Vec::new(),
6385 bitmap: false,
6386 refused: None,
6387 };
6388 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6389 let s1 = p.add_lane(LaneKind::Subtitle);
6390 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6391 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6392
6393 // The subtitle lane is not in the scope, so the group's caption half
6394 // sits outside it: refused, in the law's own words.
6395 let err = p
6396 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6397 .unwrap_err()
6398 .to_string();
6399 assert!(
6400 err.contains("is one take with the S1 caption at frame 0"),
6401 "{err}"
6402 );
6403
6404 // ...and with the caption's lane in the scope, the cut carries it:
6405 // the words over the hole go, and the words behind slide up.
6406 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6407 .expect("the whole group is in the scope");
6408 let subs = p.sub_lane(s1);
6409 assert_eq!(
6410 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6411 [(0, 10), (10, 75)],
6412 "the caption is cut and shifted with the clips"
6413 );
6414 }
6415
6416 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6417 /// mates riding along, the offsets kept, the refusals in words.
6418 #[test]
6419 fn a_hand_built_group_holds_clips_and_a_caption() {
6420 let caption = |start: u32, frames: u32| SubClip {
6421 start,
6422 frames,
6423 track: 0,
6424 in_us: 0,
6425 out_us: i64::from(frames) * 1_000_000,
6426 link: None,
6427 };
6428 let track = || SubtitleTrack {
6429 path: FILE.into(),
6430 track: None,
6431 language: "eng".into(),
6432 name: String::new(),
6433 label: "eng".into(),
6434 cues: Vec::new(),
6435 bitmap: false,
6436 refused: None,
6437 };
6438 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6439 let v2 = p.add_lane(LaneKind::Video);
6440 let s1 = p.add_lane(LaneKind::Subtitle);
6441 // A layer at its own offset, and a caption over the head of the take.
6442 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6443 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6444
6445 // Too few, one lane twice, and an index that is not there: words, no
6446 // snapshot.
6447 let history = p.history.len();
6448 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6449 assert!(p
6450 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6451 .unwrap_err()
6452 .to_string()
6453 .contains("V1 is picked twice"));
6454 assert!(p
6455 .group_all(&[(Lane::V1, 0), (s1, 9)])
6456 .unwrap_err()
6457 .to_string()
6458 .contains("no subtitle 9"));
6459 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6460
6461 // The group: the picture, the layer, and the caption -- and the sound
6462 // the picture was already grouped with comes along unasked.
6463 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6464 .expect("three picks, three lanes");
6465 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6466 for lane in [Lane::V1, Lane::A1, v2] {
6467 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6468 }
6469 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6470 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6471 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6472 assert!(links_are_consistent(&p.lanes).is_ok());
6473 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6474
6475 // ...and one undo takes it apart again.
6476 assert!(p.undo());
6477 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
6478
6479 // Detach names a caption like it names a clip: every member an id of
6480 // its own, which is never `None` (see `ungroup`).
6481 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
6482 assert!(p.ungroup(s1, 0));
6483 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
6484 assert!(loose_sub.is_some() && loose_clip.is_some());
6485 assert_ne!(loose_sub, loose_clip);
6486 assert!(links_are_consistent(&p.lanes).is_ok());
6487 }
6488
6489 /// Two captions on one sub lane, each already grouped with a *different*
6490 /// clip: `group_all` over both those clips would merge the two existing
6491 /// groups into one id and leave both captions on `s1` carrying it --
6492 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
6493 /// group closes. Refused by name, and nothing moves.
6494 #[test]
6495 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
6496 let caption = |start: u32, frames: u32| SubClip {
6497 start,
6498 frames,
6499 track: 0,
6500 in_us: 0,
6501 out_us: i64::from(frames) * 1_000_000,
6502 link: None,
6503 };
6504 let track = || SubtitleTrack {
6505 path: FILE.into(),
6506 track: None,
6507 language: "eng".into(),
6508 name: String::new(),
6509 label: "eng".into(),
6510 cues: Vec::new(),
6511 bitmap: false,
6512 refused: None,
6513 };
6514 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6515 let v2 = p.add_lane(LaneKind::Video);
6516 let s1 = p.add_lane(LaneKind::Subtitle);
6517 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
6518 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
6519 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6520 // V1 grouped with the first caption, v2 with the second -- two
6521 // separate groups, each already one member per lane.
6522 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6523 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
6524 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
6525
6526 let history = p.history.len();
6527 let err = p
6528 .group_all(&[(Lane::V1, 0), (v2, 0)])
6529 .unwrap_err()
6530 .to_string();
6531 assert!(err.contains("one placement per lane"), "{err}");
6532 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
6533 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
6534 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
6535 assert!(links_are_consistent(&p.lanes).is_ok());
6536 }
6537
6538 /// A split hands the caption of a group the same ids it hands the clips:
6539 /// the left halves keep the group, the right halves share a fresh one.
6540 #[test]
6541 fn a_split_cuts_a_grouped_caption_with_its_clips() {
6542 let caption = |start: u32, frames: u32| SubClip {
6543 start,
6544 frames,
6545 track: 0,
6546 in_us: 0,
6547 out_us: i64::from(frames) * 1_000_000,
6548 link: None,
6549 };
6550 let track = || SubtitleTrack {
6551 path: FILE.into(),
6552 track: None,
6553 language: "eng".into(),
6554 name: String::new(),
6555 label: "eng".into(),
6556 cues: Vec::new(),
6557 bitmap: false,
6558 refused: None,
6559 };
6560 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6561 let s1 = p.add_lane(LaneKind::Subtitle);
6562 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
6563 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6564 let take = p.lane(Lane::V1)[0].link.expect("the group id");
6565
6566 assert!(p.split(4));
6567 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6568 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6569 assert_eq!(left.frames, 4);
6570 assert_eq!(
6571 right.link,
6572 p.lane(Lane::V1)[1].link,
6573 "the caption's tail shares the clips' fresh id"
6574 );
6575 assert_ne!(right.link, Some(take));
6576 assert!(links_are_consistent(&p.lanes).is_ok());
6577
6578 // Regroup at the seam restores the take, caption included.
6579 assert!(p.regroup(4));
6580 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6581 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6582 }
6583
6584 /// Deleting a member of a hand-built group takes the group: every
6585 /// member's own span out of its own lane, hole closed -- the lanes may
6586 /// end up out of step, which is what one undo restores together.
6587 #[test]
6588 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6589 let caption = |start: u32, frames: u32| SubClip {
6590 start,
6591 frames,
6592 track: 0,
6593 in_us: 0,
6594 out_us: i64::from(frames) * 1_000_000,
6595 link: None,
6596 };
6597 let track = || SubtitleTrack {
6598 path: FILE.into(),
6599 track: None,
6600 language: "eng".into(),
6601 name: String::new(),
6602 label: "eng".into(),
6603 cues: Vec::new(),
6604 bitmap: false,
6605 refused: None,
6606 };
6607 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6608 let s1 = p.add_lane(LaneKind::Subtitle);
6609 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6610 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6611 // A neighbour on a lane the group does not touch.
6612 let v2 = p.add_lane(LaneKind::Video);
6613 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6614
6615 // By the picture or by the caption, the same whole-group delete.
6616 assert!(p.delete_sub_in(s1, 0));
6617 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6618 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6619 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6620 assert!(links_are_consistent(&p.lanes).is_ok());
6621 assert!(p.undo(), "one step puts the group back");
6622 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6623 }
6624
6625 /// The delete law, one statement for every anchor: a caption deleted
6626 /// WITH its group ripples its lane exactly as its clip siblings do --
6627 /// the hole closes and what follows slides up -- while a caption lifted
6628 /// alone leaves its gap, as it always has. And the delete of a grouped
6629 /// clip takes the group from whichever member was clicked.
6630 #[test]
6631 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
6632 let caption = |start: u32, frames: u32| SubClip {
6633 start,
6634 frames,
6635 track: 0,
6636 in_us: 0,
6637 out_us: i64::from(frames) * 1_000_000,
6638 link: None,
6639 };
6640 let track = || SubtitleTrack {
6641 path: FILE.into(),
6642 track: None,
6643 language: "eng".into(),
6644 name: String::new(),
6645 label: "eng".into(),
6646 cues: Vec::new(),
6647 bitmap: false,
6648 refused: None,
6649 };
6650 // V+A+S grouped, with a second caption BEHIND the group's caption:
6651 // closing the hole is what the second caption's position says.
6652 let group = || {
6653 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6654 let s1 = p.add_lane(LaneKind::Subtitle);
6655 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6656 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6657 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6658 (p, s1)
6659 };
6660
6661 // Deleted by the picture: all three lanes close.
6662 let (mut p, s1) = group();
6663 assert!(p.delete_in(Lane::V1, 0));
6664 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6665 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6666 assert_eq!(
6667 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6668 [60],
6669 "the caption's lane closed by its own span: the follower slid up"
6670 );
6671 assert!(p.undo(), "one step");
6672 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6673
6674 // By the sound: the same whole-group delete.
6675 let (mut p, s1) = group();
6676 assert!(p.delete_in(Lane::A1, 0));
6677 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6678 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6679
6680 // By the caption itself: the same again.
6681 let (mut p, s1) = group();
6682 assert!(p.delete_sub_in(s1, 0));
6683 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6684 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6685 assert!(links_are_consistent(&p.lanes).is_ok());
6686
6687 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6688 // unchanged.
6689 let (mut p, s1) = group();
6690 assert!(p.ungroup(s1, 0), "the caption stands alone");
6691 assert!(p.lift_sub(s1, 0));
6692 assert_eq!(
6693 p.sub_lane(s1)[0].start, 90,
6694 "the follower stayed put: a lone caption's lift is a gap"
6695 );
6696 }
6697
6698 /// Dragging a grouped caption carries its clips, one delta for all of them
6699 /// -- and a caption in no group refuses an overlap exactly as it always did.
6700 #[test]
6701 fn dragging_a_grouped_caption_carries_its_group() {
6702 let caption = |start: u32, frames: u32| SubClip {
6703 start,
6704 frames,
6705 track: 0,
6706 in_us: 0,
6707 out_us: i64::from(frames) * 1_000_000,
6708 link: None,
6709 };
6710 let track = || SubtitleTrack {
6711 path: FILE.into(),
6712 track: None,
6713 language: "eng".into(),
6714 name: String::new(),
6715 label: "eng".into(),
6716 cues: Vec::new(),
6717 bitmap: false,
6718 refused: None,
6719 };
6720 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6721 let s1 = p.add_lane(LaneKind::Subtitle);
6722 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6723 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6724
6725 // Same lane, further along: everyone moves by the same eight frames.
6726 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6727 assert_eq!(p.sub_lane(s1)[0].start, 10);
6728 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6729 assert!(links_are_consistent(&p.lanes).is_ok());
6730
6731 // ...and an ungrouped caption is the caption it always was.
6732 assert!(p.ungroup(s1, 0));
6733 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6734 let s1 = q.add_lane(LaneKind::Subtitle);
6735 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6736 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6737 assert!(q
6738 .move_sub(s1, 0, s1, 3)
6739 .unwrap_err()
6740 .to_string()
6741 .contains("already covers"));
6742 }
6743
6744 /// A trim carries a group's caption by the same delta as its clips, clamped
6745 /// to the caption's own walls -- the offsets between the members survive.
6746 #[test]
6747 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6748 let caption = |start: u32, frames: u32| SubClip {
6749 start,
6750 frames,
6751 track: 0,
6752 in_us: 0,
6753 out_us: i64::from(frames) * 1_000_000,
6754 link: None,
6755 };
6756 let track = || SubtitleTrack {
6757 path: FILE.into(),
6758 track: None,
6759 language: "eng".into(),
6760 name: String::new(),
6761 label: "eng".into(),
6762 cues: Vec::new(),
6763 bitmap: false,
6764 refused: None,
6765 };
6766 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6767 let s1 = p.add_lane(LaneKind::Subtitle);
6768 // The caption sits two frames into the take and ends one early. The
6769 // source runs past the clip, or there is no tail to pull out.
6770 let src = &[20];
6771 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6772 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6773
6774 // The tail goes out by three: the clip to 12, the caption to 11.
6775 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6776 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6777 assert_eq!(
6778 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6779 (2, 11),
6780 "the caption follows by the delta"
6781 );
6782 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6783
6784 // The head comes in by two: everyone's start moves two along.
6785 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6786 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6787 assert!(links_are_consistent(&p.lanes).is_ok());
6788 }
6789
6790 #[test]
6791 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6792 let mut p = three();
6793 let before = shape(&p);
6794 assert!(!p.split(0), "timeline 0 has nothing before it");
6795 assert!(!p.split(3), "existing boundary");
6796 assert!(!p.split(5), "existing boundary");
6797 assert!(!p.split(9), "one past the last frame");
6798 assert!(!p.split(1_000));
6799 assert_eq!(shape(&p), before);
6800 // one undo lands before the *second* split, so the refusals pushed nothing
6801 assert!(p.undo());
6802 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6803
6804 // ...and a frame that is a gap in both lanes has nothing to split.
6805 let mut p = three();
6806 assert!(p.lift(Lane::V1, 1));
6807 assert!(p.lift(Lane::A1, 1));
6808 assert!(!p.split(4), "a gap is not a clip");
6809 }
6810
6811 #[test]
6812 fn regroup_refuses_what_a_split_could_not_have_made() {
6813 let mut p = three();
6814 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6815 assert!(p.regroup(5));
6816 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6817 // A boundary with a gap on one side, and one where the sources do not
6818 // meet, are both refused.
6819 let mut p = three();
6820 assert!(p.lift(Lane::V1, 1));
6821 assert!(p.lift(Lane::A1, 1));
6822 assert!(!p.regroup(3), "nothing starts at 3 any more");
6823 let mut p = three();
6824 for l in p.lanes() {
6825 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6826 }
6827 assert!(!p.regroup(3), "source 100 does not follow source 3");
6828 assert!(!p.regroup(0), "nothing ends at 0");
6829 assert!(!p.regroup(1_000));
6830 }
6831
6832 #[test]
6833 fn map_and_spans_sweep_every_boundary() {
6834 let p = three();
6835 assert_eq!(p.timeline_frames(), 9);
6836 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6837 // contiguous source here, so the clip index is what actually moves
6838 let expect = [
6839 (0, (0, 0)),
6840 (1, (0, 1)),
6841 (2, (0, 2)),
6842 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6843 (4, (1, 4)),
6844 (5, (2, 5)),
6845 (6, (2, 6)),
6846 (7, (2, 7)),
6847 (8, (2, 8)),
6848 ];
6849 for (t, want) in expect {
6850 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6851 }
6852 assert_eq!(p.map_timeline(9), None);
6853 // A span is the rest of the clip from where it was asked about.
6854 assert_eq!(
6855 p.span_at(Lane::V1, 6),
6856 Some(Span {
6857 start: 6,
6858 len: 3,
6859 from: Some((0, 6)),
6860 speed: Speed::NORMAL
6861 })
6862 );
6863 assert_eq!(p.span_at(Lane::V1, 9), None);
6864 }
6865
6866 /// The fit policy is one byte *in* the clip rather than an index into a
6867 /// table like the eq and the grade: there is nothing for a table to share.
6868 /// It costs the clip nothing at all -- the fields before it (a `usize`
6869 /// source and two `Option<u16>`s) already left the struct padded to 40
6870 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
6871 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
6872 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
6873 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
6874 /// words after it pads out to the next multiple of 8: 56 bytes total.
6875 /// The transform index is a third `Option<u16>`, same reason as the eq and
6876 /// colour ones before it -- it lands in bytes already spent on padding, so
6877 /// the struct still costs 56.
6878 /// This is the assert that says so: a clip that grows a word grows every
6879 /// undo snapshot and every clipboard copy with it.
6880 #[test]
6881 fn a_fit_policy_costs_the_clip_no_word() {
6882 assert_eq!(
6883 std::mem::size_of::<Clip>(),
6884 56,
6885 "Clip changed size: {} bytes",
6886 std::mem::size_of::<Clip>()
6887 );
6888 }
6889
6890 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6891 /// anything in `three()` so it is recognisable wherever it lands.
6892 const PASTED: Clip = Clip {
6893 fade_in: 0,
6894 fade_out: 0,
6895 transition_out: 0,
6896 start: 0,
6897 in_frame: 100,
6898 out_frame: 102,
6899 source: 0,
6900 link: None,
6901 eq: None,
6902 color: None,
6903 transform: None,
6904 fit: FitPolicy::Fit,
6905 speed: Speed::NORMAL,
6906 };
6907
6908 #[test]
6909 fn paste_mid_clip_splits_around_it() {
6910 let mut p = three();
6911 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6912 assert_eq!(p.timeline_frames(), 11);
6913 assert_eq!(
6914 shape(&p)[0],
6915 vec![
6916 clip(0, 0, 3, 0),
6917 clip(3, 3, 5, 0),
6918 clip(5, 5, 6, 0),
6919 clip(6, 100, 102, 0),
6920 clip(8, 6, 9, 0),
6921 ]
6922 );
6923 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6924 // The pasted frames are exactly where they were asked for, and the
6925 // split-off remainder resumes after them.
6926 assert_eq!(p.map_timeline(6), Some((3, 100)));
6927 assert_eq!(p.map_timeline(7), Some((3, 101)));
6928 assert_eq!(p.map_timeline(8), Some((4, 6)));
6929 }
6930
6931 #[test]
6932 fn paste_at_boundary_zero_and_end() {
6933 let mut p = three();
6934 assert!(p.paste(3, PASTED), "existing boundary: no split");
6935 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6936 assert_eq!(p.map_timeline(3), Some((1, 100)));
6937
6938 let mut p = three();
6939 assert!(p.paste(0, PASTED));
6940 assert_eq!(p.map_timeline(0), Some((0, 100)));
6941 assert_eq!(p.map_timeline(2), Some((1, 0)));
6942
6943 // At the end: appended, there being nothing in front to leave black.
6944 let mut p = three();
6945 assert!(p.paste(9, PASTED));
6946 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6947 // Past it: down on the frame it was asked for, black in front of it --
6948 // a row let go on the open bed lands under the ghost that promised it.
6949 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6950 assert!(p.paste(1_000, PASTED));
6951 assert_eq!(p.timeline_frames(), 1_002);
6952 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6953 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6954
6955 // An empty clip is the one thing refused, and it pushes no history.
6956 let mut p = three();
6957 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6958 assert_eq!(p.clips().len(), 3);
6959 }
6960
6961 /// The data-loss paste: a clip of a source with no picture used to land on
6962 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6963 /// carried it was refused on the way back in ("a box with a larger size").
6964 #[test]
6965 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6966 let mut p = three();
6967 let wav = p.import("/nonexistent/song.wav", 0);
6968 let copied = Clip {
6969 fade_in: 0,
6970 fade_out: 0,
6971 transition_out: 0,
6972 source: wav,
6973 ..PASTED
6974 };
6975 assert!(p.paste(3, copied));
6976 // The room is opened on every lane, or the two would slide apart...
6977 assert_eq!(p.timeline_frames(), 11);
6978 assert_eq!(
6979 shape(&p)[0],
6980 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6981 "the video lane got room and nothing else"
6982 );
6983 // ...but the clip itself only reaches the lane that can play it.
6984 assert_eq!(
6985 shape(&p)[1],
6986 vec![
6987 clip(0, 0, 3, 0),
6988 clip(3, 100, 102, wav),
6989 clip(5, 3, 5, 0),
6990 clip(7, 5, 9, 0)
6991 ]
6992 );
6993 // A source with a picture is unchanged: still the grouped pair.
6994 let mut p = three();
6995 assert!(p.paste(3, PASTED));
6996 assert_eq!(shape(&p)[0], shape(&p)[1]);
6997 }
6998
6999 /// A hand-written file may hold a clip that ends at the very last frame
7000 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
7001 /// to wrap its start round to the front of the lane: an overlap in debug, a
7002 /// project no reload would accept in release.
7003 #[test]
7004 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
7005 let far = clip(u32::MAX - 90, 0, 90, 0);
7006 let parts = |c: Clip| {
7007 Project::from_parts(
7008 vec![Source::new(FILE, 0)],
7009 two(vec![c], vec![c]),
7010 Vec::new(),
7011 Vec::new(),
7012 Vec::new(),
7013 )
7014 .expect("valid parts")
7015 };
7016 let mut p = parts(far);
7017 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
7018 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
7019 assert!(!p.undo(), "...and pushes no history either");
7020 assert!(
7021 !p.paste(u32::MAX, PASTED),
7022 "appending has nowhere to go either: the timeline ends at the last frame"
7023 );
7024 // With room for exactly those frames the same paste is taken.
7025 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
7026 assert!(p.paste(0, PASTED));
7027 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
7028 }
7029
7030 #[test]
7031 fn paste_undoes_in_one_step() {
7032 let mut p = three();
7033 let before = shape(&p);
7034 assert!(p.paste(6, PASTED));
7035 assert!(p.undo());
7036 assert_eq!(shape(&p), before, "a paste is one undo step");
7037 }
7038
7039 #[test]
7040 fn a_copy_outlives_the_clip_it_came_from() {
7041 let mut p = three();
7042 let copied = p.clips()[1]; // [3,5)
7043 assert!(p.delete(1));
7044 // Just a frame range: the source is still on disk either way.
7045 assert!(p.paste(0, copied));
7046 assert_eq!(p.map_timeline(0), Some((0, 3)));
7047 assert_eq!(p.timeline_frames(), 9);
7048 }
7049
7050 #[test]
7051 fn delete_closes_the_gap_on_both_lanes() {
7052 let mut p = three();
7053 assert!(p.delete(1));
7054 assert_eq!(p.timeline_frames(), 7);
7055 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
7056 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
7057 // timeline 3 used to be source 3; the gap closed so it is source 5 now
7058 assert_eq!(p.map_timeline(3), Some((1, 5)));
7059 assert_eq!(p.map_timeline(6), Some((1, 8)));
7060 assert_eq!(p.map_timeline(7), None);
7061 }
7062
7063 #[test]
7064 fn delete_first_last_and_only() {
7065 let mut p = three();
7066 assert!(p.delete(0));
7067 assert_eq!(p.map_timeline(0), Some((0, 3)));
7068 assert_eq!(p.timeline_frames(), 6);
7069
7070 let mut p = three();
7071 assert!(p.delete(2));
7072 assert_eq!(p.timeline_frames(), 5);
7073 assert_eq!(p.map_timeline(4), Some((1, 4)));
7074
7075 assert!(!p.delete(2), "index past the end");
7076 assert!(p.delete(1));
7077 assert!(p.delete(0), "and the last remaining clip goes too");
7078 assert_eq!(p.clips().len(), 0);
7079 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
7080 assert!(!p.delete(0), "there is nothing left to delete");
7081 assert!(p.undo(), "one gesture, one undo");
7082 assert_eq!(p.clips().len(), 1);
7083 }
7084
7085 /// The offset model's point: one lane loses a clip, the other does not move.
7086 #[test]
7087 fn a_lift_leaves_a_gap_and_moves_nothing() {
7088 let mut p = three();
7089 let video_before = shape(&p)[0].clone();
7090 assert!(p.lift(Lane::A1, 1));
7091 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7092 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7093 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7094 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7095 assert_eq!(p.map(Lane::A1, 4), None);
7096 assert_eq!(
7097 p.span_at(Lane::A1, 3),
7098 Some(Span {
7099 start: 3,
7100 len: 2,
7101 from: None,
7102 speed: Speed::NORMAL
7103 })
7104 );
7105 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7106 assert!(p.undo());
7107 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7108 }
7109
7110 #[test]
7111 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7112 let mut p = three();
7113 assert!(p.lift(Lane::A1, 2));
7114 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7115 assert_eq!(
7116 p.span_at(Lane::A1, 5),
7117 Some(Span {
7118 start: 5,
7119 len: 4,
7120 from: None,
7121 speed: Speed::NORMAL
7122 }),
7123 "the audio lane holds silence to the end of the picture"
7124 );
7125 assert_eq!(p.span_at(Lane::A1, 9), None);
7126 // Every lane covers the timeline exactly, gaps included.
7127 for l in p.lanes() {
7128 let spans = p.spans_from(l, 0);
7129 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7130 assert_eq!(spans[0].start, 0);
7131 }
7132 }
7133
7134 /// The timeline is emptiable: the last placement comes off like any other,
7135 /// the project holds "nothing on any lane" as a state, and one undo per
7136 /// gesture brings it back.
7137 #[test]
7138 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7139 let mut p = Project::single(FILE, 9);
7140 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7141 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7142 assert_eq!(p.timeline_frames(), 0);
7143 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7144 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7145 assert!(!p.lift(Lane::A1, 0), "index past the end");
7146 assert!(p.undo(), "and the last lift comes back");
7147 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7148 // A saved-and-loaded empty timeline is a project like any other, and it
7149 // still names the file its frame rate came from.
7150 assert!(p.lift(Lane::V1, 0));
7151 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7152 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7153 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7154 assert_eq!(back.timeline_frames(), 0);
7155 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7156 }
7157
7158 /// What a keyboard selection walks: one answer per lane, gaps included --
7159 /// the composite's own answer is one lane's and cannot say what the audio
7160 /// lane holds under the same playhead.
7161 #[test]
7162 fn lane_clip_at_answers_for_each_lane_separately() {
7163 let mut p = Project::single(FILE, 9);
7164 assert!(p.split(3), "both lanes split");
7165 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7166 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7167 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7168 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7169 // A gap on one lane leaves the other's clip selectable there.
7170 assert!(p.lift(Lane::A1, 0));
7171 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7172 assert_eq!(
7173 p.lane_clip_at(Lane::A1, 3),
7174 Some(0),
7175 "indices moved with it"
7176 );
7177 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7178 // A lane that is not there is not a panic.
7179 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7180 }
7181
7182 #[test]
7183 fn place_overwrites_only_its_own_lane() {
7184 let mut p = three();
7185 let audio_before = shape(&p)[1].clone();
7186 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7187 // is trimmed, nothing shifts.
7188 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7189 assert_eq!(
7190 shape(&p)[0],
7191 vec![
7192 clip(0, 0, 3, 0),
7193 clip(3, 3, 4, 0),
7194 clip(4, 100, 102, 0),
7195 clip(6, 6, 9, 0),
7196 ]
7197 );
7198 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7199 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7200
7201 // Placed inside one clip, it splits it in two.
7202 let mut p = Project::single(FILE, 9);
7203 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7204 assert_eq!(
7205 shape(&p)[0],
7206 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7207 );
7208 // ...and placed past the end it makes a gap, which is the whole point.
7209 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7210 assert_eq!(p.timeline_frames(), 22);
7211 assert_eq!(
7212 p.span_at(Lane::V1, 9),
7213 Some(Span {
7214 start: 9,
7215 len: 11,
7216 from: None,
7217 speed: Speed::NORMAL
7218 })
7219 );
7220 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7221 }
7222
7223 /// A file with sound let go over a further video track: both halves go down,
7224 /// on the same frames, and the audio row is added when the `+ V` button left
7225 /// the project without one. One undo takes the lane and both clips back.
7226 #[test]
7227 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7228 let mut p = three();
7229 let v2 = p.add_lane(LaneKind::Video);
7230 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7231
7232 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7233 let a2 = Lane::new(LaneKind::Audio, 1);
7234 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7235 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7236 assert_eq!(p.lane(v2)[0].start, 4);
7237 assert_eq!(p.lane(v2)[0].end(), 6);
7238 assert_eq!(
7239 p.lane(v2)[0].link,
7240 p.lane(a2)[0].link,
7241 "one take, not two placements"
7242 );
7243 assert!(p.lane(v2)[0].link.is_some());
7244 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7245 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7246
7247 // The pair overwrites its own two lanes and nothing else, exactly as a
7248 // one-lane place does.
7249 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7250 assert_eq!(p.lane(v2), p.lane(a2));
7251 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7252 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7253
7254 assert!(p.undo(), "one step for the second pair");
7255 assert_eq!(p.lane(v2).len(), 1);
7256 assert!(p.undo(), "one step for the first pair *and* its lane");
7257 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7258 assert!(p.lane(v2).is_empty());
7259
7260 // Refusals cost nothing: sound placed alone is `place`'s door.
7261 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7262 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7263 assert!(
7264 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7265 "a lane that is not there"
7266 );
7267 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7268 }
7269
7270 /// The drag between tracks: let go at the frames it already covers the clip
7271 /// keeps them, one undo takes it back, and every way it can be refused
7272 /// leaves the project untouched.
7273 #[test]
7274 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7275 let v2 = Lane::new(LaneKind::Video, 1);
7276 let mut p = three();
7277 assert_eq!(p.add_lane(LaneKind::Video), v2);
7278 let before = shape(&p);
7279
7280 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7281 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7282 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7283 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7284 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7285 // One snapshot: a single undo, and the lane list survives it.
7286 assert!(p.undo());
7287 assert_eq!(shape(&p), before);
7288
7289 // A lane that is not there, the lane and frame it is already at, an
7290 // index that is not there, and a move across kinds: all refused,
7291 // nothing changed.
7292 let history = p.history.len();
7293 for (from, idx, to, start) in [
7294 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7295 (Lane::V1, 1, Lane::V1, 3),
7296 (Lane::V1, 9, v2, 3),
7297 (Lane::V1, 1, Lane::A1, 3),
7298 (Lane::A1, 1, v2, 3),
7299 ] {
7300 assert!(
7301 !p.move_clip(from, idx, to, start),
7302 "{from:?} {idx} -> {to:?} at {start}"
7303 );
7304 }
7305 assert_eq!(shape(&p), before);
7306 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7307
7308 // Landing on another clip is refused rather than overwriting it: the
7309 // pointer named the lane, never the take already sitting there.
7310 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7311 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7312 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7313 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7314 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7315 }
7316
7317 /// The drag *along* a track, which is the one every other editor has: the
7318 /// clip lands on the frame the pointer let it go at, and stops dead against
7319 /// the neighbour rather than overwriting it.
7320 #[test]
7321 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7322 let sources = vec![Source::new(FILE, 0)];
7323 let lanes = vec![
7324 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7325 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7326 ];
7327 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7328 let before = shape(&p);
7329
7330 // Into the gap, exactly where it was let go -- nothing else moves.
7331 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7332 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7333 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7334 // Dragged past the clip in front of it: clamped to its wall, laid end
7335 // to end with it, never over it.
7336 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7337 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7338 // One undo per drag, and both of them together are the state it started
7339 // in -- the frames each clip plays never changed.
7340 assert!(p.undo() && p.undo());
7341 assert_eq!(shape(&p), before);
7342
7343 // A drop that changes nothing is a click, not an edit.
7344 let history = p.history.len();
7345 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7346 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7347 }
7348
7349 /// A drag carries the whole take: the sound half travels exactly as far as
7350 /// the picture does, and the tighter of their two walls stops both.
7351 #[test]
7352 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7353 let mut p = three();
7354 assert!(
7355 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7356 "room to the right"
7357 );
7358 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7359 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7360 // Something in the sound's way, and nothing at all in the picture's.
7361 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7362 let before = shape(&p);
7363
7364 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7365 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7366 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7367 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7368 assert!(p.undo());
7369 assert_eq!(shape(&p), before, "one undo for the whole take");
7370 }
7371
7372 /// The drag that does both at once -- another lane *and* another frame --
7373 /// which is what a pointer let go over a lane always names.
7374 #[test]
7375 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7376 let v2 = Lane::new(LaneKind::Video, 1);
7377 let mut p = three();
7378 assert_eq!(p.add_lane(LaneKind::Video), v2);
7379
7380 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7381 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7382 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7383 assert_eq!(
7384 p.lane(Lane::A1)[2].start,
7385 20,
7386 "its sound travelled the same distance"
7387 );
7388 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7389 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7390 }
7391
7392 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7393 /// [`three`] cuts up all nine of its frames.
7394 const SRC: &[u32] = &[9];
7395
7396 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7397 /// else on the lane moves, and every wall stops the edge rather than
7398 /// refusing the gesture.
7399 #[test]
7400 fn trimming_the_tail_stops_at_every_wall() {
7401 let mut p = three();
7402
7403 // Pulled in: a gap opens behind it and the clip after it stays put.
7404 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7405 assert_eq!(
7406 shape(&p)[0],
7407 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7408 );
7409 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7410 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7411
7412 // ...and back out, no further than the clip behind it.
7413 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7414 assert_eq!(
7415 shape(&p)[0][1],
7416 clip(3, 3, 5, 0),
7417 "stopped at the neighbour"
7418 );
7419 assert!(
7420 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7421 "already at the wall"
7422 );
7423
7424 // One frame of clip always survives, however far back the pointer went.
7425 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7426 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7427
7428 // The last clip has no neighbour, so what stops it is the file: nine
7429 // frames is nine frames.
7430 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7431 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7432 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7433 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7434 // A source nobody told us the length of may not grow at all -- an
7435 // out-point past the end of a file is a save that will not open again.
7436 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7437 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7438 }
7439
7440 /// The head pulled in takes the in-point with it -- what stays plays what it
7441 /// always played -- and stops at the source's own first frame.
7442 #[test]
7443 fn trimming_the_head_moves_the_in_point() {
7444 let mut p = three();
7445 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7446 assert_eq!(
7447 shape(&p)[0][0],
7448 clip(2, 2, 3, 0),
7449 "two frames off the front"
7450 );
7451 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7452 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7453 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7454 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7455 // One frame survives here too.
7456 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7457 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7458
7459 // A clip that does not begin at its source's first frame: its head goes
7460 // back to source frame 0 and not one frame further.
7461 let mut p = Project::single(FILE, 9);
7462 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7463 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7464 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7465 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7466 }
7467
7468 /// A clip whose in-point is *past* its own start -- what a ripple delete
7469 /// leaves, the piece in front of it gone and this one slid back to frame 0
7470 /// carrying the in-point the cut gave it. Its head has more source behind it
7471 /// than the timeline has room for, and the timeline's own first frame is the
7472 /// wall: asking is not an overflow, and the answer is 0.
7473 #[test]
7474 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
7475 let mut p = Project::single(FILE, 9);
7476 assert!(p.split(5));
7477 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
7478 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
7479
7480 assert_eq!(
7481 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
7482 Some((0, 3)),
7483 "back to frame 0 at most, and one frame of clip always survives"
7484 );
7485 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
7486 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7487 assert_eq!(
7488 shape(&p)[0],
7489 vec![clip(2, 7, 9, 0)],
7490 "the in-point followed"
7491 );
7492 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
7493 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
7494 }
7495
7496 /// A still is trimmed from its head exactly as it is from its tail: it has
7497 /// no earlier frame to walk an in-point back to, so the wall is the length
7498 /// the caller's table allows it, measured back from the tail. Measured from
7499 /// the in-point -- which a placed picture has at 0 -- its left edge could
7500 /// never be dragged outwards at all.
7501 #[test]
7502 fn a_stills_head_stretches_out_like_its_tail() {
7503 const STILL: &str = "/nonexistent/card.png";
7504 /// What a still is held to, as `PlaybackSession` fills the table in.
7505 const CAP: &[u32] = &[60];
7506
7507 let mut p = Project::single(STILL, 20);
7508 assert!(p.lift(Lane::A1, 0), "a picture is silent");
7509 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
7510 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
7511
7512 // A source with no entry in the table may not grow, here as at the tail.
7513 assert_eq!(
7514 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
7515 Some((100, 119)),
7516 "a length nobody told us buys no head room"
7517 );
7518 assert_eq!(
7519 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
7520 Some((60, 119)),
7521 "back to a whole cap's worth, one frame of clip surviving"
7522 );
7523 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
7524 assert_eq!(
7525 shape(&p)[0][0],
7526 clip(80, 0, 40, 0),
7527 "twenty frames longer, and still read from the source's first frame"
7528 );
7529 // Past the cap is clamped, exactly as the tail is -- not refused.
7530 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
7531 assert_eq!(
7532 shape(&p)[0][0],
7533 clip(60, 0, 60, 0),
7534 "a cap's worth, no more"
7535 );
7536 // ...and the clip in front is the nearer wall of the two: no head trim
7537 // may open an overlap.
7538 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
7539 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
7540 assert_eq!(
7541 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
7542 Some((85, 119)),
7543 "up to the neighbour's last frame and not over it"
7544 );
7545 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
7546 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
7547 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
7548 }
7549
7550 /// Linked halves trim as one: a link is one span on however many lanes, so
7551 /// the sound follows the picture's edge -- and the tightest wall of the two
7552 /// is what stops both.
7553 #[test]
7554 fn linked_halves_trim_together() {
7555 let mut p = three();
7556 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
7557 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
7558
7559 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
7560 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
7561 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
7562 assert!(
7563 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
7564 "either half drags it"
7565 );
7566 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
7567 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7568
7569 // Something in the way on the *audio* lane stops the picture's tail as
7570 // well: the group can only go as far as its tightest member.
7571 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
7572 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7573 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
7574 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
7575 links_are_consistent(&p.lanes).expect("still one span");
7576 }
7577
7578 /// A whole drag is one undo step -- the front-end commits once, at the
7579 /// release -- and an edge asked to stay where it is costs none at all.
7580 #[test]
7581 fn a_trim_is_one_undo_step() {
7582 let mut p = three();
7583 let before = shape(&p);
7584 let history = p.history.len();
7585
7586 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7587 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7588 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7589 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7590 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7591 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7592
7593 assert!(p.undo());
7594 assert_eq!(shape(&p), before, "both halves back, in one step");
7595 }
7596
7597 /// A moved half stays in its group: a link names a span, not a lane, so the
7598 /// picture on `V2` is still the same take as the sound under it on `A1`.
7599 #[test]
7600 fn move_clip_keeps_the_group() {
7601 let v2 = Lane::new(LaneKind::Video, 1);
7602 let mut p = three();
7603 p.add_lane(LaneKind::Video);
7604 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7605 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7606 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7607 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7608 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7609 assert_eq!(
7610 p.lane(v2)[0].start,
7611 p.lane(Lane::A1)[1].start,
7612 "and still covers the same span as its sound"
7613 );
7614 }
7615
7616 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
7617 /// head of a lane, between two clips, inside a clip, past the last one,
7618 /// and on a lane holding nothing at all.
7619 #[test]
7620 fn gap_at_finds_the_hole_a_frame_sits_in() {
7621 let mut p = Project::single(FILE, 1);
7622 let v = p.add_lane(LaneKind::Video);
7623 // Empty lane: nothing before and nothing after -- not a gap, since
7624 // there is nothing to ripple toward.
7625 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
7626
7627 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
7628 // Before the only clip: the gap runs from the timeline's own head.
7629 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
7630 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
7631 // Inside the clip: not a gap.
7632 assert_eq!(p.gap_at(v, 5), None);
7633 assert_eq!(p.gap_at(v, 7), None);
7634 // Past the only clip: the open end of the lane, not a gap -- there is
7635 // nothing after it to slide back.
7636 assert_eq!(p.gap_at(v, 8), None);
7637 assert_eq!(p.gap_at(v, 100), None);
7638
7639 assert!(p.place(v, 12, clip(12, 0, 2, 0)), "a second clip at [12,14)");
7640 // Between the two: the gap [8,12).
7641 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
7642 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
7643 assert_eq!(p.gap_at(v, 14), None, "still the open end");
7644
7645 assert!(
7646 p.place(v, 8, clip(8, 0, 4, 0)),
7647 "fills [8,12) exactly, meeting both neighbours"
7648 );
7649 assert_eq!(p.gap_at(v, 8), None, "adjacent clips leave no frame to name a gap");
7650 assert_eq!(p.gap_at(v, 11), None);
7651 }
7652
7653 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
7654 /// menu named: the clip after the gap slides back on that lane, a clip on
7655 /// another lane at the very same frame range does not move, and the whole
7656 /// close is one press of undo.
7657 #[test]
7658 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
7659 let mut p = Project::single(FILE, 1);
7660 let v = p.add_lane(LaneKind::Video);
7661 let a = p.add_lane(LaneKind::Audio);
7662 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
7663 assert!(
7664 p.place(a, 0, clip(0, 0, 3, 0)),
7665 "A clip at [0,3) -- outside the video lane's gap and this scope"
7666 );
7667 let before = shape(&p);
7668 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
7669 assert_eq!((start, len), (0, 5));
7670 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
7671 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
7672 assert_eq!(p.lane(a)[0].start, 0, "the untouched lane's clip did not move");
7673 assert!(p.undo(), "one press undoes the whole close");
7674 assert_eq!(shape(&p), before, "back to exactly where it was");
7675 }
7676
7677 /// A clip carrying an explicit link id -- what a
7678 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
7679 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
7680 /// already builds inline.
7681 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
7682 Clip {
7683 fade_in: 0,
7684 fade_out: 0,
7685 transition_out: 0,
7686 start,
7687 in_frame,
7688 out_frame,
7689 source: 0,
7690 link: Some(link),
7691 eq: None,
7692 color: None,
7693 transform: None,
7694 fit: FitPolicy::default(),
7695 speed: Speed::NORMAL,
7696 }
7697 }
7698
7699 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
7700 /// bordered by a linked take whose `A1` half is empty across the very
7701 /// same stretch widens the scope to both lanes, so the ripple carries the
7702 /// take rather than tearing it -- and one undo puts both halves back.
7703 #[test]
7704 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
7705 let sources = vec![Source::new(FILE, 0)];
7706 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
7707 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
7708 let mut p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
7709 .expect("valid parts");
7710 let before = shape(&p);
7711 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
7712 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 2)), "the same stretch is empty on A1 too");
7713
7714 let scope = p
7715 .gap_take_scope(Lane::V1, 3, 2)
7716 .expect("a matching gap on both halves widens the scope");
7717 assert_eq!(scope.len(), 2, "the take's other lane joins");
7718 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
7719
7720 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
7721 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
7722 assert_eq!(p.lane(Lane::A1)[1].start, 3, "A1's far half rode along, in sync");
7723 assert!(p.undo(), "one press undoes the whole close");
7724 assert_eq!(shape(&p), before, "back to exactly where it was");
7725 }
7726
7727 /// The real design question: a take whose gap is not the *same size* on
7728 /// both lanes cannot ripple by one number without pulling a lane's clip
7729 /// out from under the other's sync -- refused by name, with the frame
7730 /// naming which lane is out of step, rather than silently taking real
7731 /// media off the shorter side.
7732 #[test]
7733 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
7734 let sources = vec![Source::new(FILE, 0)];
7735 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
7736 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
7737 // shorter than V1's [3,5) -- a legal offset-preserving group, and
7738 // still one take.
7739 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
7740 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
7741 .expect("valid parts");
7742 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
7743 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
7744
7745 let err = p
7746 .gap_take_scope(Lane::V1, 3, 2)
7747 .expect_err("a mismatched gap cannot ripple by one number")
7748 .to_string();
7749 assert!(err.contains("A1"), "{err}");
7750 assert!(err.contains("out of sync"), "{err}");
7751 }
7752
7753 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
7754 /// there -- cannot close without cutting that audio out from under
7755 /// nothing asked to touch it: refused, not widened silently past.
7756 #[test]
7757 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
7758 let sources = vec![Source::new(FILE, 0)];
7759 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
7760 // A1 plays through the whole span as one continuous clip, sharing
7761 // V1's first-half link: nothing empty at frame 3 there at all.
7762 let audio = vec![linked(0, 0, 9, 1)];
7763 let p = Project::from_parts(sources, two(video, audio), Vec::new(), Vec::new(), Vec::new())
7764 .expect("valid parts");
7765 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
7766 assert_eq!(p.gap_at(Lane::A1, 3), None, "A1 plays through, no gap there");
7767
7768 let err = p
7769 .gap_take_scope(Lane::V1, 3, 2)
7770 .expect_err("a solid partner cannot ripple with the gap")
7771 .to_string();
7772 assert!(err.contains("A1"), "{err}");
7773 assert!(err.contains("detach"), "{err}");
7774 }
7775
7776 #[test]
7777 fn ripple_delete_spans_partial_clips() {
7778 let mut p = three();
7779 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
7780 assert!(p.ripple_delete(2, 4));
7781 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
7782 assert_eq!(shape(&p)[1], shape(&p)[0]);
7783 assert_eq!(p.timeline_frames(), 5);
7784 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
7785 assert!(p.undo());
7786 assert_eq!(shape(&p), shape(&three()));
7787 // One that takes everything is a delete like any other: the timeline
7788 // empties, and the undo it cost brings it back whole.
7789 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
7790 assert_eq!(p.timeline_frames(), 0);
7791 assert!(
7792 !p.ripple_delete(0, 100),
7793 "and a delete with nothing left to take is not an undo step"
7794 );
7795 assert!(p.undo());
7796 assert_eq!(shape(&p), shape(&three()));
7797 }
7798
7799 #[test]
7800 fn undo_restores_exactly() {
7801 let mut p = three();
7802 let after_splits = shape(&p);
7803 assert!(p.delete(1));
7804 assert!(p.undo());
7805 assert_eq!(shape(&p), after_splits);
7806
7807 // walk all the way back through both splits, then run dry
7808 assert!(p.undo());
7809 assert_eq!(p.clips().len(), 2);
7810 assert!(p.undo());
7811 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7812 assert!(!p.undo(), "empty history");
7813 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7814 }
7815
7816 #[test]
7817 fn redo_restores_exactly() {
7818 let mut p = three();
7819 assert!(p.delete(1));
7820 let after_delete = p.parts();
7821 assert!(p.undo());
7822 assert!(p.redo());
7823 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
7824 assert!(!p.redo(), "empty redo stack");
7825 }
7826
7827 #[test]
7828 fn edit_after_undo_empties_redo() {
7829 let mut p = three();
7830 assert!(p.delete(1));
7831 assert!(p.undo());
7832 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
7833 assert!(p.split(1), "a fresh edit");
7834 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
7835 assert!(!p.redo(), "so redo has nothing left");
7836 }
7837
7838 #[test]
7839 fn redo_on_empty_stack_is_false() {
7840 let mut p = three();
7841 assert!(!p.redo(), "nothing has been undone yet");
7842 }
7843
7844 /// Past the cap the *oldest* step goes, so a long session undoes exactly
7845 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
7846 #[test]
7847 fn history_stops_at_the_cap() {
7848 let mut p = Project::single(FILE, 400);
7849 for frame in 1..=150 {
7850 assert!(p.split(frame), "split {frame} is an edit");
7851 }
7852 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
7853 for step in 0..HISTORY_CAP {
7854 assert!(p.undo(), "undo {step} is inside the cap");
7855 }
7856 assert!(!p.undo(), "and the 101st has nothing left to take");
7857 // 100 undos off 150 splits is the timeline after the 50th: the older
7858 // steps were dropped, not the newer ones.
7859 assert_eq!(p.clips().len(), 51);
7860 }
7861
7862 /// Undo/redo by hand across a split must never merge two takes into one
7863 /// group by reusing an id.
7864 #[test]
7865 fn group_ids_are_never_reused() {
7866 let mut p = Project::single(FILE, 9);
7867 assert!(p.split(3));
7868 let first = p.clips()[1].link;
7869 assert!(p.undo());
7870 assert!(p.split(5));
7871 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
7872 }
7873
7874 #[test]
7875 fn segments_from_reads_the_audio_lane() {
7876 let p = three();
7877 // mid-clip: partial first segment, whole clips after it
7878 assert_eq!(
7879 p.segments_from(4, FPS),
7880 vec![
7881 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7882 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7883 ]
7884 );
7885 // on a boundary: nothing partial
7886 assert_eq!(
7887 p.segments_from(3, FPS),
7888 vec![
7889 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7890 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7891 ]
7892 );
7893 // from the top: one entry per clip
7894 assert_eq!(p.segments_from(0, FPS).len(), 3);
7895 // last clip only
7896 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7897 // past the end / unusable fps
7898 assert!(p.segments_from(9, FPS).is_empty());
7899 assert!(p.segments_from(0, 0.0).is_empty());
7900 assert!(p.segments_from(0, f64::NAN).is_empty());
7901 }
7902
7903 #[test]
7904 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7905 let mut p = three();
7906 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7907 assert_eq!(
7908 p.segments_from(0, FPS),
7909 vec![
7910 (Some(0), 0.0, 3.0 / 30.0),
7911 (None, 0.0, 2.0 / 30.0),
7912 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7913 ]
7914 );
7915 // The list still covers exactly the timeline: that is what stops the
7916 // master clock stalling at the hole.
7917 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7918 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7919 // Starting inside the gap trims the silence, not the clip after it.
7920 assert_eq!(
7921 p.segments_from(4, FPS),
7922 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7923 );
7924 // ...and a lane that is nothing but gap is a run of silence.
7925 assert!(p.lift(Lane::A1, 0));
7926 assert!(p.lift(Lane::A1, 0));
7927 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7928 }
7929
7930 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7931 /// of source 0 then [0,4) of source 1.
7932 fn two_sources() -> Project {
7933 let mut p = three();
7934 let s = p.import(FILE2, 0);
7935 assert_eq!(s, 1);
7936 assert!(p.append_clip(s, 4));
7937 p
7938 }
7939
7940 #[test]
7941 fn import_dedups_and_appends() {
7942 let mut p = Project::single(FILE, 9);
7943 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7944 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7945 assert_eq!(p.import(FILE2, 0), 1);
7946 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7947 // ...but the same file on another audio stream is another source: it is
7948 // what a clip names, and a clip plays exactly one stream.
7949 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7950 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7951 assert_eq!(p.sources()[2].audio_stream, 1);
7952 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7953 assert!(p.undo());
7954 assert_eq!(p.sources().len(), 3);
7955 assert!(!p.append_clip(3, 5), "unknown source index");
7956 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7957
7958 // Two spellings of one real file are one source: this is the case the
7959 // raw-path comparison above would get wrong.
7960 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7961 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7962 let mut p = Project::single(here, 9);
7963 assert_eq!(p.import(detour, 0), 0);
7964 assert_eq!(p.sources().len(), 1);
7965 }
7966
7967 #[test]
7968 fn append_clip_is_one_undo_step() {
7969 let mut p = two_sources();
7970 assert_eq!(p.timeline_frames(), 13);
7971 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7972 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7973 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7974 assert!(p.undo());
7975 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7976 assert_eq!(
7977 p.sources().len(),
7978 2,
7979 "the orphan source entry stays -- indexes are forever"
7980 );
7981 // ...and it is still usable, so a redo-by-hand costs no reimport.
7982 assert!(p.append_clip(1, 0));
7983 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7984 }
7985
7986 #[test]
7987 fn edits_carry_the_source_along() {
7988 let mut p = two_sources();
7989 // A split inside the second source splits into two source-1 clips.
7990 assert!(p.split(11));
7991 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7992 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7993
7994 // A source-1 clip pasted into source-0 territory keeps its file, and so
7995 // does the source-0 half that got split off around it.
7996 let copied = p.clips()[4];
7997 assert!(p.paste(1, copied));
7998 assert_eq!(p.clips()[1].source, 1);
7999 assert_eq!(p.clips()[1].in_frame, 2);
8000 assert_eq!(p.clips()[2].source, 0);
8001 assert!(p.undo());
8002 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
8003 }
8004
8005 #[test]
8006 fn segments_from_names_the_source() {
8007 let p = two_sources();
8008 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
8009 assert_eq!(
8010 p.segments_from(4, FPS),
8011 vec![
8012 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
8013 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
8014 (Some(1), 0.0, 4.0 / 30.0),
8015 ]
8016 );
8017 // Mid-clip in source 1: only that source is left.
8018 assert_eq!(
8019 p.segments_from(10, FPS),
8020 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
8021 );
8022 assert!(p.segments_from(13, FPS).is_empty());
8023 // Segments still cover exactly the timeline across the join.
8024 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
8025 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
8026 }
8027
8028 #[test]
8029 fn segments_follow_deletes_and_fps() {
8030 let mut p = three();
8031 assert!(p.delete(0));
8032 // source seconds, not timeline: deleting the head does not shift them
8033 let segs = p.segments_from(0, 25.0);
8034 assert_eq!(
8035 segs,
8036 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
8037 );
8038 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
8039 assert!(
8040 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
8041 "segments must cover exactly the timeline: {played}"
8042 );
8043 }
8044
8045 #[test]
8046 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
8047 // Import a second file, undo it: source 1 is now an orphan.
8048 let mut p = two_sources();
8049 assert!(p.undo());
8050 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8051 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
8052 assert!(eq.is_empty(), "and a project with no equalizer writes none");
8053 assert!(color.is_empty(), "nor a colour it never graded with");
8054 assert_eq!(
8055 lanes,
8056 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
8057 "the clips are untouched"
8058 );
8059
8060 // Three sources where only the middle one is orphaned: the survivors
8061 // renumber, and the clips follow.
8062 let mut p = Project::single(FILE, 9);
8063 assert_eq!(p.import(FILE2, 0), 1);
8064 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
8065 assert!(p.append_clip(2, 4));
8066 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8067 assert_eq!(
8068 sources,
8069 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
8070 );
8071 assert_eq!(
8072 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
8073 [0, 1]
8074 );
8075 // ...and what comes out is loadable, with the same timeline.
8076 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8077 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
8078 assert_eq!(reloaded.sources().len(), 2);
8079 }
8080
8081 /// Taking a file out of the library: refused by name -- lanes and counts --
8082 /// while a clip still plays from it, and once nothing does, the entry goes
8083 /// and every clip that indexed past it is renumbered onto the short list.
8084 #[test]
8085 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
8086 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
8087 // plus a second stream of FILE as source 2 with a take of its own.
8088 let mut p = two_sources();
8089 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
8090 assert!(p.append_clip(2, 4));
8091
8092 let refusal = p
8093 .remove_source(1)
8094 .expect_err("a source with clips on it cannot go")
8095 .to_string();
8096 assert!(refusal.contains(FILE2), "names the file: {refusal}");
8097 assert!(
8098 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
8099 "names the lanes holding it: {refusal}"
8100 );
8101 assert!(refusal.contains("still plays"), "{refusal}");
8102 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
8103 assert_eq!(shape(&p)[0][3].source, 1);
8104
8105 // Delete FILE2's take -- the whole span, on every lane -- and the entry
8106 // is free to go. Source 2's clips become source 1's.
8107 assert!(p.delete_in(Lane::V1, 3));
8108 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
8109 p.remove_source(1).expect("nothing plays FILE2 any more");
8110 assert_eq!(
8111 p.sources(),
8112 [Source::new(FILE, 0), Source::new(FILE, 1)],
8113 "the middle entry is gone"
8114 );
8115 assert_eq!(
8116 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
8117 [0, 0, 0, 1],
8118 "the clips past it renumbered"
8119 );
8120 assert_eq!(
8121 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
8122 [0, 0, 0, 1],
8123 "on every lane"
8124 );
8125 // What is left is a project that still loads, which is the whole point
8126 // of renumbering rather than leaving a hole.
8127 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
8128 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
8129 }
8130
8131 /// The two edges of a removal: it retires the undo stack (the corner-cut on
8132 /// [`Project::remove_source`]), and the last entry goes like any other
8133 /// once nothing plays it -- a project may name no file at all.
8134 #[test]
8135 fn remove_source_retires_undo_and_empties_the_library() {
8136 let mut p = two_sources();
8137 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
8138 assert!(!p.history.is_empty(), "there is something to undo");
8139 p.remove_source(1).expect("nothing plays FILE2");
8140 assert!(
8141 p.history.is_empty(),
8142 "a snapshot naming the removed source must not survive it"
8143 );
8144 assert!(!p.undo(), "and so there is nothing left to undo");
8145
8146 // The last file standing is held to the one rule every row is -- what
8147 // plays cannot go -- and to no other.
8148 assert_eq!(p.sources().len(), 1);
8149 let refusal = p
8150 .remove_source(0)
8151 .expect_err("its clips are still on the lanes")
8152 .to_string();
8153 assert!(refusal.contains("still plays"), "{refusal}");
8154 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
8155 while p.delete_in(Lane::V1, 0) {}
8156 p.remove_source(0)
8157 .expect("the last row goes like any other");
8158 assert!(
8159 p.sources().is_empty(),
8160 "a project may name no file at all: an empty library over an empty timeline"
8161 );
8162 assert_eq!(p.timeline_frames(), 0);
8163 assert!(
8164 p.remove_source(0).is_err(),
8165 "and an index that is not there is refused, not panicked on"
8166 );
8167 }
8168
8169 /// A clip's equalizer is the clip's: it survives every edit that copies a
8170 /// placement, and it comes back with an undo.
8171 #[test]
8172 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
8173 let mut p = three();
8174 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
8175 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
8176 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8177 assert!(
8178 p.eq_of(Lane::V1, 0).is_none(),
8179 "one clip, not the lane above"
8180 );
8181
8182 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
8183 assert!(p.split(1));
8184 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8185 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
8186 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
8187
8188 // A clipboard copy carries it -- onto another lane, at that.
8189 let copied = p.lane(Lane::A1)[1];
8190 assert!(p.place(Lane::V1, 20, copied));
8191 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
8192 assert!(p.undo());
8193 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
8194
8195 // ...and a change to one is one undo step, in both directions.
8196 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
8197 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
8198 assert!(p.undo());
8199 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8200 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
8201 assert!(p.eq_of(Lane::A1, 0).is_none());
8202 assert!(p.undo());
8203 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8204
8205 // Two refusals, neither of which costs an undo step.
8206 let mut nan = band_at(1);
8207 nan.bands[0].q = f32::INFINITY;
8208 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
8209 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
8210 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
8211 assert!(p.undo());
8212 assert_eq!(
8213 p.lane(Lane::A1).len(),
8214 3,
8215 "one step back is before the split"
8216 );
8217 assert!(p.undo());
8218 assert!(
8219 p.eq_of(Lane::A1, 0).is_none(),
8220 "and the next is before the setting: the refusals pushed none"
8221 );
8222 }
8223
8224 /// The table is append-only within a session, exactly as the sources are, so
8225 /// an undone setting is still in it -- and a save is where it goes.
8226 #[test]
8227 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
8228 let mut p = three();
8229 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
8230 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
8231 assert!(p.undo(), "back to the first setting");
8232 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
8233
8234 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8235 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
8236 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
8237 assert_eq!(lanes[0].1[1].eq, None);
8238
8239 // One curve on three clips is one entry: settings that are equal share.
8240 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
8241 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
8242 let (_, lanes, eq, _, _) = p.without_orphan_sources();
8243 assert_eq!(eq.len(), 1, "equal settings share their entry");
8244 assert_eq!(lanes[1].1[2].eq, Some(0));
8245 reloads(&p, "an equalizer that outlived an undo");
8246 }
8247
8248 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8249 /// grade is the clip's, through every edit that copies a placement.
8250 #[test]
8251 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
8252 let mut p = three();
8253 assert!(
8254 p.color_of(Lane::V1, 0).is_none(),
8255 "a fresh clip is ungraded"
8256 );
8257 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8258 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8259 assert!(
8260 p.color_of(Lane::A1, 0).is_none(),
8261 "one clip, not the lane below"
8262 );
8263 assert!(
8264 p.eq_of(Lane::V1, 0).is_none(),
8265 "and a grade is not an equalizer"
8266 );
8267
8268 // Cutting a graded clip must not grade half of it: both halves inherit.
8269 assert!(p.split(1));
8270 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8271 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
8272 assert!(
8273 p.color_of(Lane::V1, 2).is_none(),
8274 "the clip after it is ungraded"
8275 );
8276
8277 // A clipboard copy carries it -- onto another lane, at that.
8278 let copied = p.lane(Lane::V1)[1];
8279 assert!(p.place(Lane::A1, 20, copied));
8280 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
8281 assert!(p.undo());
8282 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8283
8284 // ...and a change to one is one undo step, in both directions.
8285 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
8286 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
8287 assert!(p.undo());
8288 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8289 assert!(
8290 p.set_color(Lane::V1, 0, None),
8291 "and taking it off is an edit"
8292 );
8293 assert!(p.color_of(Lane::V1, 0).is_none());
8294 assert!(p.undo());
8295 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8296
8297 // Two refusals, neither of which costs an undo step.
8298 let nan = ColorParams {
8299 contrast: f32::NAN,
8300 ..grade_at(1)
8301 };
8302 assert!(
8303 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
8304 "no clip there"
8305 );
8306 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
8307 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8308 assert!(p.undo());
8309 assert_eq!(
8310 p.lane(Lane::V1).len(),
8311 3,
8312 "one step back is before the split"
8313 );
8314 assert!(p.undo());
8315 assert!(
8316 p.color_of(Lane::V1, 0).is_none(),
8317 "and the next is before the grade: the refusals pushed none"
8318 );
8319 }
8320
8321 /// A slider drag is one gesture: the press snapshots, every sample after it
8322 /// only regrades, and the single undo lands on what the clip was *before*
8323 /// the hand touched it -- not one step back down the drag.
8324 #[test]
8325 fn a_whole_colour_drag_undoes_in_one_step() {
8326 let mut p = three();
8327 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
8328 for n in 2..=8 {
8329 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
8330 }
8331 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
8332 assert!(p.undo());
8333 assert!(
8334 p.color_of(Lane::V1, 0).is_none(),
8335 "one undo is the whole gesture, back to ungraded"
8336 );
8337
8338 // The live write refuses what the snapshotting one refuses, and a
8339 // refusal still costs no history either way.
8340 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
8341 assert!(!p.set_color_live(
8342 Lane::V1,
8343 0,
8344 Some(ColorParams {
8345 contrast: f32::NAN,
8346 ..grade_at(1)
8347 })
8348 ));
8349 assert!(p.undo());
8350 assert_eq!(
8351 p.lane(Lane::V1).len(),
8352 2,
8353 "the next step back is the split before the drag: no sample pushed one"
8354 );
8355 }
8356
8357 /// The colour table is append-only within a session, exactly as the eq one
8358 /// is -- and a save is where an undone grade goes.
8359 #[test]
8360 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
8361 let mut p = three();
8362 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
8363 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8364 assert!(p.undo(), "back to the first grade");
8365 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
8366
8367 let (_, lanes, _, color, _) = p.without_orphan_sources();
8368 assert_eq!(
8369 color,
8370 vec![grade_at(1)],
8371 "what nothing plays is not written"
8372 );
8373 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
8374 assert_eq!(lanes[0].1[1].color, None);
8375
8376 // One grade on three clips is one entry: settings that are equal share.
8377 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
8378 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
8379 let (_, lanes, _, color, _) = p.without_orphan_sources();
8380 assert_eq!(color.len(), 1, "equal grades share their entry");
8381 assert_eq!(lanes[1].1[2].color, Some(0));
8382 reloads(&p, "a colour that outlived an undo");
8383
8384 // An equalizer and a grade on one clip are two independent tables.
8385 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
8386 let (_, lanes, eq, color, _) = p.without_orphan_sources();
8387 assert_eq!((eq.len(), color.len()), (1, 1));
8388 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
8389 }
8390
8391 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8392 /// placement is the clip's, through every edit that copies one.
8393 #[test]
8394 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
8395 let mut p = three();
8396 assert!(
8397 p.transform_of(Lane::V1, 0).is_none(),
8398 "a fresh clip is untransformed"
8399 );
8400 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8401 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8402 assert!(
8403 p.transform_of(Lane::A1, 0).is_none(),
8404 "one clip, not the lane below"
8405 );
8406 assert!(
8407 p.color_of(Lane::V1, 0).is_none(),
8408 "and a placement is not a grade"
8409 );
8410
8411 // Cutting a transformed clip must not transform half of it: both
8412 // halves inherit.
8413 assert!(p.split(1));
8414 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8415 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
8416 assert!(
8417 p.transform_of(Lane::V1, 2).is_none(),
8418 "the clip after it is untransformed"
8419 );
8420
8421 // A clipboard copy carries it -- onto another lane, at that.
8422 let copied = p.lane(Lane::V1)[1];
8423 assert!(p.place(Lane::A1, 20, copied));
8424 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
8425 assert!(p.undo());
8426 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8427
8428 // ...and a change to one is one undo step, in both directions.
8429 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
8430 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
8431 assert!(p.undo());
8432 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8433 assert!(
8434 p.set_transform(Lane::V1, 0, None),
8435 "and taking it off is an edit"
8436 );
8437 assert!(p.transform_of(Lane::V1, 0).is_none());
8438 assert!(p.undo());
8439 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8440
8441 // Two refusals, neither of which costs an undo step.
8442 let nan = TransformParams {
8443 scale: f32::NAN,
8444 ..transform_at(1)
8445 };
8446 assert!(
8447 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
8448 "no clip there"
8449 );
8450 assert!(
8451 !p.set_transform(Lane::V1, 0, Some(nan)),
8452 "not a finite value"
8453 );
8454 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8455 assert!(p.undo());
8456 assert_eq!(
8457 p.lane(Lane::V1).len(),
8458 3,
8459 "one step back is before the split"
8460 );
8461 assert!(p.undo());
8462 assert!(
8463 p.transform_of(Lane::V1, 0).is_none(),
8464 "and the next is before the placement: the refusals pushed none"
8465 );
8466 }
8467
8468 /// The transform table is append-only within a session, exactly as the eq
8469 /// and colour ones are -- and a save is where an undone placement goes.
8470 #[test]
8471 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
8472 let mut p = three();
8473 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
8474 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8475 assert!(p.undo(), "back to the first placement");
8476 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
8477
8478 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8479 assert_eq!(
8480 transform,
8481 vec![transform_at(1)],
8482 "what nothing plays is not written"
8483 );
8484 assert_eq!(
8485 lanes[0].1[0].transform,
8486 Some(0),
8487 "and the survivor renumbers"
8488 );
8489 assert_eq!(lanes[0].1[1].transform, None);
8490
8491 // One placement on three clips is one entry: settings that are equal
8492 // share.
8493 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
8494 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
8495 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8496 assert_eq!(transform.len(), 1, "equal placements share their entry");
8497 assert_eq!(lanes[1].1[2].transform, Some(0));
8498 reloads(&p, "a transform that outlived an undo");
8499
8500 // A grade and a placement on one clip are two independent tables.
8501 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
8502 let (_, lanes, _, color, transform) = p.without_orphan_sources();
8503 assert_eq!((color.len(), transform.len()), (1, 1));
8504 assert_eq!(
8505 (lanes[0].1[0].color, lanes[0].1[0].transform),
8506 (Some(0), Some(0))
8507 );
8508 }
8509
8510 /// Not a claim about correctness but about cost: a clip is copied on every
8511 /// paste, every undo snapshot and every lane clone, so its size is worth
8512 /// knowing. The eq index fit the padding a `Copy` clip already had; the
8513 /// colour one did not, and the struct grew a word. The transform index is
8514 /// a third `Option<u16>`, and it fits the padding the fit policy and the
8515 /// transition byte already left behind, so the struct did not grow again.
8516 #[test]
8517 fn a_clip_is_still_a_small_copy() {
8518 assert_eq!(
8519 std::mem::size_of::<Clip>(),
8520 56,
8521 "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index"
8522 );
8523 }
8524
8525 #[test]
8526 fn from_parts_has_no_history_and_checks_the_invariants() {
8527 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
8528 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
8529 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
8530 .expect("valid parts");
8531 assert_eq!(p.clips(), three().clips());
8532 assert!(!p.undo(), "a loaded project has nothing to undo");
8533 assert!(p.split(4), "...and is editable from there");
8534 assert!(p.undo());
8535
8536 // A lane may be empty, and so may every lane -- an emptied timeline is a
8537 // project. No lane at all is not one: there would be nothing to place on.
8538 assert!(
8539 Project::from_parts(
8540 sources.clone(),
8541 two(video.clone(), Vec::new()),
8542 Vec::new(),
8543 Vec::new(),
8544 Vec::new(),
8545 )
8546 .is_ok()
8547 );
8548 assert!(
8549 Project::from_parts(
8550 sources.clone(),
8551 two(Vec::new(), Vec::new()),
8552 Vec::new(),
8553 Vec::new(),
8554 Vec::new(),
8555 )
8556 .is_ok()
8557 );
8558 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
8559 let bad: [Vec<Clip>; 5] = [
8560 vec![clip(0, 0, 3, 1)], // source that is not there
8561 vec![clip(0, 3, 3, 0)], // empty clip
8562 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
8563 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
8564 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
8565 ];
8566 for clips in bad {
8567 assert!(
8568 Project::from_parts(
8569 sources.clone(),
8570 two(clips.clone(), Vec::new()),
8571 Vec::new(),
8572 Vec::new(),
8573 Vec::new(),
8574 )
8575 .is_err(),
8576 "{clips:?}"
8577 );
8578 assert!(
8579 Project::from_parts(
8580 sources.clone(),
8581 two(video.clone(), clips.clone()),
8582 Vec::new(),
8583 Vec::new(),
8584 Vec::new(),
8585 )
8586 .is_err()
8587 );
8588 // ...and on a third lane, which is checked by the same walk.
8589 assert!(
8590 Project::from_parts(
8591 sources.clone(),
8592 vec![
8593 (LaneKind::Video, video.clone()),
8594 (LaneKind::Audio, audio.clone()),
8595 (LaneKind::Video, clips),
8596 ],
8597 Vec::new(),
8598 Vec::new(),
8599 Vec::new(),
8600 )
8601 .is_err()
8602 );
8603 }
8604 // An equalizer index no table entry answers, and a table entry the file
8605 // format could not have written, are refused at this door too.
8606 let eqd = |i: u16| {
8607 vec![Clip {
8608 fade_in: 0,
8609 fade_out: 0,
8610 transition_out: 0,
8611 eq: Some(i),
8612 ..video[0]
8613 }]
8614 };
8615 assert!(
8616 Project::from_parts(
8617 sources.clone(),
8618 two(eqd(0), Vec::new()),
8619 Vec::new(),
8620 Vec::new(),
8621 Vec::new(),
8622 )
8623 .is_err()
8624 );
8625 let mut nan = band_at(1);
8626 nan.bands[0].freq_hz = f32::NAN;
8627 assert!(
8628 Project::from_parts(
8629 sources.clone(),
8630 two(eqd(0), Vec::new()),
8631 vec![nan],
8632 Vec::new(),
8633 Vec::new(),
8634 )
8635 .is_err()
8636 );
8637 let loaded = Project::from_parts(
8638 sources.clone(),
8639 two(eqd(0), Vec::new()),
8640 vec![band_at(1)],
8641 Vec::new(),
8642 Vec::new(),
8643 )
8644 .expect("an eq the table holds");
8645 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
8646
8647 // The same two refusals for a colour, at the same door.
8648 let graded = |i: u16| {
8649 vec![Clip {
8650 fade_in: 0,
8651 fade_out: 0,
8652 transition_out: 0,
8653 color: Some(i),
8654 fit: FitPolicy::default(),
8655 speed: Speed::NORMAL,
8656 ..video[0]
8657 }]
8658 };
8659 assert!(
8660 Project::from_parts(
8661 sources.clone(),
8662 two(graded(0), Vec::new()),
8663 Vec::new(),
8664 Vec::new(),
8665 Vec::new(),
8666 )
8667 .is_err(),
8668 "a colour index no entry answers"
8669 );
8670 assert!(
8671 Project::from_parts(
8672 sources.clone(),
8673 two(graded(0), Vec::new()),
8674 Vec::new(),
8675 vec![ColorParams {
8676 tint: f32::NAN,
8677 ..grade_at(1)
8678 }],
8679 Vec::new(),
8680 )
8681 .is_err(),
8682 "a value the file format could not have written"
8683 );
8684 let loaded = Project::from_parts(
8685 sources.clone(),
8686 two(graded(0), Vec::new()),
8687 Vec::new(),
8688 vec![grade_at(1)],
8689 Vec::new(),
8690 )
8691 .expect("a colour the table holds");
8692 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
8693
8694 // Group ids survive a load, and the next split gets a fresh one.
8695 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
8696 assert!(p.split(4));
8697 assert!(p.clips().iter().all(|c| c.link.is_some()));
8698 }
8699
8700 /// The grouping rules, at the untrusted door and after every edit that can
8701 /// touch a link. A link id is at most one placement per lane -- a clip or a
8702 /// caption, whichever carries it -- and no sequence of edits may produce
8703 /// otherwise, because what an edit produces is what a save writes and a load
8704 /// reads.
8705 ///
8706 /// Amended for the offset-preserving group: the members keep their own
8707 /// spans, so two placements of one id covering different frames is *legal*
8708 /// -- it is what a hand-built group is -- and the only refusal left is the
8709 /// doubled id inside one lane.
8710 #[test]
8711 fn a_link_id_is_never_two_clips_of_one_lane() {
8712 let sources = vec![Source::new(FILE, 0)];
8713 let linked = |start, in_frame, out_frame, link| Clip {
8714 fade_in: 0,
8715 fade_out: 0,
8716 transition_out: 0,
8717 start,
8718 in_frame,
8719 out_frame,
8720 source: 0,
8721 link: Some(link),
8722 eq: None,
8723 color: None,
8724 transform: None,
8725 fit: FitPolicy::default(),
8726 speed: Speed::NORMAL,
8727 };
8728
8729 // The door: a doubled id inside one lane, refused by name.
8730 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
8731 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
8732 .expect_err("refused")
8733 .to_string()
8734 };
8735 assert!(
8736 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
8737 .contains("link 7 names two clips in the V1 lane"),
8738 "a duplicate id inside one lane is refused by name"
8739 );
8740 // ...and the same doubling on a subtitle lane, in its own words: a
8741 // caption is the other placement an id may name.
8742 let caption = |start: u32, frames: u32, link| SubClip {
8743 start,
8744 frames,
8745 track: 0,
8746 in_us: 0,
8747 out_us: i64::from(frames) * 1_000_000,
8748 link: Some(link),
8749 };
8750 let subs = LaneData {
8751 clips: Vec::new(),
8752 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
8753 ..LaneData::new(LaneKind::Subtitle, Vec::new())
8754 };
8755 assert_eq!(
8756 links_are_consistent(&[subs]).unwrap_err().to_string(),
8757 "link 7 names two captions in the S1 lane"
8758 );
8759 // A pair covering *different* frames is legal now: the members of a
8760 // hand-built group keep their own spans, and what binds them is the id.
8761 let apart = Project::from_parts(
8762 sources.clone(),
8763 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
8764 Vec::new(),
8765 Vec::new(),
8766 Vec::new(),
8767 );
8768 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
8769 // A one-sided link is *not* an error: it is what a lift leaves behind.
8770 let mut p = Project::single(FILE, 9);
8771 assert!(p.lift(Lane::A1, 0));
8772 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
8773 assert!(
8774 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
8775 "a lifted lane's project has to load again"
8776 );
8777
8778 // The edits: nothing below may break either rule.
8779 let consistent = |p: &Project, what: &str| {
8780 assert!(
8781 links_are_consistent(&p.lanes).is_ok(),
8782 "{what}: {:?}",
8783 p.lanes
8784 );
8785 };
8786 let mut p = three();
8787 let copied = p.clips()[0];
8788 assert!(
8789 copied.link.is_some(),
8790 "the clipboard clip carries its group"
8791 );
8792 assert!(p.lift(Lane::V1, 0));
8793 assert!(p.place(Lane::V1, 0, copied));
8794 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
8795 assert_eq!(
8796 p.clips().iter().filter(|c| c.link == copied.link).count(),
8797 0,
8798 "a placement belongs to no group, so it cannot duplicate one"
8799 );
8800 consistent(&p, "lift + place twice");
8801 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
8802 consistent(&p, "place through a grouped clip");
8803 assert!(p.paste(6, copied), "a rippling paste through another");
8804 consistent(&p, "paste");
8805 assert!(p.split(2));
8806 consistent(&p, "split");
8807 assert!(p.ripple_delete(1, 3));
8808 consistent(&p, "ripple_delete");
8809 assert!(p.undo());
8810 consistent(&p, "undo");
8811 }
8812
8813 /// What an edit produces is what a save writes, so *every* state the public
8814 /// API can reach has to load again. The two the verifier panel found where
8815 /// it did not: a split and a regroup handed one group id to two clips that
8816 /// were not the same span, because the lanes had been edited apart.
8817 #[test]
8818 fn every_reachable_state_reloads() {
8819 let mut p = Project::single(FILE, 150);
8820 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
8821 assert!(p.split(10), "the lanes are cut apart at 10");
8822 reloads(&p, "place on one lane, then split");
8823
8824 let mut p = Project::single(FILE, 150);
8825 assert!(p.split(30));
8826 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
8827 assert!(p.regroup(30), "only the audio lane can rejoin");
8828 assert!(p.split(60));
8829 reloads(&p, "lift, regroup one lane, split");
8830
8831 // Two audio streams of one file, both placed: two source entries with
8832 // one path between them, which is the state a stream picked out of the
8833 // library reaches -- and the state a save has to write and read back.
8834 let mut p = Project::single(FILE, 150);
8835 let second = p.import(FILE, 1);
8836 assert_eq!(second, 1, "the same file on another stream is a new source");
8837 assert!(p.append_clip(second, 150));
8838 assert!(p.split(200));
8839 reloads(
8840 &p,
8841 "a second audio stream of the same file, placed and split",
8842 );
8843 let (sources, ..) = p.without_orphan_sources();
8844 assert_eq!(
8845 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
8846 [0, 1],
8847 "both entries survive the orphan prune: both are played"
8848 );
8849 }
8850
8851 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
8852 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
8853 /// is the stamp playback puts on a decoded source frame -- and the *last*
8854 /// source frame the pump is still holding at a timeline frame has to be
8855 /// exactly the one the export encoded there, at every rate. Anything else is
8856 /// A/V drift that grows with the clip, and no test of either side alone
8857 /// would see it.
8858 ///
8859 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
8860 /// is a better answer than the floor/floor this had: floor/floor put the
8861 /// preview a whole held frame off the export at slow rates.)
8862 #[test]
8863 fn speed_maps_both_ways() {
8864 for permille in (250..=4000).step_by(1) {
8865 let speed = Speed::from_permille(permille);
8866 assert_eq!(speed.permille(), permille, "no clamping in range");
8867 for d in 0..200u32 {
8868 let want = speed.source_at(d);
8869 // What the pump shows at `d` is the last frame whose stamp has
8870 // come due -- and it is `want`, the frame the export encodes
8871 // there. Slowed, that is the frame it is still holding; sped up,
8872 // it is the newest of the several that arrived.
8873 let held = (0..=want + 8)
8874 .filter(|&s| speed.timeline_at(s) <= d)
8875 .next_back();
8876 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
8877 }
8878 for n in 1..300u32 {
8879 // A footprint is never zero: a clip occupying no timeline frame
8880 // is a placement the lane invariants cannot hold.
8881 let frames = speed.frames(n);
8882 assert!(frames >= 1, "{speed} of {n} frames");
8883 // ...and its last timeline frame never reads past the clip.
8884 assert!(
8885 speed.source_at(frames - 1) < n,
8886 "{speed}: the last timeline frame of {n} reads past the clip"
8887 );
8888 // The trim inverse never overshoots the room it was given, and
8889 // answers for every room a footprint can be.
8890 let fit = speed.fit(frames).expect("a clip fits its own footprint");
8891 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
8892 // A room narrower than one source frame's own footprint holds
8893 // nothing, and says so rather than rounding something into it.
8894 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
8895 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
8896 }
8897 }
8898 // Real time is the identity map, byte for byte.
8899 for d in 0..1000 {
8900 assert_eq!(Speed::NORMAL.source_at(d), d);
8901 assert_eq!(Speed::NORMAL.timeline_at(d), d);
8902 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
8903 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
8904 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
8905 }
8906 // The one door: no zero, no reverse, nothing past the ends.
8907 assert_eq!(Speed::from_permille(0), Speed::MIN);
8908 assert_eq!(Speed::from_permille(249), Speed::MIN);
8909 assert_eq!(Speed::from_permille(4001), Speed::MAX);
8910 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
8911 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
8912 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
8913 }
8914
8915 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
8916 /// export encodes at a timeline frame is the one playback is holding there,
8917 /// a file is as long in timeline frames as the seconds it lasts, and the two
8918 /// compose so a speeded clip at another rate is exactly both.
8919 #[test]
8920 fn rate_composes_with_speed() {
8921 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
8922 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
8923 // the identity map or a single-rate project would move.
8924 for (source_fps, timeline_fps) in [
8925 (24000. / 1001., 30.),
8926 (30., 24000. / 1001.),
8927 (60., 30.),
8928 (25., 30.),
8929 (30., 30.),
8930 ] {
8931 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
8932 for n in 0..2000u32 {
8933 let source = rate.source_at(n);
8934 // The stamp is the *first* timeline-rate frame that shows it, so
8935 // the picture on screen at `n` is the picture encoded at `n`.
8936 let held = (0..=source + 4)
8937 .filter(|&s| rate.timeline_at(s) <= n)
8938 .next_back();
8939 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
8940 }
8941 // A file of `count` frames is `timeline_at(count)` frames long here,
8942 // and its last one still reads a frame the file has.
8943 for count in 1..500u32 {
8944 let frames = rate.timeline_at(count);
8945 assert!(frames >= 1, "a file is never zero frames long");
8946 assert!(
8947 rate.source_at(frames - 1) < count,
8948 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
8949 );
8950 }
8951 // No drift: the mapping is one exact division of the *rate itself*,
8952 // not an accumulation and not a rounded rate, so an hour in is as
8953 // true as the first second. (Held to the real ratio of the two rates
8954 // the caller asked for -- `as_f64` would be true of a wrong rate.)
8955 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
8956 let want = f64::from(n) * source_fps / timeline_fps;
8957 assert!(
8958 (f64::from(rate.source_at(n)) - want).abs() < 1.,
8959 "{source_fps} on {timeline_fps}: frame {n} drifted"
8960 );
8961 }
8962 }
8963 // The timeline's own rate is the identity, whichever way it is written.
8964 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
8965 assert!(
8966 Rate::from_fps(30.0004, 30.)
8967 .expect("30.0004 over 30")
8968 .is_real_time(),
8969 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
8970 );
8971 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
8972 // one thing `matches_timeline` refuses a file for now that the rate gate
8973 // is gone.
8974 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
8975 assert!(Rate::from_fps(30., f64::NAN).is_err());
8976 for n in 0..1000 {
8977 assert_eq!(Rate::REAL_TIME.source_at(n), n);
8978 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
8979 }
8980 // ...and the composition, in the order the decoder's door applies it:
8981 // the speed picks the clip's (timeline-rate) frame, the rate picks the
8982 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
8983 // timeline frames per frame shown, each of them exactly 800/1001 of a
8984 // file frame.
8985 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
8986 let speed = Speed::from_permille(2000);
8987 for d in 0..100u32 {
8988 assert_eq!(
8989 rate.source_at(speed.source_at(d)),
8990 (u64::from(d) * 2 * 800 / 1001) as u32,
8991 "2x of a 23.976 fps file at timeline frame {d}"
8992 );
8993 }
8994 }
8995
8996 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
8997 /// source frames per timeline frame and still starts at its own in-point,
8998 /// and a half-speed one shows every source frame twice.
8999 #[test]
9000 fn a_rate_maps_timeline_frames_onto_source_frames() {
9001 let mut p = Project::single(FILE, 40);
9002 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9003 .expect("room enough");
9004 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
9005 assert_eq!(
9006 p.map(Lane::V1, 0),
9007 Some((0, 0)),
9008 "and it starts where it did"
9009 );
9010 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
9011 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
9012 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
9013 // The span a decoder is handed: as many source frames as it will read,
9014 // which is the last shown frame's own and not one more -- timeline frame
9015 // 19 shows source frame 38, so 39 frames are read and the 40th is a
9016 // picture nothing would display.
9017 let span = p.span_at(Lane::V1, 0).expect("a span");
9018 assert_eq!((span.len, span.source_len()), (20, 39));
9019 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
9020 // ...and the same clip the other way round.
9021 let mut p = Project::single(FILE, 40);
9022 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9023 .expect("room enough");
9024 assert_eq!(p.timeline_frames(), 80);
9025 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
9026 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
9027 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
9028 assert_eq!(
9029 p.map(Lane::V1, 79),
9030 Some((0, 39)),
9031 "and the last timeline frame is still inside the source range"
9032 );
9033 }
9034
9035 /// A trim of a speeded clip is still a trim of its *source*, and the edge
9036 /// still stops at the wall: the room a rate leaves is measured in timeline
9037 /// frames and the range it commits in source ones.
9038 #[test]
9039 fn trimming_a_speeded_clip_stays_inside_its_room() {
9040 let mut p = Project::single(FILE, 40);
9041 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
9042 .expect("room enough");
9043 // A second clip butted against the first, so the wall is a real one.
9044 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
9045 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
9046 assert_eq!(room, (1, 20), "out to the neighbour and no further");
9047 assert!(
9048 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
9049 "clamped to the wall, which is where the edge already is"
9050 );
9051 let c = p.clips()[0];
9052 assert_eq!(c.end(), 20, "so nothing moved");
9053 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
9054 // ...and in: half the timeline frames is half the source range.
9055 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
9056 let c = p.clips()[0];
9057 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
9058 assert_eq!(c.end(), 10, "and ten timeline frames of them");
9059 assert!(sorted_disjoint(p.clips()));
9060 }
9061
9062 /// The frames a rate cannot address: at half speed each source frame is on
9063 /// screen twice, and the cut between the two showings is not a cut in the
9064 /// file. Refused, so the two halves always add up to the clip that was cut.
9065 #[test]
9066 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
9067 let mut p = Project::single(FILE, 10);
9068 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
9069 .expect("room enough");
9070 assert_eq!(p.timeline_frames(), 20);
9071 assert!(
9072 !p.split(3),
9073 "an odd frame is between two showings of one frame"
9074 );
9075 assert_eq!(p.clips().len(), 1, "and nothing was cut");
9076 assert!(p.split(4), "an even one is a frame boundary");
9077 let halves = p.clips().to_vec();
9078 assert_eq!(
9079 (halves[0].end(), halves[1].start, halves[1].end()),
9080 (4, 4, 20),
9081 "the halves meet, and still end where the clip did"
9082 );
9083 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
9084 assert!(p.regroup(4), "and the inverse puts it back");
9085 assert_eq!(p.clips().len(), 1);
9086 }
9087
9088 /// The same claim, swept: random op sequences off the public surface, the
9089 /// project reloaded after every one of them. A failure prints its seed, and
9090 /// the seed replays the whole sequence.
9091 #[test]
9092 fn random_edit_sequences_reload() {
9093 // Two thousand, not two hundred: the overlap a hole punched into a slow
9094 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
9095 // sequences, and a 200-seed sweep walked straight past it (it took a
9096 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
9097 // has no business being the narrow one.
9098 for seed in 0..2000u64 {
9099 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9100 let mut next = move |n: u32| {
9101 // xorshift64*: no dependency, and the seed replays it exactly.
9102 rng ^= rng << 13;
9103 rng ^= rng >> 7;
9104 rng ^= rng << 17;
9105 (rng >> 33) as u32 % n
9106 };
9107 let mut p = Project::single(FILE, 40);
9108 for step in 0..24 {
9109 let frame = next(44);
9110 // A clipboard copy carries the group id of the take it came from
9111 // -- the input that made a placement duplicate an id -- and, one
9112 // time in three, a rate of its own: a *speeded clip placed over
9113 // a speeded clip* is the shape whose remainders have to be run
9114 // through `Speed::fit`, and it is not a shape the lanes hand out
9115 // on their own often enough to be sure of.
9116 let mut copied = *p
9117 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
9118 .get(next(4) as usize)
9119 .unwrap_or(&clip(0, 0, 5, 0));
9120 if next(3) == 0 {
9121 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
9122 }
9123 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
9124 let idx = next(4) as usize;
9125 let _ = match next(16) {
9126 // A clip dragged along its own lane to wherever the pointer
9127 // let it go: the op that moves a placement without changing
9128 // what it plays, so what it may not do is land on top of the
9129 // neighbour it was dragged at.
9130 15 => p.move_clip(lane, idx, lane, frame),
9131 // ...and a second `place`, so a punch lands inside a clip
9132 // far more often than one op in fourteen would put it there.
9133 14 => p.place(lane, frame, copied),
9134 0 => p.split(frame),
9135 1 => p.regroup(frame),
9136 2 => p.lift(lane, idx),
9137 3 => p.place(lane, frame, copied),
9138 4 => p.paste(frame, copied),
9139 5 => p.ripple_delete(frame, next(9)),
9140 6 => p.delete(idx),
9141 7 => p.undo(),
9142 // An equalizer put on and taken off in the mix: what a clip
9143 // carries has to reload with it, and the entries an undo
9144 // orphans must not come back out of the prune.
9145 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9146 9 => p.set_eq(lane, idx, None),
9147 // ...and a colour grade in the same mix, for the same
9148 // reason: it rides on the clip and its orphans must go.
9149 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
9150 11 => p.set_color(lane, idx, None),
9151 // ...and a rate in with them, which is the one of the three
9152 // that moves *placements*: a clip that grew has to be
9153 // refused rather than overlap, and one that shrank leaves a
9154 // lane that still loads. Both are what `reloads` asks.
9155 12 => p
9156 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9157 .is_ok(),
9158 _ => p.append_clip(0, 1 + next(9)),
9159 };
9160 reloads(&p, &format!("seed {seed}, step {step}"));
9161 }
9162 }
9163 }
9164
9165 /// The save/load round trip a project must survive: the parts a save writes,
9166 /// handed back to the constructor a load goes through -- every lane of them,
9167 /// and the reloaded timeline has to be the same lanes in the same order.
9168 fn reloads(p: &Project, what: &str) {
9169 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
9170 match Project::from_parts(sources, lanes, eq, color, transform) {
9171 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
9172 Ok(back) => {
9173 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
9174 // Placements, not whole clips: an orphan prune renumbers the
9175 // sources a clip names, which is the point of it.
9176 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
9177 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
9178 };
9179 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
9180 // The prune renumbers the eq table too, so what has to survive
9181 // is the settings themselves, clip by clip.
9182 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
9183 p.lanes()
9184 .into_iter()
9185 .map(|l| {
9186 (0..p.lane(l).len())
9187 .map(|i| p.eq_of(l, i).cloned())
9188 .collect()
9189 })
9190 .collect()
9191 };
9192 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
9193 // The colour table renumbers in the same prune, so the same
9194 // claim: the params a clip names, not the index it names them by.
9195 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
9196 p.lanes()
9197 .into_iter()
9198 .map(|l| {
9199 (0..p.lane(l).len())
9200 .map(|i| p.color_of(l, i).copied())
9201 .collect()
9202 })
9203 .collect()
9204 };
9205 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
9206 // ...and the transform table, by the same claim again.
9207 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
9208 p.lanes()
9209 .into_iter()
9210 .map(|l| {
9211 (0..p.lane(l).len())
9212 .map(|i| p.transform_of(l, i).copied())
9213 .collect()
9214 })
9215 .collect()
9216 };
9217 assert_eq!(
9218 transforms(&back),
9219 transforms(p),
9220 "{what}: the transforms changed"
9221 );
9222 }
9223 }
9224 }
9225
9226 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
9227 /// -- each one sorted and disjoint, and one span per group id -- asserted
9228 /// directly, where the point is the invariant rather than the round trip.
9229 fn invariants_hold(p: &Project, what: &str) {
9230 for lane in p.lanes() {
9231 assert!(
9232 sorted_disjoint(p.lane(lane)),
9233 "{what}: {} is out of order or overlaps itself: {:?}",
9234 lane.label(),
9235 p.lane(lane)
9236 );
9237 }
9238 if let Err(e) = links_are_consistent(&p.lanes) {
9239 panic!("{what}: {e}\n{:?}", p.lanes);
9240 }
9241 }
9242
9243 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
9244 /// edited without any other lane hearing about it. A handle naming a lane
9245 /// that is not there reads as empty and refuses to mutate.
9246 #[test]
9247 fn a_third_lane_is_a_peer() {
9248 let mut p = three();
9249 assert_eq!(p.lane_count(LaneKind::Video), 1);
9250 assert_eq!(p.lane_count(LaneKind::Audio), 1);
9251 let v2 = p.add_lane(LaneKind::Video);
9252 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
9253 assert_eq!(v2.label(), "V2");
9254 assert_eq!(p.lane_count(LaneKind::Video), 2);
9255 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9256 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
9257
9258 // A handle for a lane that is not there: empty, and no mutation takes.
9259 let v3 = Lane::new(LaneKind::Video, 2);
9260 assert!(p.lane(v3).is_empty());
9261 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
9262 assert!(!p.lift(v3, 0));
9263 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
9264
9265 // Placing on V2 moves nothing else, and the lane can outrun the rest.
9266 let before = shape(&p);
9267 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9268 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
9269 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
9270 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9271 assert_eq!(
9272 p.timeline_frames(),
9273 16,
9274 "the last lane to end sets the length"
9275 );
9276 assert_eq!(p.map(v2, 5), Some((0, 21)));
9277 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
9278 assert_eq!(
9279 p.span_at(v2, 0),
9280 Some(Span {
9281 start: 0,
9282 len: 4,
9283 from: None,
9284 speed: Speed::NORMAL
9285 })
9286 );
9287 // Every lane still covers the whole timeline, gaps included.
9288 for l in p.lanes() {
9289 let spans = p.spans_from(l, 0);
9290 assert_eq!(
9291 spans.iter().map(|s| s.len).sum::<u32>(),
9292 16,
9293 "{}",
9294 l.label()
9295 );
9296 }
9297 // ...and playback still reads V1 and A1, whatever else is there.
9298 assert_eq!(p.clips(), p.lane(Lane::V1));
9299 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
9300 let segments = p.segments_from(0, FPS);
9301 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
9302 assert_eq!(
9303 segments[3],
9304 (None, 0.0, 7.0 / FPS),
9305 "A1 keeps the clock counting over the picture V2 added"
9306 );
9307 invariants_hold(&p, "place on V2");
9308
9309 // A lift is that lane's business too, and the lane list undoes.
9310 assert!(p.lift(v2, 0));
9311 assert!(p.lane(v2).is_empty());
9312 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
9313 assert!(p.undo());
9314 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9315 assert!(p.undo());
9316 assert!(p.lane(v2).is_empty(), "the placement came off V2");
9317 assert!(p.undo(), "and one more step takes the lane itself back");
9318 assert_eq!(p.lane_count(LaneKind::Video), 1);
9319 assert_eq!(shape(&p), shape(&three()));
9320 }
9321
9322 /// The add taken back: an empty lane comes off, a lane holding clips never
9323 /// does (and says which clips), the last lane of a kind never does, the
9324 /// lanes below the one that went move up an `ord`, and one undo puts it
9325 /// back where it stood.
9326 #[test]
9327 fn an_empty_lane_comes_off_again() {
9328 let mut p = three();
9329 let v2 = p.add_lane(LaneKind::Video);
9330 let v3 = p.add_lane(LaneKind::Video);
9331 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
9332 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
9333 let history = p.history.len();
9334
9335 // The last lane of its kind stays: `V1`/`A1` are where an import and a
9336 // paste land, and a project missing one would swallow half of a file
9337 // dropped on it.
9338 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
9339 assert_eq!(
9340 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
9341 "there is no V10 to remove"
9342 );
9343
9344 // A lane with clips on it refuses and names them: a track removal never
9345 // deletes a take.
9346 let refusal = why(p.remove_lane(v3));
9347 assert!(refusal.contains("V3 still holds"), "{refusal}");
9348 assert!(refusal.contains(FILE), "{refusal}");
9349 assert!(refusal.contains("at frame 0"), "{refusal}");
9350 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
9351 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
9352
9353 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
9354 // all.
9355 p.remove_lane(v2).expect("V2 is empty");
9356 assert_eq!(p.lane_count(LaneKind::Video), 2);
9357 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9358 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
9359 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
9360 invariants_hold(&p, "remove V2");
9361
9362 // ...and one stroke puts the empty lane back above it.
9363 assert!(p.undo());
9364 assert_eq!(p.lane_count(LaneKind::Video), 3);
9365 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
9366 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
9367 }
9368
9369 /// A track dragged to another place in the stack: the whole lane travels --
9370 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
9371 /// a video one, a lane that crosses one of its own kind swaps names with it
9372 /// (and swaps the composite with it), one undo puts the order back, and a
9373 /// save carries it.
9374 #[test]
9375 fn a_track_is_dragged_to_another_place_in_the_stack() {
9376 let mut p = three();
9377 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
9378 let before = shape(&p);
9379 let history = p.history.len();
9380
9381 // A1 over V1: the screen is rearranged and nothing else is. Both keep
9382 // their names -- neither crossed a lane of its own kind -- so every
9383 // handle a front-end holds still names the track it named before.
9384 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
9385 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
9386 assert_eq!(
9387 shape(&p),
9388 vec![before[1].clone(), before[0].clone()],
9389 "each lane's clips travelled with it, and none was remapped"
9390 );
9391 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
9392 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
9393 invariants_hold(&p, "A1 over V1");
9394
9395 // Nothing moves for a lane that is not there, a slot that is not, or a
9396 // lane already standing in the one it was pointed at.
9397 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
9398 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
9399 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
9400 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
9401
9402 // ...and one stroke puts the order back.
9403 assert!(p.undo());
9404 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
9405 assert_eq!(shape(&p), before);
9406
9407 // A second video lane over the first: display order *is* the stack, so
9408 // the last video lane covering a frame is the picture that shows.
9409 let v2 = p.add_lane(LaneKind::Video);
9410 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
9411 let over = shape(&p)[2].clone();
9412 assert_eq!(
9413 p.composite_span_at(0).map(|s| s.len),
9414 Some(5),
9415 "V2's five frames are what frame 0 shows"
9416 );
9417
9418 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
9419 // a position among the lanes of its kind. The picture that wins changes
9420 // with it: the take that was covering is the covered one now.
9421 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
9422 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
9423 assert_eq!(
9424 shape(&p),
9425 vec![over.clone(), before[0].clone(), before[1].clone()],
9426 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
9427 );
9428 assert_eq!(
9429 p.composite_span_at(0).map(|s| s.len),
9430 Some(3),
9431 "the lower video lane wins, and it is the old V1 now"
9432 );
9433 invariants_hold(&p, "V2 over V1");
9434
9435 // A save writes that order and a load takes it back.
9436 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9437 assert_eq!(
9438 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9439 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
9440 );
9441 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
9442 assert_eq!(back.lanes(), p.lanes());
9443 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
9444
9445 assert!(p.undo(), "and the stack goes back to how it stood");
9446 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
9447 }
9448
9449 /// The grouping rule across more than two lanes, under the offset model: a
9450 /// split *keeps* the group on the left halves and hands the right halves of
9451 /// that group one fresh id of their own -- a clip in no group comes out of
9452 /// the cut in none. So a take cut apart is two takes, one per side, and a
9453 /// lane that was never part of it stays out of both.
9454 #[test]
9455 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
9456 let mut p = Project::single(FILE, 9);
9457 let take = p.clips()[0].link.expect("a fresh project is one take");
9458 let v2 = p.add_lane(LaneKind::Video);
9459 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
9460 assert!(p.split(4));
9461 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
9462 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
9463 };
9464 let (left, right) = (side(&p, 0), side(&p, 1));
9465 // The lanes in order are V1, A1, V2: the take's two keep its id on the
9466 // left, and the placed clip never had one for the cut to keep.
9467 assert_eq!(
9468 left,
9469 vec![Some(take), Some(take), None],
9470 "the left halves keep the take"
9471 );
9472 // ...and the right halves of that take are one fresh group.
9473 assert_eq!(right[0], right[1]);
9474 assert_ne!(right[0], Some(take));
9475 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
9476 invariants_hold(&p, "split across three lanes");
9477
9478 // V2 ends early: the left halves still keep what each clip carried --
9479 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
9480 // shared by exactly the take's lanes.
9481 let mut p = Project::single(FILE, 9);
9482 let v2 = p.add_lane(LaneKind::Video);
9483 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
9484 assert!(p.split(3));
9485 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
9486 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
9487 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
9488 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
9489 invariants_hold(&p, "split where one lane ends early");
9490
9491 // The inverse rejoins each lane into the group its left half kept.
9492 assert!(p.regroup(3));
9493 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
9494 assert_eq!(
9495 p.lane(Lane::V1)[0].link,
9496 Some(take),
9497 "the take's id is back, not a fresh one"
9498 );
9499 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
9500 invariants_hold(&p, "regroup across three lanes");
9501 }
9502
9503 /// A group is one placement per lane, on however many lanes carry the id --
9504 /// not a video/audio pair and not a pairing by `ord` -- and the members may
9505 /// cover whatever frames they cover: the offset between them is what a
9506 /// hand-built group keeps. Lanes built by hand, because the rule is checked
9507 /// at the untrusted door and no edit can produce the one thing it refuses.
9508 #[test]
9509 fn a_group_may_span_any_lane() {
9510 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
9511 let one = |start: u32, end: u32, link| Clip {
9512 fade_in: 0,
9513 fade_out: 0,
9514 transition_out: 0,
9515 start,
9516 in_frame: start,
9517 out_frame: end,
9518 source: 0,
9519 link: Some(link),
9520 eq: None,
9521 color: None,
9522 transform: None,
9523 fit: FitPolicy::default(),
9524 speed: Speed::NORMAL,
9525 };
9526 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
9527 let kinds = [
9528 LaneKind::Video,
9529 LaneKind::Audio,
9530 LaneKind::Video,
9531 LaneKind::Audio,
9532 ];
9533 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
9534 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
9535 };
9536 let take = || vec![one(0, 4, 7)];
9537 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
9538 // The same take on V1 + A2 only, the lanes between it empty: legal, the
9539 // way a lifted half is legal.
9540 let across = build([take(), Vec::new(), Vec::new(), take()]);
9541 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
9542 // ...and so is a group whose members disagree about their spans: the
9543 // offset between them is the hand's business, not the loader's.
9544 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
9545 assert!(
9546 links_are_consistent(&apart).is_ok(),
9547 "[0, 4) on V1 and [2, 6) on A2 are one group"
9548 );
9549 // One id twice in one lane is still that lane's error, by name.
9550 let twice = build([
9551 Vec::new(),
9552 Vec::new(),
9553 vec![one(0, 4, 7), one(4, 8, 7)],
9554 Vec::new(),
9555 ]);
9556 assert_eq!(
9557 links_are_consistent(&twice).unwrap_err().to_string(),
9558 "link 7 names two clips in the V2 lane"
9559 );
9560 }
9561
9562 /// Every lane a save writes comes out, in display order and with its kind --
9563 /// an empty one included, since it is state a front-end shows -- and a
9564 /// two-lane project still writes exactly the parts it always did.
9565 #[test]
9566 fn a_save_writes_every_lane_it_has() {
9567 let mut p = three();
9568 let before = p.without_orphan_sources();
9569 assert_eq!(before.1.len(), 2, "V1 and A1");
9570 let v2 = p.add_lane(LaneKind::Video);
9571 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9572 let a2 = p.add_lane(LaneKind::Audio);
9573 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9574 assert_eq!(
9575 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9576 [
9577 LaneKind::Video,
9578 LaneKind::Audio,
9579 LaneKind::Video,
9580 LaneKind::Audio
9581 ],
9582 "display order, not video-then-audio"
9583 );
9584 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
9585 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
9586 // ...and all four load again as the same four.
9587 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
9588 assert_eq!(back.lanes(), p.lanes());
9589 assert_eq!(back.lane(a2), p.lane(a2));
9590
9591 // Taking the lanes back leaves exactly what a two-lane save wrote.
9592 for _ in 0..3 {
9593 assert!(p.undo());
9594 }
9595 assert_eq!(
9596 p.without_orphan_sources(),
9597 before,
9598 "byte for byte the same parts a two-lane save always wrote"
9599 );
9600 }
9601
9602 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
9603 /// three lanes and grows more: every lane's own order and the one
9604 /// span-per-id rule after every op, *and* the reload the v4 format restored
9605 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
9606 /// project of any number of lanes.
9607 #[test]
9608 fn random_edit_sequences_keep_many_lanes_consistent() {
9609 for seed in 0..2000u64 {
9610 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9611 let mut next = move |n: u32| {
9612 rng ^= rng << 13;
9613 rng ^= rng >> 7;
9614 rng ^= rng << 17;
9615 (rng >> 33) as u32 % n
9616 };
9617 let mut p = Project::single(FILE, 40);
9618 let v2 = p.add_lane(LaneKind::Video);
9619 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
9620 let lanes = [Lane::V1, Lane::A1, v2];
9621 for step in 0..24 {
9622 let frame = next(44);
9623 let copied = *p
9624 .lane(lanes[next(3) as usize])
9625 .get(next(4) as usize)
9626 .unwrap_or(&clip(0, 0, 5, 0));
9627 let lane = lanes[next(3) as usize];
9628 let idx = next(4) as usize;
9629 let _ = match next(14) {
9630 // The drag, in the mix: a clip dragged along its own lane
9631 // and onto another one, at a frame the pointer picked --
9632 // which is where the group rule and the sorted+disjoint one
9633 // meet, since every half travels the same distance.
9634 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
9635 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9636 11 => p.set_eq(lane, idx, None),
9637 // A rate, which on many lanes is the group rule as well:
9638 // every clip carrying the link moves together or none of
9639 // them does, and `invariants_hold` is what says so.
9640 12 => p
9641 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9642 .is_ok(),
9643 0 => p.split(frame),
9644 1 => p.regroup(frame),
9645 2 => p.lift(lane, idx),
9646 3 => p.place(lane, frame, copied),
9647 4 => p.paste(frame, copied),
9648 5 => p.ripple_delete(frame, next(9)),
9649 6 => p.delete(idx),
9650 7 => p.undo(),
9651 8 => {
9652 p.add_lane(if next(2) == 0 {
9653 LaneKind::Video
9654 } else {
9655 LaneKind::Audio
9656 });
9657 true
9658 }
9659 _ => p.append_clip(0, 1 + next(9)),
9660 };
9661 invariants_hold(&p, &format!("seed {seed}, step {step}"));
9662 reloads(&p, &format!("seed {seed}, step {step}"));
9663 }
9664 }
9665 }
9666
9667 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
9668 /// there, `V1` shows again on either side of it, and a frame no video lane
9669 /// covers is a gap however many lanes there are.
9670 #[test]
9671 fn the_composite_is_the_topmost_lane_with_a_clip() {
9672 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9673 let lanes = vec![
9674 // V1: the whole 30 frames of source 0.
9675 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9676 // V2: source 1 over the middle third.
9677 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
9678 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9679 ];
9680 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9681 assert_eq!(
9682 p.composite_spans_from(0),
9683 vec![
9684 Span {
9685 start: 0,
9686 len: 10,
9687 from: Some((0, 0)),
9688 speed: Speed::NORMAL
9689 },
9690 Span {
9691 start: 10,
9692 len: 10,
9693 from: Some((1, 5)),
9694 speed: Speed::NORMAL
9695 },
9696 Span {
9697 start: 20,
9698 len: 10,
9699 from: Some((0, 20)),
9700 speed: Speed::NORMAL
9701 },
9702 ],
9703 "V2 takes over for its own span and hands V1 back"
9704 );
9705 // A mid-span ask resolves the same way, which is what a seek does.
9706 assert_eq!(
9707 p.composite_span_at(15),
9708 Some(Span {
9709 start: 15,
9710 len: 5,
9711 from: Some((1, 10)),
9712 speed: Speed::NORMAL
9713 })
9714 );
9715 assert_eq!(p.composite_span_at(30), None, "past the end");
9716
9717 // A hole in V1 under V2's clip: black between the two, and black after
9718 // both run out (the audio lane is still holding the timeline open).
9719 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9720 let holed = vec![
9721 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
9722 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
9723 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9724 ];
9725 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
9726 assert_eq!(
9727 p.composite_spans_from(0),
9728 vec![
9729 Span {
9730 start: 0,
9731 len: 5,
9732 from: Some((0, 0)),
9733 speed: Speed::NORMAL
9734 },
9735 Span {
9736 start: 5,
9737 len: 5,
9738 from: None,
9739 speed: Speed::NORMAL
9740 },
9741 Span {
9742 start: 10,
9743 len: 10,
9744 from: Some((1, 0)),
9745 speed: Speed::NORMAL
9746 },
9747 Span {
9748 start: 20,
9749 len: 10,
9750 from: None,
9751 speed: Speed::NORMAL
9752 },
9753 ]
9754 );
9755
9756 // One video lane: the composite *is* that lane, span for span -- the
9757 // promise every existing two-lane project rests on.
9758 let p = Project::single(FILE, 30);
9759 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
9760 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
9761 }
9762
9763 /// Every audio lane holding something gets a play list, and only those.
9764 #[test]
9765 fn audio_segments_cover_every_lane_that_holds_something() {
9766 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9767 let lanes = vec![
9768 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9769 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9770 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
9771 (LaneKind::Audio, Vec::new()),
9772 ];
9773 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9774 let lists = p.audio_segments_from(0, FPS);
9775 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
9776 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
9777 // A2 is a gap up to frame 15, then the whole of source 1.
9778 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
9779
9780 // No audio lane holds anything: one all-gap list, so such a timeline
9781 // still plays silence against a master clock.
9782 let p = Project::from_parts(
9783 vec![Source::new(FILE, 0)],
9784 vec![
9785 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9786 (LaneKind::Audio, Vec::new()),
9787 ],
9788 vec![],
9789 vec![],
9790 Vec::new(),
9791 )
9792 .expect("valid parts");
9793 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
9794 }
9795}