forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

project.rs9543 lines, 416.2 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 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
4184 /// out of the lanes in `scope` and close each hole, as one edit: the
4185 /// jumpcut a silence scan asks for ([`crate::silence`]).
4186 ///
4187 /// A lane that is not in `scope` **does not move**, which is the whole
4188 /// point of the parameter: the silences of a podcast track come out
4189 /// without the music track under it sliding. `scope` is an arbitrary set of
4190 /// lanes and not a kind or a range, so a caller with its own idea of what
4191 /// is selected (a take, a track, everything) says it in lanes and nothing
4192 /// here has to learn about selection.
4193 ///
4194 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
4195 /// reason this exists rather than a caller's loop over
4196 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
4197 /// undo press, not forty. Cut back to front, so a region's frames still
4198 /// mean what the caller measured while the ones before it are cut.
4199 ///
4200 /// The list is sorted and overlapping entries are merged before anything is
4201 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
4202 /// other's frames. Refused, with no undo step, for an empty list, for a
4203 /// scope naming no lane that is there, and -- by name -- when the scope
4204 /// would take one half of a take with it
4205 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
4206 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4207 let regions = tidy(regions);
4208 let on = self.scoped(scope)?;
4209 let Some(&(first, _)) = regions.first() else {
4210 return Err("nothing to cut".into());
4211 };
4212 self.scope_holds_takes_whole(&on, first)?;
4213 self.snapshot();
4214 for &(at, len) in regions.iter().rev() {
4215 ripple(&mut self.lanes, &on, at, len);
4216 }
4217 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4218 Ok(())
4219 }
4220
4221 /// The storage indices of `scope`, which is what every batch below walks.
4222 /// `Err` for a scope that names nothing there rather than a silent no-op:
4223 /// an edit asked for on a lane that is not there did not happen, and the
4224 /// caller has to hear so.
4225 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
4226 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
4227 match on.is_empty() {
4228 true => Err("no track to work on".into()),
4229 false => Ok(on),
4230 }
4231 }
4232
4233 /// The law a scoped ripple lives under: **a group travels as one**, so a
4234 /// batch that moves one half of a take and not the other would leave the
4235 /// halves disagreeing about where they stand -- an offset no hand asked
4236 /// for, and the reason the take's lanes have to be scoped together.
4237 ///
4238 /// Refused by name rather than widened silently. Widening would edit a
4239 /// track the user did not scope, which is exactly the surprise scoping
4240 /// exists to end; a front-end that wants the take is free to *say* the
4241 /// take's lanes, and to name them in what it tells the user afterwards.
4242 ///
4243 /// Only from `from` on: a take sitting entirely before the first cut does
4244 /// not move, so it is not this rule's business.
4245 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
4246 let labels = handles(&self.lanes);
4247 // The halves of a group are on either of a lane's lists, and the
4248 // refusal names whichever sits outside the scope -- a clip like it
4249 // always has, and a caption now that a group may hold one.
4250 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
4251 let Some(id) = link else {
4252 return Ok(());
4253 };
4254 for (j, data) in self.lanes.iter().enumerate() {
4255 if on.contains(&j) {
4256 continue;
4257 }
4258 let clip = data.clips.iter().find(|o| o.link == Some(id));
4259 let sub = data.subs.iter().find(|s| s.link == Some(id));
4260 if let Some(half) = clip {
4261 return Err(format!(
4262 "the {what} at frame {start} is one take with the {} clip at frame {}: \
4263 moving one track of a take would pull it apart -- take the whole take, \
4264 or detach them first",
4265 labels[j].label(),
4266 half.start
4267 )
4268 .into());
4269 }
4270 if let Some(half) = sub {
4271 return Err(format!(
4272 "the {what} at frame {start} is one take with the {} caption at frame {}: \
4273 moving one track of a take would pull it apart -- take the whole take, \
4274 or detach them first",
4275 labels[j].label(),
4276 half.start
4277 )
4278 .into());
4279 }
4280 }
4281 Ok(())
4282 };
4283 for &i in on {
4284 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
4285 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
4286 }
4287 // A caption before the first cut does not move, so it is not this
4288 // rule's business -- exactly the clip test's own line.
4289 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
4290 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
4291 }
4292 }
4293 Ok(())
4294 }
4295
4296 /// Play every one of `regions` at `speed` instead of cutting it: each is
4297 /// split out of whatever covers it, re-rated, and the room it no longer
4298 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
4299 /// does not ripple, and a hole where a silence shrank is the one thing this
4300 /// must not leave. One snapshot for the lot, like
4301 /// [`cut_regions`](Project::cut_regions).
4302 ///
4303 /// The rate is **absolute**, not a multiplier on what is there: running it
4304 /// twice over the same stretch leaves it at `speed`, not at `speed`
4305 /// squared, so a second pass over an already-cut timeline changes nothing.
4306 ///
4307 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
4308 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
4309 ///
4310 /// Refused by name, with nothing changed and no undo step, when:
4311 ///
4312 /// * the scope would take one half of a take with it
4313 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
4314 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
4315 /// shrink by different amounts and the ripple would pull them apart,
4316 /// which is what cutting does not suffer and why delete mode has no such
4317 /// refusal;
4318 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
4319 /// piece could not be split out exactly;
4320 /// * two lanes' pieces would end up different lengths, which is a group
4321 /// whose halves disagree about their span (the refusal
4322 /// [`write_speed`](Project::write_speed) already makes, in its words);
4323 /// * the region would grow rather than shrink, i.e. it already plays faster
4324 /// than `speed`.
4325 pub fn speed_regions(
4326 &mut self,
4327 regions: &[(u32, u32)],
4328 speed: Speed,
4329 scope: &[Lane],
4330 ) -> crate::Result<()> {
4331 let regions = tidy(regions);
4332 let on = self.scoped(scope)?;
4333 let Some(&(first, _)) = regions.first() else {
4334 return Err("nothing to speed up".into());
4335 };
4336 self.scope_holds_takes_whole(&on, first)?;
4337 let labels = handles(&self.lanes);
4338 // Before anything is touched, because this is the refusal a person can
4339 // act on: a clip that laps over the edge of a silence has to be trimmed
4340 // (or the silences cut instead), and saying so after a rollback would
4341 // be saying it about a timeline that already looks different.
4342 for &(at, len) in &regions {
4343 for &l in &on {
4344 for c in &self.lanes[l].clips {
4345 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
4346 {
4347 return Err(format!(
4348 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
4349 speeding it up would pull the lanes apart -- trim it first, or cut the \
4350 silences out instead",
4351 labels[l].label(),
4352 c.start,
4353 at + len
4354 )
4355 .into());
4356 }
4357 }
4358 }
4359 }
4360 // The rest is checked as it is built: a split's own arithmetic is what
4361 // says whether a rate can address an edge. So the snapshot is taken
4362 // first and *rolled back* on a refusal -- one undo either way, and a
4363 // refusal still costs no step (`undo` pops the one just pushed).
4364 self.snapshot();
4365 for &(at, len) in regions.iter().rev() {
4366 self.write_split(at, false, &on);
4367 self.write_split(at + len, false, &on);
4368 let mut room: Option<(Lane, u32)> = None;
4369 let mut refused = None;
4370 for &l in &on {
4371 let clips = &self.lanes[l].clips;
4372 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
4373 if (c.start, c.end()) != (at, at + len) {
4374 // *Which* edge did not come off: a rate that cannot
4375 // address the end of the silence is not a rate that
4376 // cannot address its start, and naming the wrong frame
4377 // sends the user looking in the wrong place.
4378 let edge = match c.start == at {
4379 true => at + len,
4380 false => at,
4381 };
4382 refused = Some(format!(
4383 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
4384 detach it, or put it back to 1.00x first",
4385 labels[l].label(),
4386 c.start,
4387 c.speed
4388 ));
4389 continue;
4390 }
4391 let after = speed.frames(c.len());
4392 match room {
4393 None => room = Some((labels[l], after)),
4394 Some((first, n)) if n != after => {
4395 refused = Some(format!(
4396 "at {speed} the {} half of the silence at frame {at} would cover \
4397 {after} frames and the {} half {n}: they are one take and a take \
4398 is one span -- detach them first",
4399 labels[l].label(),
4400 first.label()
4401 ));
4402 }
4403 Some(_) => {}
4404 }
4405 }
4406 }
4407 let shrunk = match (refused, room) {
4408 (Some(e), _) => {
4409 self.undo();
4410 return Err(e.into());
4411 }
4412 // A gap on every lane: nothing to re-rate, and nothing to close.
4413 (None, None) => continue,
4414 (None, Some((_, after))) => after,
4415 };
4416 // The region's new length, on every scoped lane alike.
4417 let after = shrunk;
4418 let Some(delta) = len.checked_sub(shrunk) else {
4419 self.undo();
4420 return Err(format!(
4421 "the silence at frame {at} already plays faster than {speed}: \
4422 at that rate it would be {shrunk} frames instead of {len}"
4423 )
4424 .into());
4425 };
4426 for &l in &on {
4427 for c in &mut self.lanes[l].clips {
4428 if c.start == at && c.end() == at + len {
4429 c.speed = speed;
4430 } else if c.start >= at + len {
4431 c.start -= delta;
4432 }
4433 }
4434 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
4435 // The captions on a scoped lane travel with the region's time:
4436 // a piece inside it plays in `after` frames instead of `len`
4437 // -- same words on less timeline, its window untouched, for
4438 // [`write_speed`]'s reason -- and everything behind the region
4439 // slides up by what the region gave back.
4440 //
4441 // The pieces inside re-time by their *boundaries*, not each
4442 // on its own: rounding one piece's start and its neighbour's
4443 // start apart can land both on the same frame (two one-frame
4444 // cues of a thirty-frame region at 2x both want frame 15), so
4445 // the mapped boundaries are walked in order and forced apart
4446 // -- each piece at least one frame, none past the region's own
4447 // new end, where the first follower lands exactly. A rounding
4448 // artifact is clamped, not refused: nothing about the words
4449 // asked for an overlap.
4450 let share = f64::from(after) / f64::from(len).max(1.);
4451 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
4452 let mut prev = at;
4453 let subs = &mut self.lanes[l].subs;
4454 for i in 0..subs.len() {
4455 let s = subs[i];
4456 if s.start >= at + len {
4457 subs[i].start = s.start - delta;
4458 } else if s.start >= at && s.end() <= at + len {
4459 let mut start = map(s.start).max(prev);
4460 let end = map(s.end()).max(start + 1).min(at + after);
4461 start = start.min(end - 1);
4462 subs[i].start = start;
4463 subs[i].frames = end - start;
4464 prev = end;
4465 }
4466 }
4467 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
4468 }
4469 }
4470 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4471 Ok(())
4472 }
4473
4474 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
4475 /// -- the whole-group delete a single-lane front-end means. `false` for a
4476 /// bad index. Changes the mapping: the caller must reseek.
4477 pub fn delete(&mut self, idx: usize) -> bool {
4478 self.delete_in(Lane::V1, idx)
4479 }
4480
4481 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
4482 /// in no group (or a group of one, which is the same thing to a delete) is
4483 /// what it always was: its own span cut out of *every* lane, so the
4484 /// timeline closes up under it. A clip in a group takes the group with it,
4485 /// each member by its **own** span and on its **own** lane -- the members
4486 /// keep their offsets, so their spans may disagree, and the lanes may end
4487 /// up out of step with each other, which is inherent to a hand-built group
4488 /// and one undo away. Every member -- clips and captions alike -- goes by
4489 /// the same law: its own span out of its own lane, hole closed; a caption
4490 /// in no group keeps the lift that leaves a gap, which is its own door's
4491 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
4492 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
4493 /// index, and for a lane that is not there. Changes the mapping: the
4494 /// caller must reseek.
4495 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
4496 let Some(members) = self.group_of(lane, idx) else {
4497 return false;
4498 };
4499 if !members.alone() {
4500 return self.delete_members(&members);
4501 }
4502 let Some(clip) = self.lane(lane).get(idx).copied() else {
4503 return false;
4504 };
4505 self.ripple_delete(clip.start, clip.frames())
4506 }
4507
4508 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
4509 /// caption in no group lifts, exactly as its own key always made it
4510 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
4511 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
4512 /// span out of its own lane, hole closed, captions and clips alike.
4513 /// `false` for a bad index.
4514 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
4515 let Some(members) = self.group_of(lane, idx) else {
4516 return false;
4517 };
4518 if !members.alone() {
4519 return self.delete_members(&members);
4520 }
4521 self.lift_sub(lane, idx)
4522 }
4523
4524 /// The one whole-group delete both doors land in: every member's own span
4525 /// cut out of its own lane and the hole closed there -- clips and
4526 /// captions by the same law -- and nothing else on another lane moves,
4527 /// which is what keeps one member's ripple from dragging another
4528 /// member's lane out from under it. One snapshot, one undo step.
4529 fn delete_members(&mut self, members: &Members) -> bool {
4530 self.snapshot();
4531 for &(l, i) in &members.clips {
4532 let c = self.lanes[l].clips[i];
4533 ripple(&mut self.lanes, &[l], c.start, c.frames());
4534 }
4535 // The captions go by the same law their clip siblings do -- the span
4536 // out of its own lane, the hole closed -- and not by the lift a
4537 // *lone* caption's delete is: deleted with its group, the words after
4538 // it slide up with everything else, or the lane the group emptied is
4539 // the one lane the delete left a hole in. `ripple` is the one
4540 // mechanism (it clears the span and shifts the rest, clips and
4541 // captions alike); a sub lane holds no clips, so its other list is
4542 // untouched.
4543 for &(l, i) in &members.subs {
4544 let s = self.lanes[l].subs[i];
4545 ripple(&mut self.lanes, &[l], s.start, s.frames);
4546 }
4547 debug_assert!(links_are_consistent(&self.lanes).is_ok());
4548 true
4549 }
4550
4551 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
4552 #[cfg(test)]
4553 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
4554 self.lane(lane)
4555 }
4556
4557 /// How many undo steps are stacked: what the sweep asks so "one op, one
4558 /// snapshot" is a count and not a guess.
4559 #[cfg(test)]
4560 pub(crate) fn history_len(&self) -> usize {
4561 self.history.len()
4562 }
4563
4564 /// How many redo steps are stacked: what the sweep asks to check `undo`
4565 /// left a branch behind, and that a fresh edit clears it.
4566 #[cfg(test)]
4567 pub(crate) fn redo_len(&self) -> usize {
4568 self.redo.len()
4569 }
4570
4571 /// Every part of the project that an edit can change, as comparable
4572 /// values: what the sweep's undo round-trip asks "byte identical?" of.
4573 #[cfg(test)]
4574 pub(crate) fn parts(&self) -> SweepParts {
4575 SweepParts(
4576 self.sources.len(),
4577 self.lanes.iter().map(|l| (l.kind, l.clips.clone())).collect(),
4578 self.lanes.iter().map(|l| l.subs.clone()).collect(),
4579 )
4580 }
4581
4582 /// Restore every lane from before the last successful edit -- the clips and
4583 /// the lane list both. `false` when there is nothing left to undo. Pushes
4584 /// the lanes just left onto the redo stack, so [`Project::redo`] can walk
4585 /// forward again.
4586 pub fn undo(&mut self) -> bool {
4587 match self.history.pop() {
4588 Some(prev) => {
4589 self.redo.push(std::mem::replace(&mut self.lanes, prev));
4590 true
4591 }
4592 None => false,
4593 }
4594 }
4595
4596 /// Restore every lane from before the last [`Project::undo`] -- the
4597 /// mirror of `undo`, walking the redo stack it fills. `false` when there
4598 /// is nothing left to redo, which is also true after any fresh edit: a
4599 /// new [`Project::snapshot`] clears the branch `undo` left behind.
4600 pub fn redo(&mut self) -> bool {
4601 match self.redo.pop() {
4602 Some(next) => {
4603 self.history.push(std::mem::replace(&mut self.lanes, next));
4604 true
4605 }
4606 None => false,
4607 }
4608 }
4609
4610 /// The project an export renders from: everything a render reads, with the
4611 /// undo history left behind. An export never walks the history back, and
4612 /// cloning it costs a copy of every lane list in the session -- this is
4613 /// taken on the UI thread, so it clones the lanes and the sources alone.
4614 pub fn export_snapshot(&self) -> Self {
4615 Self {
4616 sources: self.sources.clone(),
4617 lanes: self.lanes.clone(),
4618 eq: self.eq.clone(),
4619 color: self.color.clone(),
4620 transform: self.transform.clone(),
4621 history: Vec::new(),
4622 redo: Vec::new(),
4623 next_link: self.next_link,
4624 subtitles: self.subtitles.clone(),
4625 limiter: self.limiter,
4626 tone: self.tone,
4627 }
4628 }
4629
4630 /// Half-open `(source, start, end)` segments in *source* seconds, from
4631 /// `timeline_frame` to the end of the timeline -- the play list for the
4632 /// audio worker, read off **`A1`**. A `None` source is a gap: the
4633 /// worker synthesises that many seconds of silence, which is what keeps the
4634 /// audio master clock counting across a hole instead of stalling on it.
4635 /// The first entry is partial when the position is mid-clip. Empty when the
4636 /// position is past the end or `fps` is not usable.
4637 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
4638 self.lane_segments_from(Lane::A1, timeline_frame, fps)
4639 }
4640
4641 /// [`segments_from`](Project::segments_from) for a named lane.
4642 pub fn lane_segments_from(
4643 &self,
4644 lane: Lane,
4645 timeline_frame: u32,
4646 fps: f64,
4647 ) -> Vec<(Option<usize>, f64, f64)> {
4648 if !(fps.is_finite() && fps > 0.0) {
4649 return Vec::new();
4650 }
4651 self.spans_from(lane, timeline_frame)
4652 .iter()
4653 .map(|span| match span.from {
4654 // A clip's window is in *source* seconds: where in the file it
4655 // reads from, which a delete before it never shifts. How many
4656 // source frames that is, is the span's own arithmetic -- at a
4657 // speed it is not the timeline length ([`Span::source_len`]).
4658 Some((source, in_frame)) => (
4659 Some(source),
4660 f64::from(in_frame) / fps,
4661 f64::from(in_frame + span.source_len()) / fps,
4662 ),
4663 // A gap has no file, so all it can say is how long it is.
4664 None => (None, 0.0, f64::from(span.len) / fps),
4665 })
4666 .collect()
4667 }
4668
4669 /// One play list per audio lane that *holds* something, in display order --
4670 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
4671 /// what an export asks how many lanes it would have to mix.
4672 ///
4673 /// Never empty: a timeline whose audio lanes are all empty (or which has no
4674 /// audio lane at all) still yields one all-gap list, so it plays silence
4675 /// against a master clock exactly as it did before there were lanes to
4676 /// count. Lanes with nothing on them are left out rather than mixed in as
4677 /// silence: they would cost a decode thread each and add zero.
4678 pub fn audio_segments_from(
4679 &self,
4680 timeline_frame: u32,
4681 fps: f64,
4682 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
4683 self.audio_lanes()
4684 .into_iter()
4685 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
4686 .collect()
4687 }
4688
4689 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
4690 /// builds a play list for, in the same order. Public because everything
4691 /// asked per audio lane -- which clip a segment's equalizer belongs to,
4692 /// which lane an mp4 export would copy -- has to read the very list the
4693 /// sound comes off, or the two answers drift apart (which is exactly how an
4694 /// `A2`-only project once exported silently, ledger).
4695 pub fn audio_lanes(&self) -> Vec<Lane> {
4696 let lanes: Vec<Lane> = self
4697 .lanes()
4698 .into_iter()
4699 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
4700 .collect();
4701 match lanes.is_empty() {
4702 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
4703 // no sound still plays silence against the master clock.
4704 true => vec![Lane::A1],
4705 false => lanes,
4706 }
4707 }
4708
4709 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
4710 /// segments plays at, and how long the timeline gives it: the same lanes in
4711 /// the same order, one entry per segment, `None` for a segment at real time
4712 /// -- which is every segment of a project nobody has speeded, and the path
4713 /// the audio worker leaves bit-identical.
4714 ///
4715 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
4716 /// the segment tuple is what every opener and a dozen tests speak, and a
4717 /// rate is not part of *which samples* a segment names.
4718 ///
4719 /// The seconds are what makes a resample exact: a segment's own window
4720 /// resolves to whole source frames, and dividing that by the rate would
4721 /// leave each clip a fraction of a frame short or long -- a drift that grows
4722 /// clip by clip. Told how much timeline it owes, the worker pads or trims
4723 /// the last few samples of each segment instead, so the sound stays locked
4724 /// to the picture however many speeded cuts it walks through.
4725 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
4726 self.audio_lanes()
4727 .into_iter()
4728 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
4729 .collect()
4730 }
4731
4732 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
4733 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4734 /// same walk, same `fps` refusal.
4735 pub fn lane_speeds_from(
4736 &self,
4737 lane: Lane,
4738 timeline_frame: u32,
4739 fps: f64,
4740 ) -> Vec<Option<Stretch>> {
4741 if !(fps.is_finite() && fps > 0.0) {
4742 return Vec::new();
4743 }
4744 self.spans_from(lane, timeline_frame)
4745 .iter()
4746 .map(|span| {
4747 (!span.speed.is_normal()).then(|| Stretch {
4748 step: span.speed.as_f64(),
4749 timeline_secs: f64::from(span.len) / fps,
4750 })
4751 })
4752 .collect()
4753 }
4754
4755 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
4756 /// segments plays through: the same lanes in the same order, one entry per
4757 /// segment, `None` where the segment is a gap or its clip plays flat.
4758 ///
4759 /// A parallel list rather than a fourth element of the segment tuple: that
4760 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
4761 /// and an effect is not part of *which samples* a segment names. A short
4762 /// list therefore means "flat from here on" rather than a length mismatch --
4763 /// see [`crate::AudioSession::open_mixed_streams_eq`].
4764 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
4765 self.audio_lanes()
4766 .into_iter()
4767 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
4768 .collect()
4769 }
4770
4771 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
4772 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
4773 /// same walk, same `fps` refusal, so the two lists cannot come out different
4774 /// lengths.
4775 pub fn lane_eqs_from(
4776 &self,
4777 lane: Lane,
4778 timeline_frame: u32,
4779 fps: f64,
4780 ) -> Vec<Option<EqParams>> {
4781 if !(fps.is_finite() && fps > 0.0) {
4782 return Vec::new();
4783 }
4784 self.spans_from(lane, timeline_frame)
4785 .iter()
4786 // A span off a clip covers that clip's frames and no others, so its
4787 // own start names the clip -- the index a [`Span`] does not carry.
4788 .map(|span| {
4789 self.map(lane, span.start)
4790 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
4791 })
4792 .collect()
4793 }
4794
4795 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
4796 /// segments plays through: the same lanes in the same order, one entry per
4797 /// segment, `None` where the segment is a gap or its clip has neither a
4798 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
4799 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
4800 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
4801 self.audio_lanes()
4802 .into_iter()
4803 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
4804 .collect()
4805 }
4806
4807 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
4808 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
4809 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
4810 if !(fps.is_finite() && fps > 0.0) {
4811 return Vec::new();
4812 }
4813 self.spans_from(lane, timeline_frame)
4814 .iter()
4815 .map(|span| {
4816 let (idx, _) = self.map(lane, span.start)?;
4817 let clip = self.lane(lane).get(idx)?;
4818 (clip.fade_in > 0 || clip.fade_out > 0).then(|| Fade {
4819 // `span.len` is the clip's own remaining frames from
4820 // `span.start` on -- shorter than `clip.frames()` only
4821 // when this is the first span of a seek mid-clip.
4822 elapsed: clip.frames().saturating_sub(span.len),
4823 fade_in: clip.fade_in,
4824 fade_out: clip.fade_out,
4825 total: clip.frames(),
4826 })
4827 })
4828 .collect()
4829 }
4830
4831 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
4832 /// it has decided it will succeed -- a refusal must not cost an undo step.
4833 /// Clears the redo stack: a fresh edit branches off from here, so whatever
4834 /// `undo` had left to redo is no longer where this edit leads back to.
4835 fn snapshot(&mut self) {
4836 if self.history.len() == HISTORY_CAP {
4837 self.history.remove(0);
4838 }
4839 self.history.push(self.lanes.clone());
4840 self.redo.clear();
4841 }
4842
4843 fn new_link(&mut self) -> u32 {
4844 let id = self.next_link;
4845 self.next_link = self.next_link.saturating_add(1);
4846 id
4847 }
4848
4849}
4850
4851/// The handle of every lane, in storage order -- the one definition of what
4852/// [`Lane::ord`] counts.
4853fn handles(lanes: &[LaneData]) -> Vec<Lane> {
4854 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
4855 lanes
4856 .iter()
4857 .map(|l| match l.kind {
4858 LaneKind::Video => {
4859 video += 1;
4860 Lane::new(LaneKind::Video, video - 1)
4861 }
4862 LaneKind::Audio => {
4863 audio += 1;
4864 Lane::new(LaneKind::Audio, audio - 1)
4865 }
4866 LaneKind::Subtitle => {
4867 subtitle += 1;
4868 Lane::new(LaneKind::Subtitle, subtitle - 1)
4869 }
4870 })
4871 .collect()
4872}
4873
4874/// The one law a caption re-time scales by: frame `f` moves about the held
4875/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
4876/// commits it, [`Project::speeded_playhead`] previews it -- both build their
4877/// [`TimelineMap`] piece from this single answer so the two cannot drift
4878/// apart by a frame the way they once did.
4879fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
4880 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
4881 .round()
4882 .clamp(0., f64::from(u32::MAX)) as u32
4883}
4884
4885/// Which source frame a clip plays at `timeline_frame`: its in-point plus the
4886/// offset *at the clip's own rate*. The one place the two frame spaces meet, so
4887/// a speed cannot be applied twice or forgotten in one of them.
4888fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
4889 // Clamped inside the clip's own range: rounding at a slow rate can put the
4890 // last timeline frame of a clip a frame past its out-point, and a source
4891 // frame outside the range is one the next clip owns.
4892 (c.in_frame + c.speed.source_at(timeline_frame - c.start)).min(c.out_frame - 1)
4893}
4894
4895/// Index of the clip covering `frame`, or `None` for a gap or past the end.
4896/// Binary search: the sorted-disjoint invariant is what makes it legal.
4897fn at(clips: &[Clip], frame: u32) -> Option<usize> {
4898 let idx = clips.partition_point(|c| c.start <= frame).checked_sub(1)?;
4899 (frame < clips[idx].end()).then_some(idx)
4900}
4901
4902/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
4903/// there would cut in two. A placement's own first frame is not inside it.
4904fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
4905 let idx = at(clips, frame)?;
4906 // ...and, on a speeded clip, one its rate can actually address
4907 // ([`Speed::split_at`]): a cut between two showings of one source frame
4908 // would leave halves that no longer add up to the clip that was cut.
4909 (frame > clips[idx].start)
4910 .then_some(idx)
4911 .filter(|&idx| split_source(&clips[idx], frame).is_some())
4912}
4913
4914/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
4915/// rate cannot address that frame.
4916fn split_source(c: &Clip, frame: u32) -> Option<u32> {
4917 c.speed
4918 .split_at(c.len(), frame - c.start)
4919 .map(|src| c.in_frame + src)
4920}
4921
4922/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
4923/// rejoin: they must touch there, and be consecutive frames of one source.
4924fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
4925 let idx = clips.iter().position(|c| c.end() == frame)?;
4926 let next = clips.get(idx + 1)?;
4927 let joined = clips[idx].len() + next.len();
4928 (next.start == frame
4929 && next.source == clips[idx].source
4930 && next.in_frame == clips[idx].out_frame
4931 // ...at one rate, and one that puts the rejoined clip back in exactly
4932 // the room the two took up: what a split could have produced, which is
4933 // all this undoes.
4934 && next.speed == clips[idx].speed
4935 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
4936 .then_some(idx)
4937}
4938
4939/// The lane invariant: sorted by `start`, no two placements overlapping, no
4940/// empty placement. Checked at every constructor and asserted after every
4941/// mutation -- the offset model is only tractable while it holds.
4942/// The one thing an equalizer setting may not be: a value the text format
4943/// cannot write and read back as itself. Checked wherever params come in, so
4944/// what an edit produces is always what a save writes and a load reads.
4945fn finite(params: &EqParams) -> bool {
4946 params
4947 .bands
4948 .iter()
4949 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
4950}
4951
4952/// The same for a colour grade: [`crate::color`] itself falls back to identity
4953/// on a non-finite value, but a value that cannot be written and read back as
4954/// itself has no business reaching the model.
4955fn color_finite(p: &ColorParams) -> bool {
4956 p.brightness.is_finite()
4957 && p.contrast.is_finite()
4958 && p.saturation.is_finite()
4959 && p.tint.is_finite()
4960}
4961
4962/// The same for a transform: [`crate::scale`] clamps a non-finite value to
4963/// identity at read time, but a value that cannot round-trip has no business
4964/// reaching the model.
4965fn transform_finite(p: &TransformParams) -> bool {
4966 p.pos_x.is_finite()
4967 && p.pos_y.is_finite()
4968 && p.scale.is_finite()
4969 && p.rotate.is_finite()
4970 && p.crop_l.is_finite()
4971 && p.crop_r.is_finite()
4972 && p.crop_t.is_finite()
4973 && p.crop_b.is_finite()
4974}
4975
4976fn sorted_disjoint(clips: &[Clip]) -> bool {
4977 clips.iter().all(|c| c.out_frame > c.in_frame)
4978 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
4979}
4980
4981/// The very same invariant on a subtitle lane, in that lane's own two units:
4982/// sorted by `start`, no two placements overlapping, no empty placement at
4983/// either end. Asserted after every mutation, exactly as its twin is.
4984fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
4985 subs.iter()
4986 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
4987 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
4988}
4989
4990/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
4991/// the one conversion between a lane's clock and a cue's, and `0` for a rate
4992/// that is not one (every caller of this has already refused such a rate).
4993fn us_of(frames: i64, fps: f64) -> i64 {
4994 match fps.is_finite() && fps > 0.0 {
4995 true => ((frames as f64) / fps * 1e6).round() as i64,
4996 false => 0,
4997 }
4998}
4999
5000/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
5001/// dropping what is inside the hole, splitting what straddles it and trimming
5002/// what overlaps an edge. The windows follow the cut by proportion
5003/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
5004fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
5005 let mut out = Vec::with_capacity(subs.len() + 1);
5006 for s in subs.drain(..) {
5007 if s.end() <= start || s.start >= end {
5008 out.push(s);
5009 continue;
5010 }
5011 if s.start < start {
5012 out.push(SubClip {
5013 frames: start - s.start,
5014 out_us: s.window_at(start),
5015 // Both pieces lose the group id, for [`clear`]'s reason: one
5016 // id on two boxes of one lane is the one thing it may never
5017 // mean.
5018 link: None,
5019 ..s
5020 });
5021 }
5022 if s.end() > end {
5023 out.push(SubClip {
5024 start: end,
5025 frames: s.end() - end,
5026 in_us: s.window_at(end),
5027 link: None,
5028 ..s
5029 });
5030 }
5031 }
5032 *subs = out;
5033}
5034
5035/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
5036/// `len`, splitting a placement that straddles `at` so the two halves end up on
5037/// either side of the hole. A `len` of 0 is that split alone, which is what a
5038/// [`Project::split`] over a subtitle lane is.
5039fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
5040 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
5041 let s = subs[idx];
5042 let cut = s.window_at(at);
5043 subs[idx] = SubClip {
5044 frames: at - s.start,
5045 out_us: cut,
5046 link: None,
5047 ..s
5048 };
5049 subs.insert(
5050 idx + 1,
5051 SubClip {
5052 start: at,
5053 frames: s.end() - at,
5054 in_us: cut,
5055 link: None,
5056 ..s
5057 },
5058 );
5059 }
5060 for s in subs.iter_mut().filter(|s| s.start >= at) {
5061 s.start += len;
5062 }
5063}
5064
5065/// [`joinable`] for a subtitle lane: the first of the two placements a
5066/// [`Project::regroup`] at `frame` would rejoin. What a split could have
5067/// produced and nothing else -- they touch on the timeline, they read the same
5068/// track, and the second one's window carries on where the first's stopped.
5069fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
5070 let idx = subs.iter().position(|s| s.end() == frame)?;
5071 let next = subs.get(idx + 1)?;
5072 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
5073 .then_some(idx)
5074}
5075
5076/// How far one `edge` of the caption at `idx` may travel against its own lane's
5077/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
5078/// rate, which a caption *following* a group's trim does not have to be exact
5079/// about -- its own walls, its own one surviving frame, and nothing that needs
5080/// a clock.
5081fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
5082 let s = &subs[idx];
5083 match edge {
5084 Edge::Start => (
5085 idx.checked_sub(1).map_or(0, |p| subs[p].end()),
5086 s.end() - 1,
5087 ),
5088 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5089 }
5090}
5091
5092/// Move one `edge` of `s` to timeline frame `to`, its window following by the
5093/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
5094/// forwards and backwards. The caption a group's trim is carrying has no rate
5095/// of its own and needs none: what one frame of it is worth in microseconds is
5096/// the window it already shows over the frames it already takes.
5097fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
5098 let per_frame = s.window_us() / i64::from(s.frames.max(1));
5099 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
5100 match edge {
5101 Edge::Start => {
5102 s.in_us = (s.in_us + by(s.start, to)).clamp(0, s.out_us - 1);
5103 s.frames = s.end() - to;
5104 s.start = to;
5105 }
5106 Edge::End => {
5107 s.out_us = (s.out_us + by(s.end(), to)).max(s.in_us + 1);
5108 s.frames = to - s.start;
5109 }
5110 }
5111 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5112}
5113
5114/// The grouping invariant, checked in release at [`Project::from_parts`] and
5115/// asserted by the tests after every edit: a link id names **at most one**
5116/// placement per lane -- a clip on a media lane or a caption on a subtitle
5117/// one, whichever carries it. That is all "these move together" can mean now
5118/// that a group is assembled by hand: the members keep their own spans and
5119/// their own offsets, and what binds them is the id alone.
5120///
5121/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
5122/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
5123/// placements of one group may cover different frames -- the offset-preserving
5124/// group a hand builds with [`Project::group_all`], which a drag moves by one
5125/// delta rather than by one span.
5126///
5127/// A link no other lane carries is legal and is not an error: lifting one half
5128/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
5129/// timeline has to load again.
5130/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
5131/// asked by the sweep suite's universal law.
5132#[cfg(test)]
5133pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
5134 links_are_consistent(&p.lanes)
5135}
5136
5137fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
5138 let handles = handles(lanes);
5139 for (data, lane) in lanes.iter().zip(&handles) {
5140 for (i, c) in data.clips.iter().enumerate() {
5141 let Some(id) = c.link else { continue };
5142 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
5143 return Err(
5144 format!("link {id} names two clips in the {} lane", lane.label()).into(),
5145 );
5146 }
5147 }
5148 // ...and the same for the captions, in their own list on the same lane:
5149 // a subtitle lane holds no `Clip`, so this is the only list a caption's
5150 // id could be doubled on.
5151 for (i, s) in data.subs.iter().enumerate() {
5152 let Some(id) = s.link else { continue };
5153 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
5154 return Err(format!(
5155 "link {id} names two captions in the {} lane",
5156 lane.label()
5157 )
5158 .into());
5159 }
5160 }
5161 }
5162 Ok(())
5163}
5164
5165/// Removes the timeline frames `[start, end)` from `clips`: placements inside
5166/// it go, one straddling it is split in two, one overlapping an edge is
5167/// trimmed. Source frames follow the trim, so what is left plays what it always
5168/// played. Leaves the lane sorted and disjoint.
5169///
5170/// A piece the hole cut is no longer the take its group id names -- and both
5171/// halves of a straddled placement carrying that id would be the same id twice
5172/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
5173fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
5174 let mut out = Vec::with_capacity(clips.len() + 1);
5175 for c in clips.drain(..) {
5176 // Disjoint from the hole: untouched.
5177 if c.end() <= start || c.start >= end {
5178 out.push(c);
5179 continue;
5180 }
5181 // The head that survives in front of the hole -- as much source as fits
5182 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
5183 // which at real time is that room itself. Never *more*: a head that
5184 // outgrew its room would reach into the hole it is being cut out of,
5185 // which is exactly the overlap a slow clip punched at a frame its rate
5186 // cannot address used to leave (at 0.25x a single source frame is four
5187 // timeline frames, and three frames of room hold none of it). `None`
5188 // there means no remainder at all, and the piece simply goes.
5189 if let Some(keep) = c.speed.fit(start.saturating_sub(c.start))
5190 && c.start < start
5191 {
5192 out.push(Clip {
5193 fade_in: 0,
5194 fade_out: 0,
5195 transition_out: 0,
5196 out_frame: c.in_frame + keep.min(c.len()),
5197 link: None,
5198 ..c
5199 });
5200 }
5201 // ...and the tail behind it, which keeps reading up to where it would
5202 // have: measured from its out-point for the head's reason, so what it
5203 // occupies still ends where the whole clip did -- and dropped whole on
5204 // the same `None`.
5205 if let Some(keep) = c.speed.fit(c.end().saturating_sub(end))
5206 && c.end() > end
5207 {
5208 out.push(Clip {
5209 fade_in: 0,
5210 fade_out: 0,
5211 transition_out: 0,
5212 start: end,
5213 in_frame: c.out_frame - keep.min(c.len()),
5214 link: None,
5215 ..c
5216 });
5217 }
5218 }
5219 *clips = out;
5220}
5221
5222/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
5223/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
5224/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
5225/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
5226/// the caller.
5227fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
5228 for &i in on {
5229 let clips = &mut lanes[i].clips;
5230 clear(clips, at, at + len);
5231 for c in clips.iter_mut().filter(|c| c.start >= at) {
5232 c.start -= len;
5233 }
5234 debug_assert!(sorted_disjoint(clips));
5235 // The subtitle lanes close the hole with everything else: a caption
5236 // left standing where the picture it belongs to was cut out is the
5237 // desync a lane model exists to make impossible.
5238 let subs = &mut lanes[i].subs;
5239 sub_clear(subs, at, at + len);
5240 for s in subs.iter_mut().filter(|s| s.start >= at) {
5241 s.start -= len;
5242 }
5243 debug_assert!(subs_sorted_disjoint(subs));
5244 }
5245}
5246
5247/// Every lane, as the index list the two above take: what "the whole timeline"
5248/// is spelled as, and the scope [`Project::ripple_delete`] and
5249/// [`Project::split`] have always had.
5250fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
5251 (0..lanes.len()).collect()
5252}
5253
5254/// A caller's region list as a batch may use it: sorted by start, empty entries
5255/// dropped, and touching or overlapping entries merged into one.
5256///
5257/// Overlapping regions are the one thing a batch cannot take -- cutting the
5258/// second would cut frames the first already moved -- and a detector handing
5259/// back two that touch means one silence, not two cuts. Merged rather than
5260/// refused: this is arithmetic on a preview, not a user's mistake.
5261fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
5262 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
5263 sorted.sort_by_key(|&(at, _)| at);
5264 let mut out: Vec<(u32, u32)> = Vec::new();
5265 for (at, len) in sorted {
5266 let end = at.saturating_add(len);
5267 match out.last_mut() {
5268 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
5269 _ => out.push((at, len)),
5270 }
5271 }
5272 out
5273}
5274
5275/// Slides everything from `at` on later by `len`, splitting a placement that
5276/// straddles `at` so the two halves end up on either side of the hole. The
5277/// insert half of a rippling paste. The two halves lose the group id for the
5278/// reason [`clear`] gives.
5279fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
5280 if let Some(idx) = splittable(clips, at) {
5281 let mut tail = clips[idx];
5282 // The cut in *source* frames, at the clip's own rate. `splittable` has
5283 // already refused a frame the rate cannot address, which is why
5284 // [`Project::paste`] refuses one too rather than opening room inside a
5285 // clip that cannot be cut there.
5286 tail.in_frame = split_source(&tail, at).expect("splittable said so");
5287 tail.start = at;
5288 tail.link = None;
5289 clips[idx].out_frame = tail.in_frame;
5290 clips[idx].link = None;
5291 clips.insert(idx + 1, tail);
5292 }
5293 for c in clips.iter_mut().filter(|c| c.start >= at) {
5294 c.start += len;
5295 }
5296}
5297
5298/// Absolute, symlink-resolved when the file is reachable; the path as given
5299/// when it is not -- an unreadable path still deserves an index, it simply
5300/// dedups by spelling.
5301pub(crate) fn canonical(path: &Path) -> PathBuf {
5302 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
5303}
5304
5305#[cfg(test)]
5306mod tests {
5307 use super::*;
5308
5309 const FPS: f64 = 30.0;
5310 /// Never opened -- `Project` is pure data, so a path that does not exist is
5311 /// simply a path that dedups by spelling.
5312 const FILE: &str = "/nonexistent/a.mp4";
5313 const FILE2: &str = "/nonexistent/b.mp4";
5314
5315 /// A contiguous placement, group id ignored: what most assertions compare.
5316 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
5317 Clip {
5318 fade_in: 0,
5319 fade_out: 0,
5320 transition_out: 0,
5321 start,
5322 in_frame,
5323 out_frame,
5324 source,
5325 link: None,
5326 eq: None,
5327 color: None,
5328 transform: None,
5329 fit: FitPolicy::default(),
5330 speed: Speed::NORMAL,
5331 }
5332 }
5333
5334 /// A recognisable equalizer setting: one peak band, `n` telling two of them
5335 /// apart -- which is what makes the table's dedup and its prune visible.
5336 fn band_at(n: u32) -> EqParams {
5337 EqParams {
5338 bands: vec![crate::eq::Band {
5339 freq_hz: 1000.0,
5340 gain_db: f64::from(n) as f32 * 1.5,
5341 q: 0.707,
5342 kind: crate::eq::BandKind::Peak,
5343 }],
5344 }
5345 }
5346
5347 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
5348 /// for the colour table.
5349 fn grade_at(n: u32) -> ColorParams {
5350 ColorParams {
5351 brightness: f64::from(n) as f32 * 0.05,
5352 ..Default::default()
5353 }
5354 }
5355
5356 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
5357 /// twin for the transform table.
5358 fn transform_at(n: u32) -> TransformParams {
5359 TransformParams {
5360 pos_x: f64::from(n) as f32 * 0.05,
5361 ..Default::default()
5362 }
5363 }
5364
5365 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
5366 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
5367 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5368 }
5369
5370 /// Every lane with its group ids blanked, for comparing shape.
5371 fn shape(p: &Project) -> Vec<Vec<Clip>> {
5372 p.lanes()
5373 .into_iter()
5374 .map(|l| {
5375 p.lane(l)
5376 .iter()
5377 .map(|c| Clip { link: None, ..*c })
5378 .collect()
5379 })
5380 .collect()
5381 }
5382
5383 /// The *source frame* every timeline frame reads, per lane -- the traversal
5384 /// a player performs. Deliberately not the clip index: a split changes which
5385 /// clip a frame belongs to, and nothing else.
5386 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
5387 (0..p.timeline_frames() + 2)
5388 .map(|f| {
5389 p.lanes()
5390 .into_iter()
5391 .map(|l| p.map(l, f).map(|(_, source)| source))
5392 .collect()
5393 })
5394 .collect()
5395 }
5396
5397 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
5398 /// fixture. Built through `split` so the constructor path is exercised too.
5399 fn three() -> Project {
5400 let mut p = Project::single(FILE, 9);
5401 assert!(p.split(3));
5402 assert!(p.split(5));
5403 assert_eq!(
5404 shape(&p),
5405 [
5406 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5407 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
5408 ]
5409 );
5410 p
5411 }
5412
5413 #[test]
5414 fn single_is_the_whole_file_on_both_lanes() {
5415 let p = Project::single(FILE, 150);
5416 assert_eq!(p.clips().len(), 1);
5417 assert_eq!(p.lane(Lane::A1).len(), 1);
5418 assert_eq!(p.timeline_frames(), 150);
5419 assert_eq!(p.clip_spans(), vec![(0, 150)]);
5420 // grouped: video and audio carry the same link
5421 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
5422 assert!(p.clips()[0].link.is_some());
5423 // degenerate mapping: timeline == source
5424 assert_eq!(p.map_timeline(0), Some((0, 0)));
5425 assert_eq!(p.map_timeline(149), Some((0, 149)));
5426 assert_eq!(p.map_timeline(150), None);
5427 // never-empty invariant survives a bogus frame count
5428 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
5429 }
5430
5431 #[test]
5432 fn split_cuts_every_lane_and_regroups_it_back() {
5433 let mut p = Project::single(FILE, 9);
5434 let before = traversal(&p);
5435 let before_shape = shape(&p);
5436
5437 assert!(p.split(4));
5438 for l in p.lanes() {
5439 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
5440 }
5441 // The two sides are two groups, one per side, matching across the lanes.
5442 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
5443 assert_eq!(v[0].link, a[0].link);
5444 assert_eq!(v[1].link, a[1].link);
5445 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
5446 // A split changes no mapping, in either lane.
5447 assert_eq!(traversal(&p), before, "a split moves nothing");
5448
5449 assert!(p.regroup(4), "the inverse rejoins them");
5450 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
5451 assert_eq!(traversal(&p), before);
5452 assert_eq!(
5453 p.lane(Lane::V1)[0].link,
5454 p.lane(Lane::A1)[0].link,
5455 "and the rejoined clip is one group again"
5456 );
5457 }
5458
5459 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
5460 /// the very first frame of a fade-in, unity at its last, equal-power
5461 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
5462 /// at all.
5463 #[test]
5464 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
5465 let f = Fade {
5466 elapsed: 0,
5467 fade_in: 10,
5468 fade_out: 10,
5469 total: 40,
5470 };
5471 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
5472 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
5473 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
5474 assert!(
5475 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
5476 "equal-power midpoint is sin(pi/4)"
5477 );
5478 assert_eq!(f.gain_at(20), 1.0, "unchanged in the body, past either ramp");
5479 // The fade-out is the same curve, mirrored, counting down from the
5480 // clip's end: unity at the frame the ramp starts, the same
5481 // equal-power midpoint, and -- since `total` itself is one past the
5482 // clip's last valid frame -- the very last frame is one step short of
5483 // the silence a fade-in's own frame `0` lands on exactly.
5484 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
5485 assert!(
5486 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
5487 "the fade-out's own equal-power midpoint"
5488 );
5489 assert!(
5490 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
5491 "one step short of silence at the clip's last playable frame"
5492 );
5493 }
5494
5495 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
5496 /// not adjacent, and otherwise sets the shared edge's fades and nothing
5497 /// else.
5498 #[test]
5499 fn crossfade_only_joins_adjacent_audio_clips() {
5500 let mut p = Project::single(FILE, 20);
5501 assert!(p.split(10));
5502 assert!(
5503 !p.crossfade(Lane::V1, 0, 5),
5504 "video is not an audio lane"
5505 );
5506 assert!(
5507 !p.crossfade(Lane::A1, 1, 5),
5508 "there is no clip after idx 1"
5509 );
5510 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
5511 let a = p.lane(Lane::A1);
5512 assert_eq!(a[0].fade_out, 5);
5513 assert_eq!(a[1].fade_in, 5);
5514 assert_eq!(a[0].fade_in, 0);
5515 assert_eq!(a[1].fade_out, 0);
5516
5517 // A gap between two clips is not adjacency, even on an audio lane.
5518 let mut p2 = Project::single(FILE, 1);
5519 let a2 = p2.add_lane(LaneKind::Audio);
5520 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
5521 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5522 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
5523 }
5524
5525 /// The rule [`Project::write_split`] follows for the edge the razor makes:
5526 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
5527 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
5528 /// mirror image.
5529 #[test]
5530 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
5531 let mut p = Project::single(FILE, 20);
5532 assert!(p.set_fade_in(Lane::V1, 0, 15));
5533 assert!(p.set_fade_out(Lane::V1, 0, 15));
5534 assert!(p.split(5));
5535 let v = p.lane(Lane::V1);
5536 assert_eq!(v[0].fade_in, 5, "the left half's kept fade-in, clamped to 5 frames");
5537 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
5538 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
5539 assert_eq!(v[1].fade_out, 15, "the right half's kept fade-out, unclamped: 15 frames fit in 15");
5540 }
5541
5542 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
5543 /// no successor, and two clips that do not touch, and otherwise clamps
5544 /// the dissolve to the shorter of the two clips it spans.
5545 #[test]
5546 fn set_transition_out_only_dissolves_adjacent_video_clips() {
5547 let mut p = Project::single(FILE, 20);
5548 assert!(p.split(15), "a short 5-frame tail to clamp against");
5549 assert!(
5550 !p.set_transition_out(Lane::A1, 0, 5),
5551 "audio is not a video lane"
5552 );
5553 assert!(
5554 !p.set_transition_out(Lane::V1, 1, 5),
5555 "there is no clip after idx 1"
5556 );
5557 assert!(
5558 p.set_transition_out(Lane::V1, 0, 100),
5559 "the two halves are adjacent"
5560 );
5561 assert_eq!(
5562 p.transition_out_of(Lane::V1, 0),
5563 5,
5564 "clamped to the shorter neighbour's 5 frames"
5565 );
5566
5567 // A gap between two clips is not adjacency, even on the video lane.
5568 let mut p2 = Project::single(FILE, 1);
5569 let v2 = p2.add_lane(LaneKind::Video);
5570 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
5571 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
5572 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
5573 }
5574
5575 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
5576 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
5577 /// only the half that kept the clip's original *end* keeps the dissolve,
5578 /// re-clamped to its own now-shorter length; the head the cut just made
5579 /// has no successor to dissolve into and starts flat.
5580 #[test]
5581 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
5582 let mut p = Project::single(FILE, 20);
5583 assert!(
5584 !p.set_transition_out(Lane::V1, 0, 0),
5585 "one clip on the lane, no successor to dissolve into yet"
5586 );
5587 // Give the clip a dissolve by hand, then cut it in two.
5588 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
5589 assert!(p.split(5));
5590 let v = p.lane(Lane::V1);
5591 assert_eq!(v[0].transition_out, 0, "the cut edge it made has no successor");
5592 assert_eq!(
5593 v[1].transition_out, 15,
5594 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
5595 );
5596 }
5597
5598 /// The music video's own path: the take comes apart into halves that carry
5599 /// ids of their own, one undo puts it back, and two clips over the same
5600 /// frames become one take again by hand.
5601 #[test]
5602 fn a_take_comes_apart_and_goes_back_together() {
5603 let mut p = Project::single(FILE, 9);
5604 let one = p.clips()[0].link.expect("a fresh project is one take");
5605 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
5606
5607 // A third lane in the same group -- and the merge case with it: a
5608 // placement is in no group, and grouping it in leaves *one* group.
5609 let v2 = p.add_lane(LaneKind::Video);
5610 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5611 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
5612 p.group(Lane::V1, 0, v2, 0)
5613 .expect("the same frames, one lane over");
5614 let id = p.clips()[0].link.expect("still a group");
5615 assert!(
5616 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5617 "one id over the three, not two groups sharing a span"
5618 );
5619 links_are_consistent(&p.lanes).expect("one id, one span");
5620
5621 // Detached by the sound: every half of the group, not only the two.
5622 assert!(p.ungroup(Lane::A1, 0));
5623 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
5624 assert!(
5625 ids.iter().all(Option::is_some),
5626 "a half keeps an id of its own"
5627 );
5628 assert!(
5629 ids.iter()
5630 .enumerate()
5631 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
5632 "and no two halves are the same group any more: {ids:?}"
5633 );
5634 links_are_consistent(&p.lanes).expect("a lone id is legal");
5635
5636 // One snapshot for the whole detach.
5637 assert!(p.undo());
5638 assert!(
5639 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
5640 "one undo puts the whole group back"
5641 );
5642
5643 // And back together by hand: the two the pointer named, and only them.
5644 assert!(p.ungroup(Lane::V1, 0));
5645 p.group(Lane::V1, 0, Lane::A1, 0)
5646 .expect("both cover [0, 9)");
5647 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
5648 assert_ne!(
5649 p.lane(v2)[0].link,
5650 p.lane(Lane::V1)[0].link,
5651 "the third half stayed detached"
5652 );
5653 links_are_consistent(&p.lanes).expect("one id, one span");
5654 }
5655
5656 /// What a group may not be, and what a detach has nothing to take apart --
5657 /// none of which may cost an undo step.
5658 #[test]
5659 fn a_group_is_one_span_and_one_clip_per_lane() {
5660 let mut p = three();
5661 let before = shape(&p);
5662 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
5663
5664 assert!(
5665 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
5666 "two clips of one lane are never one take"
5667 );
5668 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
5669 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
5670 assert!(
5671 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
5672 "{spans}"
5673 );
5674 assert!(
5675 spans.contains("trim them to matching bounds first"),
5676 "{spans}"
5677 );
5678 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
5679
5680 // A half nothing else is grouped with is already detached, a placement
5681 // is in no group at all, and an index that is not there has nothing to
5682 // detach either.
5683 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
5684 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
5685 assert!(p.lift(Lane::A1, 0));
5686 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
5687 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
5688
5689 // Two undos, one per edit: not one of the refusals pushed a snapshot.
5690 assert!(p.undo());
5691 assert!(p.undo());
5692 assert_eq!(shape(&p), before);
5693 }
5694
5695 /// Where a re-rate puts a playhead: the scene under the cursor stays the
5696 /// scene under the cursor, measured the way a viewer would -- the source
5697 /// frame playing at the playhead is the same frame after the write, at
5698 /// every playhead position the re-rate can catch one.
5699 #[test]
5700 fn a_re_rate_keeps_the_frame_under_the_playhead() {
5701 let caption = |start: u32, frames: u32| SubClip {
5702 start,
5703 frames,
5704 track: 0,
5705 in_us: 0,
5706 out_us: i64::from(frames) * 1_000_000,
5707 link: None,
5708 };
5709 let track = || SubtitleTrack {
5710 path: FILE.into(),
5711 track: None,
5712 language: "eng".into(),
5713 name: String::new(),
5714 label: "eng".into(),
5715 cues: Vec::new(),
5716 bitmap: false,
5717 refused: None,
5718 };
5719 // A group of a 300-frame clip and a caption offset 30 frames into it.
5720 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
5721 let s1 = p.add_lane(LaneKind::Subtitle);
5722 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
5723 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5724
5725 // The frame playing at `at`: which clip, and which source frame of it.
5726 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
5727 p.span_at(Lane::V1, at)
5728 .and_then(|s| s.from.map(|(source, from)| (source, from)))
5729 };
5730
5731 // Inside the held clip: the source frame under the playhead is the
5732 // same one after the re-rate, at 2x and at half speed both.
5733 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
5734 let at = 120;
5735 let before = playing(&p, at).expect("a clip under the playhead");
5736 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
5737 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
5738 .expect("room for it");
5739 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
5740 assert_eq!(before, after, "{what}: the same source frame plays");
5741 // ...and the write itself is untouched by the question.
5742 assert!(p.undo(), "{what}: one step back");
5743 }
5744
5745 // Past the group -- the clip ends at 300 and the caption at 270, so
5746 // from 300 on nothing is re-timed under the playhead: unmoved.
5747 for at in [300u32, 301, 1_000] {
5748 assert_eq!(
5749 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
5750 Some(at),
5751 "at {at}: outside every member, unmoved"
5752 );
5753 }
5754 // The boundary is exact: the held clip's own last frame (299) maps
5755 // to its new one (149 -- the last frame inside [0, 150), where the
5756 // shrunken clip's last source frame plays), and its first stays put.
5757 assert_eq!(
5758 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
5759 Some(149)
5760 );
5761 assert_eq!(
5762 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
5763 Some(0)
5764 );
5765 // A spot the caption shares with the clip maps by the clip (it is
5766 // what is *playing* there): the held clip's own proportion, which on
5767 // this fixture is also its head.
5768 assert_eq!(
5769 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
5770 Some(45),
5771 "the clip under the caption owns the spot"
5772 );
5773 }
5774
5775 /// A playhead inside another clip member of the group: that member keeps
5776 /// its own head, so the mapping is by its proportion and not the held
5777 /// clip's -- and the frame under the cursor is still the frame that was.
5778 #[test]
5779 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
5780 let mut p = Project::single(FILE, 300);
5781 // A second clip, grouped with the first but starting 300 later: the
5782 // head the group shares and its own differ by exactly that.
5783 let v2 = p.add_lane(LaneKind::Video);
5784 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
5785 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
5786 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
5787
5788 let at = 450; // inside the second member, 150 past its head
5789 let before = p.span_at(v2, at).and_then(|s| s.from);
5790 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
5791 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5792 .expect("room for it");
5793 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
5794 assert_eq!(before, after, "the second member's own frame plays");
5795 // ...and the mapping itself: 150 past its head halves, the head stays.
5796 assert_eq!(mapped, Some(375));
5797 }
5798
5799 /// The link counter a load seeds sits past every id the file names,
5800 /// captions included: a hand-grouped caption may carry the highest id there
5801 /// is, and a counter that read the clips alone would hand it to the next
5802 /// group that asked -- silently grouping the caption with clips it never
5803 /// met.
5804 #[test]
5805 fn the_link_counter_sits_past_a_caption_only_id() {
5806 let track = || SubtitleTrack {
5807 path: FILE.into(),
5808 track: None,
5809 language: "eng".into(),
5810 name: String::new(),
5811 label: "eng".into(),
5812 cues: Vec::new(),
5813 bitmap: false,
5814 refused: None,
5815 };
5816 let mut p = Project::single(FILE, 9);
5817 p.add_lane(LaneKind::Subtitle);
5818 let caption = SubClip {
5819 start: 0,
5820 frames: 6,
5821 track: 0,
5822 in_us: 0,
5823 out_us: 6_000_000,
5824 // The highest id in the file, and only a caption carries it.
5825 link: Some(1),
5826 };
5827 let mut p = p
5828 .with_subtitles(vec![track()])
5829 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
5830 .expect("a caption may carry the file's highest id");
5831
5832 // A new group on lanes the caption is not on mints the next id -- which
5833 // must not be the caption's.
5834 let v2 = p.add_lane(LaneKind::Video);
5835 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
5836 p.group_all(&[(Lane::V1, 0), (v2, 0)])
5837 .expect("the clips group");
5838 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
5839 assert_ne!(
5840 minted,
5841 1,
5842 "the caption's id is not re-issued to clips"
5843 );
5844 assert_eq!(
5845 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
5846 Some(1),
5847 "the caption keeps its own group"
5848 );
5849 assert!(links_are_consistent(&p.lanes).is_ok());
5850 }
5851
5852 /// A rate re-times the caption members of the group by the ratio it gives
5853 /// the held clip: the span on the timeline compresses about the held clip's
5854 /// head, the words' own window untouched -- and one undo puts it back.
5855 #[test]
5856 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
5857 let caption = |start: u32, frames: u32| SubClip {
5858 start,
5859 frames,
5860 track: 0,
5861 in_us: 0,
5862 out_us: i64::from(frames) * 1_000_000,
5863 link: None,
5864 };
5865 let track = || SubtitleTrack {
5866 path: FILE.into(),
5867 track: None,
5868 language: "eng".into(),
5869 name: String::new(),
5870 label: "eng".into(),
5871 cues: Vec::new(),
5872 bitmap: false,
5873 refused: None,
5874 };
5875 let grouped = || {
5876 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5877 let s1 = p.add_lane(LaneKind::Subtitle);
5878 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5879 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5880 (p, s1)
5881 };
5882
5883 // An aligned take, doubled: the caption plays in half the frames.
5884 let (mut p, s1) = grouped();
5885 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
5886 .expect("room for it");
5887 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
5888 let s = p.sub_lane(s1)[0];
5889 assert_eq!((s.start, s.frames), (0, 45), "same words, half the timeline");
5890 assert_eq!((s.in_us, s.out_us), (0, 90_000_000), "the window is untouched");
5891 assert!(links_are_consistent(&p.lanes).is_ok());
5892 assert!(p.undo());
5893 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
5894
5895 // An offset group, slowed to half: the caption's *offset from the held
5896 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
5897 // 0.5x, and still ends where the clip does.
5898 let (mut p, s1) = grouped();
5899 p.lift_sub(s1, 0);
5900 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
5901 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5902 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
5903 .expect("room for it");
5904 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
5905 let s = p.sub_lane(s1)[0];
5906 assert_eq!((s.start, s.frames), (60, 120), "the offset doubles with the clip");
5907 assert_eq!(s.end(), p.lane(Lane::V1)[0].end(), "still ends with the clip");
5908
5909 // A stretch that runs the caption into its neighbour is refused, by
5910 // lane and frame, and costs no undo step.
5911 let (mut p, s1) = grouped();
5912 p.lift_sub(s1, 0);
5913 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
5914 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
5915 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
5916 let history = p.history.len();
5917 let err = p
5918 .set_speed(Lane::V1, 0, Speed::from_permille(500))
5919 .unwrap_err()
5920 .to_string();
5921 assert!(
5922 err.contains("the S1 caption at frame 0 would run to frame 180 and the next starts at 95"),
5923 "{err}"
5924 );
5925 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
5926 }
5927
5928 /// The silence scan's speed-up re-times the captions on a scoped lane with
5929 /// everything else: the piece inside the region plays in the region's new
5930 /// frames, and what sits behind the region slides up with the clips.
5931 #[test]
5932 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
5933 let caption = |start: u32, frames: u32| SubClip {
5934 start,
5935 frames,
5936 track: 0,
5937 in_us: 0,
5938 out_us: i64::from(frames) * 1_000_000,
5939 link: None,
5940 };
5941 let track = || SubtitleTrack {
5942 path: FILE.into(),
5943 track: None,
5944 language: "eng".into(),
5945 name: String::new(),
5946 label: "eng".into(),
5947 cues: Vec::new(),
5948 bitmap: false,
5949 refused: None,
5950 };
5951 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
5952 let s1 = p.add_lane(LaneKind::Subtitle);
5953 // Words over the region [30, 60) and words behind it.
5954 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
5955 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
5956
5957 // The region [30, 60) plays at 4x: 30 frames become 8, everything
5958 // behind slides up 22.
5959 // The scope is what the card's Take row says, caption lane included.
5960 p.speed_regions(
5961 &[(30, 30)],
5962 Speed::from_permille(4000),
5963 &[Lane::V1, Lane::A1, s1],
5964 )
5965 .expect("the region speeds up");
5966 let subs = p.sub_lane(s1);
5967 assert_eq!(
5968 (subs[0].start, subs[0].frames),
5969 (30, 8),
5970 "the piece inside plays in the region's new frames"
5971 );
5972 assert_eq!(
5973 (subs[1].start, subs[1].frames),
5974 (38, 30),
5975 "the piece behind slides up by what the region gave back"
5976 );
5977 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
5978 }
5979
5980 /// [`Project::speeded_playhead`]'s caption arm fires only when the
5981 /// playhead is inside a caption member and outside every clip member --
5982 /// a shape every other fixture avoids by keeping its caption inside the
5983 /// held clip. Here the caption overhangs the clip's tail, and the
5984 /// playhead standing in that overhang is answered by the caption's own
5985 /// piece: it scales about the held clip's head by the held clip's own
5986 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
5987 #[test]
5988 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
5989 let caption = |start: u32, frames: u32| SubClip {
5990 start,
5991 frames,
5992 track: 0,
5993 in_us: 0,
5994 out_us: i64::from(frames) * 1_000_000,
5995 link: None,
5996 };
5997 let track = || SubtitleTrack {
5998 path: FILE.into(),
5999 track: None,
6000 language: "eng".into(),
6001 name: String::new(),
6002 label: "eng".into(),
6003 cues: Vec::new(),
6004 bitmap: false,
6005 refused: None,
6006 };
6007 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6008 let s1 = p.add_lane(LaneKind::Subtitle);
6009 // The caption spans [80, 100) -- ten frames past the clip's own end
6010 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
6011 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
6012 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6013 // At 2x the clip halves to 45 frames; the overhang frame 95, which
6014 // no clip member's old span reaches, is the caption's own question:
6015 // half of 95 is 47.5, rounded to 48.
6016 assert_eq!(
6017 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
6018 Some(48),
6019 "the overhang frame answers through the caption's own piece"
6020 );
6021 }
6022
6023 /// `write_speed` and `speeded_playhead` are two questions of the SAME
6024 /// map ([`map`]'s architecture law): a caption's landed span comes from
6025 /// the map's own ends, and the playhead standing at the caption's own
6026 /// last frame before the write has to land exactly where the write put
6027 /// it -- across clip lengths and rates that round differently, and an
6028 /// odd-length caption straddling the clip's own tail edge, the corner
6029 /// where `write_speed` used to answer a frame short.
6030 #[test]
6031 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
6032 let caption = |start: u32, frames: u32| SubClip {
6033 start,
6034 frames,
6035 track: 0,
6036 in_us: 0,
6037 out_us: i64::from(frames) * 1_000_000,
6038 link: None,
6039 };
6040 let track = || SubtitleTrack {
6041 path: FILE.into(),
6042 track: None,
6043 language: "eng".into(),
6044 name: String::new(),
6045 label: "eng".into(),
6046 cues: Vec::new(),
6047 bitmap: false,
6048 refused: None,
6049 };
6050 for &len in &[90u32, 91, 177, 300, 301] {
6051 for &permille in &[500u16, 2000, 2500, 3000] {
6052 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
6053 let s1 = p.add_lane(LaneKind::Subtitle);
6054 // An odd-length caption straddling the clip's tail edge: its
6055 // own last frame lands past the held clip.
6056 let c_start = len.saturating_sub(3);
6057 p.place_sub(s1, c_start, caption(c_start, 7)).expect("placed");
6058 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6059 let speed = Speed::from_permille(permille);
6060 let last = c_start + 7 - 1;
6061 let mapped = p
6062 .speeded_playhead(Lane::V1, 0, speed, last)
6063 .expect("the caption is there");
6064 if p.set_speed(Lane::V1, 0, speed).is_err() {
6065 continue; // a refusal changes nothing: not this law's cell
6066 }
6067 let landed = p.sub_lane(s1)[0];
6068 if permille >= 1000 {
6069 // A speed-up compresses the timeline: many old frames
6070 // share one new frame, so the caption's own last old
6071 // frame lands flush with the write's own boundary --
6072 // the exact law [`write_speed`]'s worked drift-fix case
6073 // is stated against.
6074 assert_eq!(
6075 mapped,
6076 landed.end() - 1,
6077 "len {len} permille {permille}: the playhead at the caption's own \
6078 last frame lands where the write actually put it"
6079 );
6080 } else {
6081 // A slow-down expands it: one old frame becomes several
6082 // new ones, and `apply` answers where that frame's own
6083 // block *starts*, not where the caption's last new
6084 // frame (the end of that same block) sits -- a
6085 // one-frame gap inherent to the piece's own semantics,
6086 // not a drift between the two callers. Both still have
6087 // to agree the answer sits inside the caption the write
6088 // actually landed.
6089 assert!(
6090 (landed.start..landed.end()).contains(&mapped),
6091 "len {len} permille {permille}: the playhead lands inside the \
6092 caption the write actually put ({landed:?}), got {mapped}"
6093 );
6094 }
6095 }
6096 }
6097 }
6098
6099 /// A grouped caption's cues re-time with its clip: the placement's window
6100 /// crossed the timeline at its own proportion before any rate, and a
6101 /// re-rate changes that proportion (the frames compress, the window does
6102 /// not). A cue eight seconds into a window played at 2x crosses the screen
6103 /// four seconds in -- and at unity every cue lands exactly where it always
6104 /// did, byte for byte.
6105 #[test]
6106 fn a_grouped_captions_cues_re_time_with_its_clip() {
6107 let track = SubtitleTrack {
6108 path: FILE.into(),
6109 track: None,
6110 language: "eng".into(),
6111 name: String::new(),
6112 label: "eng".into(),
6113 cues: vec![crate::subtitle::Cue {
6114 start_us: 8_000_000,
6115 end_us: 9_000_000,
6116 text: "late line".into(),
6117 image: None,
6118 }],
6119 bitmap: false,
6120 refused: None,
6121 };
6122 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
6123 let s1 = p.add_lane(LaneKind::Subtitle);
6124 // Ten seconds of the track over ten seconds of timeline: unity.
6125 p.place_sub(
6126 s1,
6127 0,
6128 SubClip {
6129 start: 0,
6130 frames: 300,
6131 track: 0,
6132 in_us: 0,
6133 out_us: 10_000_000,
6134 link: None,
6135 },
6136 )
6137 .expect("placed");
6138
6139 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
6140 let unity = p.sub_lane_cues(s1, FPS);
6141 assert_eq!(
6142 unity
6143 .iter()
6144 .map(|c| (c.start_us, c.end_us, &*c.text))
6145 .collect::<Vec<_>>(),
6146 [(8_000_000, 9_000_000, "late line")],
6147 "a unity placement maps exactly as it always did"
6148 );
6149
6150 // Grouped with the clip and re-rated to 2x: the same window now crosses
6151 // in half the time, so the cue at 8s of it lands 4s in.
6152 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6153 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
6154 .expect("room for it");
6155 let re_timed = p.sub_lane_cues(s1, FPS);
6156 assert_eq!(
6157 re_timed
6158 .iter()
6159 .map(|c| (c.start_us, c.end_us))
6160 .collect::<Vec<_>>(),
6161 [(4_000_000, 4_500_000)],
6162 "the cue crosses with the clip's new rate"
6163 );
6164 }
6165
6166 /// A video arriving on a timeline of words mutates none of them: the
6167 /// import's rippling insert used to open room on the subtitle lanes too,
6168 /// splitting a caption it landed inside and sliding the rest behind the
6169 /// video -- the hand asked for an add, and got a cut it never made. The
6170 /// words keep their own clock; co-travel is what a group is for.
6171 #[test]
6172 fn an_arriving_clip_never_touches_the_captions() {
6173 let caption = |start: u32, frames: u32| SubClip {
6174 start,
6175 frames,
6176 track: 0,
6177 in_us: i64::from(start) * 1_000_000 / 30,
6178 out_us: i64::from(start + frames) * 1_000_000 / 30,
6179 link: None,
6180 };
6181 let track = || SubtitleTrack {
6182 path: FILE.into(),
6183 track: None,
6184 language: "eng".into(),
6185 name: String::new(),
6186 label: "eng".into(),
6187 cues: Vec::new(),
6188 bitmap: false,
6189 refused: None,
6190 };
6191 // A timeline of words alone: 60 frames of caption, no media clips.
6192 let mut p = Project::single(FILE, 60)
6193 .with_subtitles(vec![track()]);
6194 for l in [Lane::V1, Lane::A1] {
6195 while !p.lane(l).is_empty() {
6196 p.lift(l, 0);
6197 }
6198 }
6199 let s1 = p.add_lane(LaneKind::Subtitle);
6200 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
6201 let before = p.sub_lane(s1).to_vec();
6202
6203 // The video lands BEFORE the caption's span: nothing moves.
6204 let vid = clip(0, 0, 30, 0);
6205 assert!(p.paste(0, vid), "the video goes down at the head");
6206 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
6207
6208 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
6209 // byte the placement the hand made.
6210 assert!(p.paste(15, vid), "a second video lands inside the caption");
6211 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
6212 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
6213 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
6214 assert!(links_are_consistent(&p.lanes).is_ok());
6215 }
6216
6217 /// The region's caption pieces re-time by mapped boundaries forced apart:
6218 /// rounding start and length independently can land two cues on one frame,
6219 /// and the artifact is clamped -- one frame each, in order, none past the
6220 /// region's new end -- never an overlap on the lane.
6221 #[test]
6222 fn a_regions_caption_pieces_never_round_onto_one_another() {
6223 let caption = |start: u32, frames: u32| SubClip {
6224 start,
6225 frames,
6226 track: 0,
6227 in_us: 0,
6228 out_us: i64::from(frames) * 1_000_000,
6229 link: None,
6230 };
6231 let track = |n| SubtitleTrack {
6232 path: FILE.into(),
6233 track: None,
6234 language: "eng".into(),
6235 name: String::new(),
6236 label: format!("eng{n}"),
6237 cues: Vec::new(),
6238 bitmap: false,
6239 refused: None,
6240 };
6241 // Three lanes, one repro shape each: adjacent one-frame cues, a
6242 // three-frame pair, and the region's last cue against the first
6243 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
6244 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
6245 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
6246 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
6247 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
6248 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
6249 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
6250 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
6251 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
6252
6253 let mut scope = vec![Lane::V1, Lane::A1];
6254 scope.extend(lanes.iter().copied());
6255 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
6256 .expect("the region speeds up");
6257 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
6258 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
6259 p.sub_lane(lane).iter().map(|s| (s.start, s.frames)).collect()
6260 };
6261 assert_eq!(spans(&p, lanes[0]), [(5, 1), (6, 1)], "one frame each, in order");
6262 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
6263 // and the walk pushes the second to where the first ends.
6264 assert_eq!(spans(&p, lanes[1]), [(3, 1), (4, 2)], "forced apart, kept in order");
6265 // The last cue of the region ends exactly where the region now does
6266 // (frame 15), and the caption behind it lands on that same frame:
6267 // touching, never overlapping.
6268 assert_eq!(spans(&p, lanes[2]), [(14, 1), (15, 15)], "the cue ends with the region");
6269 for &lane in &lanes {
6270 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
6271 }
6272 }
6273
6274 /// The scope law names a caption half too: a scoped cut that would move one
6275 // track of a group whose caption sits outside the scope is refused.
6276 #[test]
6277 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
6278 let caption = |start: u32, frames: u32| SubClip {
6279 start,
6280 frames,
6281 track: 0,
6282 in_us: 0,
6283 out_us: i64::from(frames) * 1_000_000,
6284 link: None,
6285 };
6286 let track = || SubtitleTrack {
6287 path: FILE.into(),
6288 track: None,
6289 language: "eng".into(),
6290 name: String::new(),
6291 label: "eng".into(),
6292 cues: Vec::new(),
6293 bitmap: false,
6294 refused: None,
6295 };
6296 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6297 let s1 = p.add_lane(LaneKind::Subtitle);
6298 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
6299 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6300
6301 // The subtitle lane is not in the scope, so the group's caption half
6302 // sits outside it: refused, in the law's own words.
6303 let err = p
6304 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
6305 .unwrap_err()
6306 .to_string();
6307 assert!(
6308 err.contains("is one take with the S1 caption at frame 0"),
6309 "{err}"
6310 );
6311
6312 // ...and with the caption's lane in the scope, the cut carries it:
6313 // the words over the hole go, and the words behind slide up.
6314 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
6315 .expect("the whole group is in the scope");
6316 let subs = p.sub_lane(s1);
6317 assert_eq!(
6318 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
6319 [(0, 10), (10, 75)],
6320 "the caption is cut and shifted with the clips"
6321 );
6322 }
6323
6324 /// The caption a hand groups: `group_all` over clips *and* a caption, the
6325 /// mates riding along, the offsets kept, the refusals in words.
6326 #[test]
6327 fn a_hand_built_group_holds_clips_and_a_caption() {
6328 let caption = |start: u32, frames: u32| SubClip {
6329 start,
6330 frames,
6331 track: 0,
6332 in_us: 0,
6333 out_us: i64::from(frames) * 1_000_000,
6334 link: None,
6335 };
6336 let track = || SubtitleTrack {
6337 path: FILE.into(),
6338 track: None,
6339 language: "eng".into(),
6340 name: String::new(),
6341 label: "eng".into(),
6342 cues: Vec::new(),
6343 bitmap: false,
6344 refused: None,
6345 };
6346 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6347 let v2 = p.add_lane(LaneKind::Video);
6348 let s1 = p.add_lane(LaneKind::Subtitle);
6349 // A layer at its own offset, and a caption over the head of the take.
6350 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
6351 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
6352
6353 // Too few, one lane twice, and an index that is not there: words, no
6354 // snapshot.
6355 let history = p.history.len();
6356 assert!(p.group_all(&[]).unwrap_err().to_string().contains("two placements or more"));
6357 assert!(p
6358 .group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
6359 .unwrap_err()
6360 .to_string()
6361 .contains("V1 is picked twice"));
6362 assert!(p
6363 .group_all(&[(Lane::V1, 0), (s1, 9)])
6364 .unwrap_err()
6365 .to_string()
6366 .contains("no subtitle 9"));
6367 assert_eq!(p.history.len(), history, "refusals cost no undo step");
6368
6369 // The group: the picture, the layer, and the caption -- and the sound
6370 // the picture was already grouped with comes along unasked.
6371 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
6372 .expect("three picks, three lanes");
6373 let id = p.lane(Lane::V1)[0].link.expect("grouped");
6374 for lane in [Lane::V1, Lane::A1, v2] {
6375 assert_eq!(p.lane(lane)[0].link, Some(id), "{} rides along", lane.label());
6376 }
6377 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
6378 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
6379 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
6380 assert!(links_are_consistent(&p.lanes).is_ok());
6381 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
6382
6383 // ...and one undo takes it apart again.
6384 assert!(p.undo());
6385 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
6386
6387 // Detach names a caption like it names a clip: every member an id of
6388 // its own, which is never `None` (see `ungroup`).
6389 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
6390 assert!(p.ungroup(s1, 0));
6391 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
6392 assert!(loose_sub.is_some() && loose_clip.is_some());
6393 assert_ne!(loose_sub, loose_clip);
6394 assert!(links_are_consistent(&p.lanes).is_ok());
6395 }
6396
6397 /// Two captions on one sub lane, each already grouped with a *different*
6398 /// clip: `group_all` over both those clips would merge the two existing
6399 /// groups into one id and leave both captions on `s1` carrying it --
6400 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
6401 /// group closes. Refused by name, and nothing moves.
6402 #[test]
6403 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
6404 let caption = |start: u32, frames: u32| SubClip {
6405 start,
6406 frames,
6407 track: 0,
6408 in_us: 0,
6409 out_us: i64::from(frames) * 1_000_000,
6410 link: None,
6411 };
6412 let track = || SubtitleTrack {
6413 path: FILE.into(),
6414 track: None,
6415 language: "eng".into(),
6416 name: String::new(),
6417 label: "eng".into(),
6418 cues: Vec::new(),
6419 bitmap: false,
6420 refused: None,
6421 };
6422 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6423 let v2 = p.add_lane(LaneKind::Video);
6424 let s1 = p.add_lane(LaneKind::Subtitle);
6425 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
6426 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
6427 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
6428 // V1 grouped with the first caption, v2 with the second -- two
6429 // separate groups, each already one member per lane.
6430 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6431 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
6432 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
6433
6434 let history = p.history.len();
6435 let err = p
6436 .group_all(&[(Lane::V1, 0), (v2, 0)])
6437 .unwrap_err()
6438 .to_string();
6439 assert!(err.contains("one placement per lane"), "{err}");
6440 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
6441 assert_eq!(p.lane(Lane::V1)[0].link, v1_link, "the first group untouched");
6442 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
6443 assert!(links_are_consistent(&p.lanes).is_ok());
6444 }
6445
6446 /// A split hands the caption of a group the same ids it hands the clips:
6447 /// the left halves keep the group, the right halves share a fresh one.
6448 #[test]
6449 fn a_split_cuts_a_grouped_caption_with_its_clips() {
6450 let caption = |start: u32, frames: u32| SubClip {
6451 start,
6452 frames,
6453 track: 0,
6454 in_us: 0,
6455 out_us: i64::from(frames) * 1_000_000,
6456 link: None,
6457 };
6458 let track = || SubtitleTrack {
6459 path: FILE.into(),
6460 track: None,
6461 language: "eng".into(),
6462 name: String::new(),
6463 label: "eng".into(),
6464 cues: Vec::new(),
6465 bitmap: false,
6466 refused: None,
6467 };
6468 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6469 let s1 = p.add_lane(LaneKind::Subtitle);
6470 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
6471 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6472 let take = p.lane(Lane::V1)[0].link.expect("the group id");
6473
6474 assert!(p.split(4));
6475 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
6476 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
6477 assert_eq!(left.frames, 4);
6478 assert_eq!(
6479 right.link,
6480 p.lane(Lane::V1)[1].link,
6481 "the caption's tail shares the clips' fresh id"
6482 );
6483 assert_ne!(right.link, Some(take));
6484 assert!(links_are_consistent(&p.lanes).is_ok());
6485
6486 // Regroup at the seam restores the take, caption included.
6487 assert!(p.regroup(4));
6488 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
6489 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
6490 }
6491
6492 /// Deleting a member of a hand-built group takes the group: every
6493 /// member's own span out of its own lane, hole closed -- the lanes may
6494 /// end up out of step, which is what one undo restores together.
6495 #[test]
6496 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
6497 let caption = |start: u32, frames: u32| SubClip {
6498 start,
6499 frames,
6500 track: 0,
6501 in_us: 0,
6502 out_us: i64::from(frames) * 1_000_000,
6503 link: None,
6504 };
6505 let track = || SubtitleTrack {
6506 path: FILE.into(),
6507 track: None,
6508 language: "eng".into(),
6509 name: String::new(),
6510 label: "eng".into(),
6511 cues: Vec::new(),
6512 bitmap: false,
6513 refused: None,
6514 };
6515 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6516 let s1 = p.add_lane(LaneKind::Subtitle);
6517 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6518 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6519 // A neighbour on a lane the group does not touch.
6520 let v2 = p.add_lane(LaneKind::Video);
6521 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
6522
6523 // By the picture or by the caption, the same whole-group delete.
6524 assert!(p.delete_sub_in(s1, 0));
6525 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
6526 assert!(p.sub_lane(s1).is_empty(), "the caption's span left its lane");
6527 assert_eq!(p.lane(v2)[0].start, 10, "a lane the group does not touch stays");
6528 assert!(links_are_consistent(&p.lanes).is_ok());
6529 assert!(p.undo(), "one step puts the group back");
6530 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
6531 }
6532
6533 /// The delete law, one statement for every anchor: a caption deleted
6534 /// WITH its group ripples its lane exactly as its clip siblings do --
6535 /// the hole closes and what follows slides up -- while a caption lifted
6536 /// alone leaves its gap, as it always has. And the delete of a grouped
6537 /// clip takes the group from whichever member was clicked.
6538 #[test]
6539 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
6540 let caption = |start: u32, frames: u32| SubClip {
6541 start,
6542 frames,
6543 track: 0,
6544 in_us: 0,
6545 out_us: i64::from(frames) * 1_000_000,
6546 link: None,
6547 };
6548 let track = || SubtitleTrack {
6549 path: FILE.into(),
6550 track: None,
6551 language: "eng".into(),
6552 name: String::new(),
6553 label: "eng".into(),
6554 cues: Vec::new(),
6555 bitmap: false,
6556 refused: None,
6557 };
6558 // V+A+S grouped, with a second caption BEHIND the group's caption:
6559 // closing the hole is what the second caption's position says.
6560 let group = || {
6561 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
6562 let s1 = p.add_lane(LaneKind::Subtitle);
6563 p.place_sub(s1, 30, caption(30, 30)).expect("the group's caption");
6564 p.place_sub(s1, 90, caption(90, 30)).expect("the caption behind");
6565 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6566 (p, s1)
6567 };
6568
6569 // Deleted by the picture: all three lanes close.
6570 let (mut p, s1) = group();
6571 assert!(p.delete_in(Lane::V1, 0));
6572 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
6573 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
6574 assert_eq!(
6575 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
6576 [60],
6577 "the caption's lane closed by its own span: the follower slid up"
6578 );
6579 assert!(p.undo(), "one step");
6580 assert_eq!(p.sub_lane(s1).len(), 2, "both captions back, offsets and all");
6581
6582 // By the sound: the same whole-group delete.
6583 let (mut p, s1) = group();
6584 assert!(p.delete_in(Lane::A1, 0));
6585 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6586 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
6587
6588 // By the caption itself: the same again.
6589 let (mut p, s1) = group();
6590 assert!(p.delete_sub_in(s1, 0));
6591 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
6592 assert_eq!(p.sub_lane(s1)[0].start, 60, "closed from the caption's own door");
6593 assert!(links_are_consistent(&p.lanes).is_ok());
6594
6595 // A caption lifted ALONE still leaves its gap: the ungrouped law,
6596 // unchanged.
6597 let (mut p, s1) = group();
6598 assert!(p.ungroup(s1, 0), "the caption stands alone");
6599 assert!(p.lift_sub(s1, 0));
6600 assert_eq!(
6601 p.sub_lane(s1)[0].start, 90,
6602 "the follower stayed put: a lone caption's lift is a gap"
6603 );
6604 }
6605
6606 /// Dragging a grouped caption carries its clips, one delta for all of them
6607 /// -- and a caption in no group refuses an overlap exactly as it always did.
6608 #[test]
6609 fn dragging_a_grouped_caption_carries_its_group() {
6610 let caption = |start: u32, frames: u32| SubClip {
6611 start,
6612 frames,
6613 track: 0,
6614 in_us: 0,
6615 out_us: i64::from(frames) * 1_000_000,
6616 link: None,
6617 };
6618 let track = || SubtitleTrack {
6619 path: FILE.into(),
6620 track: None,
6621 language: "eng".into(),
6622 name: String::new(),
6623 label: "eng".into(),
6624 cues: Vec::new(),
6625 bitmap: false,
6626 refused: None,
6627 };
6628 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6629 let s1 = p.add_lane(LaneKind::Subtitle);
6630 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
6631 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6632
6633 // Same lane, further along: everyone moves by the same eight frames.
6634 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
6635 assert_eq!(p.sub_lane(s1)[0].start, 10);
6636 assert_eq!(p.lane(Lane::V1)[0].start, 8, "the clip follows by the delta");
6637 assert!(links_are_consistent(&p.lanes).is_ok());
6638
6639 // ...and an ungrouped caption is the caption it always was.
6640 assert!(p.ungroup(s1, 0));
6641 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
6642 let s1 = q.add_lane(LaneKind::Subtitle);
6643 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
6644 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
6645 assert!(q
6646 .move_sub(s1, 0, s1, 3)
6647 .unwrap_err()
6648 .to_string()
6649 .contains("already covers"));
6650 }
6651
6652 /// A trim carries a group's caption by the same delta as its clips, clamped
6653 /// to the caption's own walls -- the offsets between the members survive.
6654 #[test]
6655 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
6656 let caption = |start: u32, frames: u32| SubClip {
6657 start,
6658 frames,
6659 track: 0,
6660 in_us: 0,
6661 out_us: i64::from(frames) * 1_000_000,
6662 link: None,
6663 };
6664 let track = || SubtitleTrack {
6665 path: FILE.into(),
6666 track: None,
6667 language: "eng".into(),
6668 name: String::new(),
6669 label: "eng".into(),
6670 cues: Vec::new(),
6671 bitmap: false,
6672 refused: None,
6673 };
6674 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
6675 let s1 = p.add_lane(LaneKind::Subtitle);
6676 // The caption sits two frames into the take and ends one early. The
6677 // source runs past the clip, or there is no tail to pull out.
6678 let src = &[20];
6679 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
6680 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
6681
6682 // The tail goes out by three: the clip to 12, the caption to 11.
6683 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
6684 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
6685 assert_eq!(
6686 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
6687 (2, 11),
6688 "the caption follows by the delta"
6689 );
6690 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
6691
6692 // The head comes in by two: everyone's start moves two along.
6693 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
6694 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
6695 assert!(links_are_consistent(&p.lanes).is_ok());
6696 }
6697
6698 #[test]
6699 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
6700 let mut p = three();
6701 let before = shape(&p);
6702 assert!(!p.split(0), "timeline 0 has nothing before it");
6703 assert!(!p.split(3), "existing boundary");
6704 assert!(!p.split(5), "existing boundary");
6705 assert!(!p.split(9), "one past the last frame");
6706 assert!(!p.split(1_000));
6707 assert_eq!(shape(&p), before);
6708 // one undo lands before the *second* split, so the refusals pushed nothing
6709 assert!(p.undo());
6710 assert_eq!(p.clips().len(), 2, "refused splits push no history");
6711
6712 // ...and a frame that is a gap in both lanes has nothing to split.
6713 let mut p = three();
6714 assert!(p.lift(Lane::V1, 1));
6715 assert!(p.lift(Lane::A1, 1));
6716 assert!(!p.split(4), "a gap is not a clip");
6717 }
6718
6719 #[test]
6720 fn regroup_refuses_what_a_split_could_not_have_made() {
6721 let mut p = three();
6722 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
6723 assert!(p.regroup(5));
6724 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
6725 // A boundary with a gap on one side, and one where the sources do not
6726 // meet, are both refused.
6727 let mut p = three();
6728 assert!(p.lift(Lane::V1, 1));
6729 assert!(p.lift(Lane::A1, 1));
6730 assert!(!p.regroup(3), "nothing starts at 3 any more");
6731 let mut p = three();
6732 for l in p.lanes() {
6733 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
6734 }
6735 assert!(!p.regroup(3), "source 100 does not follow source 3");
6736 assert!(!p.regroup(0), "nothing ends at 0");
6737 assert!(!p.regroup(1_000));
6738 }
6739
6740 #[test]
6741 fn map_and_spans_sweep_every_boundary() {
6742 let p = three();
6743 assert_eq!(p.timeline_frames(), 9);
6744 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
6745 // contiguous source here, so the clip index is what actually moves
6746 let expect = [
6747 (0, (0, 0)),
6748 (1, (0, 1)),
6749 (2, (0, 2)),
6750 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
6751 (4, (1, 4)),
6752 (5, (2, 5)),
6753 (6, (2, 6)),
6754 (7, (2, 7)),
6755 (8, (2, 8)),
6756 ];
6757 for (t, want) in expect {
6758 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
6759 }
6760 assert_eq!(p.map_timeline(9), None);
6761 // A span is the rest of the clip from where it was asked about.
6762 assert_eq!(
6763 p.span_at(Lane::V1, 6),
6764 Some(Span {
6765 start: 6,
6766 len: 3,
6767 from: Some((0, 6)),
6768 speed: Speed::NORMAL
6769 })
6770 );
6771 assert_eq!(p.span_at(Lane::V1, 9), None);
6772 }
6773
6774 /// The fit policy is one byte *in* the clip rather than an index into a
6775 /// table like the eq and the grade: there is nothing for a table to share.
6776 /// It costs the clip nothing at all -- the fields before it (a `usize`
6777 /// source and two `Option<u16>`s) already left the struct padded to 40
6778 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
6779 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
6780 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
6781 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
6782 /// words after it pads out to the next multiple of 8: 56 bytes total.
6783 /// The transform index is a third `Option<u16>`, same reason as the eq and
6784 /// colour ones before it -- it lands in bytes already spent on padding, so
6785 /// the struct still costs 56.
6786 /// This is the assert that says so: a clip that grows a word grows every
6787 /// undo snapshot and every clipboard copy with it.
6788 #[test]
6789 fn a_fit_policy_costs_the_clip_no_word() {
6790 assert_eq!(
6791 std::mem::size_of::<Clip>(),
6792 56,
6793 "Clip changed size: {} bytes",
6794 std::mem::size_of::<Clip>()
6795 );
6796 }
6797
6798 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
6799 /// anything in `three()` so it is recognisable wherever it lands.
6800 const PASTED: Clip = Clip {
6801 fade_in: 0,
6802 fade_out: 0,
6803 transition_out: 0,
6804 start: 0,
6805 in_frame: 100,
6806 out_frame: 102,
6807 source: 0,
6808 link: None,
6809 eq: None,
6810 color: None,
6811 transform: None,
6812 fit: FitPolicy::Fit,
6813 speed: Speed::NORMAL,
6814 };
6815
6816 #[test]
6817 fn paste_mid_clip_splits_around_it() {
6818 let mut p = three();
6819 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
6820 assert_eq!(p.timeline_frames(), 11);
6821 assert_eq!(
6822 shape(&p)[0],
6823 vec![
6824 clip(0, 0, 3, 0),
6825 clip(3, 3, 5, 0),
6826 clip(5, 5, 6, 0),
6827 clip(6, 100, 102, 0),
6828 clip(8, 6, 9, 0),
6829 ]
6830 );
6831 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
6832 // The pasted frames are exactly where they were asked for, and the
6833 // split-off remainder resumes after them.
6834 assert_eq!(p.map_timeline(6), Some((3, 100)));
6835 assert_eq!(p.map_timeline(7), Some((3, 101)));
6836 assert_eq!(p.map_timeline(8), Some((4, 6)));
6837 }
6838
6839 #[test]
6840 fn paste_at_boundary_zero_and_end() {
6841 let mut p = three();
6842 assert!(p.paste(3, PASTED), "existing boundary: no split");
6843 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
6844 assert_eq!(p.map_timeline(3), Some((1, 100)));
6845
6846 let mut p = three();
6847 assert!(p.paste(0, PASTED));
6848 assert_eq!(p.map_timeline(0), Some((0, 100)));
6849 assert_eq!(p.map_timeline(2), Some((1, 0)));
6850
6851 // At the end: appended, there being nothing in front to leave black.
6852 let mut p = three();
6853 assert!(p.paste(9, PASTED));
6854 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
6855 // Past it: down on the frame it was asked for, black in front of it --
6856 // a row let go on the open bed lands under the ghost that promised it.
6857 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
6858 assert!(p.paste(1_000, PASTED));
6859 assert_eq!(p.timeline_frames(), 1_002);
6860 assert_eq!(p.lane(Lane::V1).last().expect("the pasted clip").start, 1_000);
6861 assert_eq!(p.lane(Lane::A1).last().expect("its other half").start, 1_000);
6862
6863 // An empty clip is the one thing refused, and it pushes no history.
6864 let mut p = three();
6865 assert!(!p.paste(4, clip(0, 7, 7, 0)));
6866 assert_eq!(p.clips().len(), 3);
6867 }
6868
6869 /// The data-loss paste: a clip of a source with no picture used to land on
6870 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
6871 /// carried it was refused on the way back in ("a box with a larger size").
6872 #[test]
6873 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
6874 let mut p = three();
6875 let wav = p.import("/nonexistent/song.wav", 0);
6876 let copied = Clip {
6877 fade_in: 0,
6878 fade_out: 0,
6879 transition_out: 0,
6880 source: wav,
6881 ..PASTED
6882 };
6883 assert!(p.paste(3, copied));
6884 // The room is opened on every lane, or the two would slide apart...
6885 assert_eq!(p.timeline_frames(), 11);
6886 assert_eq!(
6887 shape(&p)[0],
6888 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
6889 "the video lane got room and nothing else"
6890 );
6891 // ...but the clip itself only reaches the lane that can play it.
6892 assert_eq!(
6893 shape(&p)[1],
6894 vec![
6895 clip(0, 0, 3, 0),
6896 clip(3, 100, 102, wav),
6897 clip(5, 3, 5, 0),
6898 clip(7, 5, 9, 0)
6899 ]
6900 );
6901 // A source with a picture is unchanged: still the grouped pair.
6902 let mut p = three();
6903 assert!(p.paste(3, PASTED));
6904 assert_eq!(shape(&p)[0], shape(&p)[1]);
6905 }
6906
6907 /// A hand-written file may hold a clip that ends at the very last frame
6908 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
6909 /// to wrap its start round to the front of the lane: an overlap in debug, a
6910 /// project no reload would accept in release.
6911 #[test]
6912 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
6913 let far = clip(u32::MAX - 90, 0, 90, 0);
6914 let parts = |c: Clip| {
6915 Project::from_parts(
6916 vec![Source::new(FILE, 0)],
6917 two(vec![c], vec![c]),
6918 Vec::new(),
6919 Vec::new(),
6920 Vec::new(),
6921 )
6922 .expect("valid parts")
6923 };
6924 let mut p = parts(far);
6925 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
6926 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
6927 assert!(!p.undo(), "...and pushes no history either");
6928 assert!(
6929 !p.paste(u32::MAX, PASTED),
6930 "appending has nowhere to go either: the timeline ends at the last frame"
6931 );
6932 // With room for exactly those frames the same paste is taken.
6933 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
6934 assert!(p.paste(0, PASTED));
6935 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
6936 }
6937
6938 #[test]
6939 fn paste_undoes_in_one_step() {
6940 let mut p = three();
6941 let before = shape(&p);
6942 assert!(p.paste(6, PASTED));
6943 assert!(p.undo());
6944 assert_eq!(shape(&p), before, "a paste is one undo step");
6945 }
6946
6947 #[test]
6948 fn a_copy_outlives_the_clip_it_came_from() {
6949 let mut p = three();
6950 let copied = p.clips()[1]; // [3,5)
6951 assert!(p.delete(1));
6952 // Just a frame range: the source is still on disk either way.
6953 assert!(p.paste(0, copied));
6954 assert_eq!(p.map_timeline(0), Some((0, 3)));
6955 assert_eq!(p.timeline_frames(), 9);
6956 }
6957
6958 #[test]
6959 fn delete_closes_the_gap_on_both_lanes() {
6960 let mut p = three();
6961 assert!(p.delete(1));
6962 assert_eq!(p.timeline_frames(), 7);
6963 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
6964 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
6965 // timeline 3 used to be source 3; the gap closed so it is source 5 now
6966 assert_eq!(p.map_timeline(3), Some((1, 5)));
6967 assert_eq!(p.map_timeline(6), Some((1, 8)));
6968 assert_eq!(p.map_timeline(7), None);
6969 }
6970
6971 #[test]
6972 fn delete_first_last_and_only() {
6973 let mut p = three();
6974 assert!(p.delete(0));
6975 assert_eq!(p.map_timeline(0), Some((0, 3)));
6976 assert_eq!(p.timeline_frames(), 6);
6977
6978 let mut p = three();
6979 assert!(p.delete(2));
6980 assert_eq!(p.timeline_frames(), 5);
6981 assert_eq!(p.map_timeline(4), Some((1, 4)));
6982
6983 assert!(!p.delete(2), "index past the end");
6984 assert!(p.delete(1));
6985 assert!(p.delete(0), "and the last remaining clip goes too");
6986 assert_eq!(p.clips().len(), 0);
6987 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
6988 assert!(!p.delete(0), "there is nothing left to delete");
6989 assert!(p.undo(), "one gesture, one undo");
6990 assert_eq!(p.clips().len(), 1);
6991 }
6992
6993 /// The offset model's point: one lane loses a clip, the other does not move.
6994 #[test]
6995 fn a_lift_leaves_a_gap_and_moves_nothing() {
6996 let mut p = three();
6997 let video_before = shape(&p)[0].clone();
6998 assert!(p.lift(Lane::A1, 1));
6999 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
7000 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
7001 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
7002 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
7003 assert_eq!(p.map(Lane::A1, 4), None);
7004 assert_eq!(
7005 p.span_at(Lane::A1, 3),
7006 Some(Span {
7007 start: 3,
7008 len: 2,
7009 from: None,
7010 speed: Speed::NORMAL
7011 })
7012 );
7013 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
7014 assert!(p.undo());
7015 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
7016 }
7017
7018 #[test]
7019 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
7020 let mut p = three();
7021 assert!(p.lift(Lane::A1, 2));
7022 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
7023 assert_eq!(
7024 p.span_at(Lane::A1, 5),
7025 Some(Span {
7026 start: 5,
7027 len: 4,
7028 from: None,
7029 speed: Speed::NORMAL
7030 }),
7031 "the audio lane holds silence to the end of the picture"
7032 );
7033 assert_eq!(p.span_at(Lane::A1, 9), None);
7034 // Every lane covers the timeline exactly, gaps included.
7035 for l in p.lanes() {
7036 let spans = p.spans_from(l, 0);
7037 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
7038 assert_eq!(spans[0].start, 0);
7039 }
7040 }
7041
7042 /// The timeline is emptiable: the last placement comes off like any other,
7043 /// the project holds "nothing on any lane" as a state, and one undo per
7044 /// gesture brings it back.
7045 #[test]
7046 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
7047 let mut p = Project::single(FILE, 9);
7048 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
7049 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
7050 assert_eq!(p.timeline_frames(), 0);
7051 assert_eq!(p.composite_span_at(0), None, "nothing to show");
7052 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
7053 assert!(!p.lift(Lane::A1, 0), "index past the end");
7054 assert!(p.undo(), "and the last lift comes back");
7055 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
7056 // A saved-and-loaded empty timeline is a project like any other, and it
7057 // still names the file its frame rate came from.
7058 assert!(p.lift(Lane::V1, 0));
7059 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7060 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
7061 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("an empty project loads");
7062 assert_eq!(back.timeline_frames(), 0);
7063 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
7064 }
7065
7066 /// What a keyboard selection walks: one answer per lane, gaps included --
7067 /// the composite's own answer is one lane's and cannot say what the audio
7068 /// lane holds under the same playhead.
7069 #[test]
7070 fn lane_clip_at_answers_for_each_lane_separately() {
7071 let mut p = Project::single(FILE, 9);
7072 assert!(p.split(3), "both lanes split");
7073 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7074 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
7075 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
7076 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
7077 // A gap on one lane leaves the other's clip selectable there.
7078 assert!(p.lift(Lane::A1, 0));
7079 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
7080 assert_eq!(
7081 p.lane_clip_at(Lane::A1, 3),
7082 Some(0),
7083 "indices moved with it"
7084 );
7085 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
7086 // A lane that is not there is not a panic.
7087 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
7088 }
7089
7090 #[test]
7091 fn place_overwrites_only_its_own_lane() {
7092 let mut p = three();
7093 let audio_before = shape(&p)[1].clone();
7094 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
7095 // is trimmed, nothing shifts.
7096 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
7097 assert_eq!(
7098 shape(&p)[0],
7099 vec![
7100 clip(0, 0, 3, 0),
7101 clip(3, 3, 4, 0),
7102 clip(4, 100, 102, 0),
7103 clip(6, 6, 9, 0),
7104 ]
7105 );
7106 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
7107 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
7108
7109 // Placed inside one clip, it splits it in two.
7110 let mut p = Project::single(FILE, 9);
7111 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
7112 assert_eq!(
7113 shape(&p)[0],
7114 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
7115 );
7116 // ...and placed past the end it makes a gap, which is the whole point.
7117 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
7118 assert_eq!(p.timeline_frames(), 22);
7119 assert_eq!(
7120 p.span_at(Lane::V1, 9),
7121 Some(Span {
7122 start: 9,
7123 len: 11,
7124 from: None,
7125 speed: Speed::NORMAL
7126 })
7127 );
7128 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
7129 }
7130
7131 /// A file with sound let go over a further video track: both halves go down,
7132 /// on the same frames, and the audio row is added when the `+ V` button left
7133 /// the project without one. One undo takes the lane and both clips back.
7134 #[test]
7135 fn a_take_placed_on_a_layer_lands_with_its_sound() {
7136 let mut p = three();
7137 let v2 = p.add_lane(LaneKind::Video);
7138 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
7139
7140 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
7141 let a2 = Lane::new(LaneKind::Audio, 1);
7142 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
7143 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
7144 assert_eq!(p.lane(v2)[0].start, 4);
7145 assert_eq!(p.lane(v2)[0].end(), 6);
7146 assert_eq!(
7147 p.lane(v2)[0].link,
7148 p.lane(a2)[0].link,
7149 "one take, not two placements"
7150 );
7151 assert!(p.lane(v2)[0].link.is_some());
7152 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
7153 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
7154
7155 // The pair overwrites its own two lanes and nothing else, exactly as a
7156 // one-lane place does.
7157 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
7158 assert_eq!(p.lane(v2), p.lane(a2));
7159 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
7160 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
7161
7162 assert!(p.undo(), "one step for the second pair");
7163 assert_eq!(p.lane(v2).len(), 1);
7164 assert!(p.undo(), "one step for the first pair *and* its lane");
7165 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7166 assert!(p.lane(v2).is_empty());
7167
7168 // Refusals cost nothing: sound placed alone is `place`'s door.
7169 assert!(!p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)), "audio lane");
7170 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
7171 assert!(
7172 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
7173 "a lane that is not there"
7174 );
7175 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
7176 }
7177
7178 /// The drag between tracks: let go at the frames it already covers the clip
7179 /// keeps them, one undo takes it back, and every way it can be refused
7180 /// leaves the project untouched.
7181 #[test]
7182 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
7183 let v2 = Lane::new(LaneKind::Video, 1);
7184 let mut p = three();
7185 assert_eq!(p.add_lane(LaneKind::Video), v2);
7186 let before = shape(&p);
7187
7188 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
7189 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
7190 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
7191 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7192 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
7193 // One snapshot: a single undo, and the lane list survives it.
7194 assert!(p.undo());
7195 assert_eq!(shape(&p), before);
7196
7197 // A lane that is not there, the lane and frame it is already at, an
7198 // index that is not there, and a move across kinds: all refused,
7199 // nothing changed.
7200 let history = p.history.len();
7201 for (from, idx, to, start) in [
7202 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
7203 (Lane::V1, 1, Lane::V1, 3),
7204 (Lane::V1, 9, v2, 3),
7205 (Lane::V1, 1, Lane::A1, 3),
7206 (Lane::A1, 1, v2, 3),
7207 ] {
7208 assert!(
7209 !p.move_clip(from, idx, to, start),
7210 "{from:?} {idx} -> {to:?} at {start}"
7211 );
7212 }
7213 assert_eq!(shape(&p), before);
7214 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7215
7216 // Landing on another clip is refused rather than overwriting it: the
7217 // pointer named the lane, never the take already sitting there.
7218 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
7219 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
7220 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
7221 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
7222 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
7223 }
7224
7225 /// The drag *along* a track, which is the one every other editor has: the
7226 /// clip lands on the frame the pointer let it go at, and stops dead against
7227 /// the neighbour rather than overwriting it.
7228 #[test]
7229 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
7230 let sources = vec![Source::new(FILE, 0)];
7231 let lanes = vec![
7232 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
7233 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
7234 ];
7235 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
7236 let before = shape(&p);
7237
7238 // Into the gap, exactly where it was let go -- nothing else moves.
7239 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
7240 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
7241 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
7242 // Dragged past the clip in front of it: clamped to its wall, laid end
7243 // to end with it, never over it.
7244 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
7245 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
7246 // One undo per drag, and both of them together are the state it started
7247 // in -- the frames each clip plays never changed.
7248 assert!(p.undo() && p.undo());
7249 assert_eq!(shape(&p), before);
7250
7251 // A drop that changes nothing is a click, not an edit.
7252 let history = p.history.len();
7253 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
7254 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
7255 }
7256
7257 /// A drag carries the whole take: the sound half travels exactly as far as
7258 /// the picture does, and the tighter of their two walls stops both.
7259 #[test]
7260 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
7261 let mut p = three();
7262 assert!(
7263 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
7264 "room to the right"
7265 );
7266 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7267 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7268 // Something in the sound's way, and nothing at all in the picture's.
7269 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
7270 let before = shape(&p);
7271
7272 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
7273 assert_eq!(p.lane(Lane::V1)[1].start, 8, "stopped where the sound did");
7274 assert_eq!(p.lane(Lane::A1)[1].start, 8, "and the sound came with it");
7275 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7276 assert!(p.undo());
7277 assert_eq!(shape(&p), before, "one undo for the whole take");
7278 }
7279
7280 /// The drag that does both at once -- another lane *and* another frame --
7281 /// which is what a pointer let go over a lane always names.
7282 #[test]
7283 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
7284 let v2 = Lane::new(LaneKind::Video, 1);
7285 let mut p = three();
7286 assert_eq!(p.add_lane(LaneKind::Video), v2);
7287
7288 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
7289 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
7290 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
7291 assert_eq!(
7292 p.lane(Lane::A1)[2].start,
7293 20,
7294 "its sound travelled the same distance"
7295 );
7296 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7297 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
7298 }
7299
7300 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
7301 /// [`three`] cuts up all nine of its frames.
7302 const SRC: &[u32] = &[9];
7303
7304 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
7305 /// else on the lane moves, and every wall stops the edge rather than
7306 /// refusing the gesture.
7307 #[test]
7308 fn trimming_the_tail_stops_at_every_wall() {
7309 let mut p = three();
7310
7311 // Pulled in: a gap opens behind it and the clip after it stays put.
7312 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7313 assert_eq!(
7314 shape(&p)[0],
7315 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
7316 );
7317 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
7318 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
7319
7320 // ...and back out, no further than the clip behind it.
7321 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
7322 assert_eq!(
7323 shape(&p)[0][1],
7324 clip(3, 3, 5, 0),
7325 "stopped at the neighbour"
7326 );
7327 assert!(
7328 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
7329 "already at the wall"
7330 );
7331
7332 // One frame of clip always survives, however far back the pointer went.
7333 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
7334 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
7335
7336 // The last clip has no neighbour, so what stops it is the file: nine
7337 // frames is nine frames.
7338 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
7339 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7340 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
7341 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
7342 // A source nobody told us the length of may not grow at all -- an
7343 // out-point past the end of a file is a save that will not open again.
7344 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
7345 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
7346 }
7347
7348 /// The head pulled in takes the in-point with it -- what stays plays what it
7349 /// always played -- and stops at the source's own first frame.
7350 #[test]
7351 fn trimming_the_head_moves_the_in_point() {
7352 let mut p = three();
7353 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7354 assert_eq!(
7355 shape(&p)[0][0],
7356 clip(2, 2, 3, 0),
7357 "two frames off the front"
7358 );
7359 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
7360 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
7361 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
7362 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
7363 // One frame survives here too.
7364 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
7365 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
7366
7367 // A clip that does not begin at its source's first frame: its head goes
7368 // back to source frame 0 and not one frame further.
7369 let mut p = Project::single(FILE, 9);
7370 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
7371 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
7372 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
7373 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
7374 }
7375
7376 /// A clip whose in-point is *past* its own start -- what a ripple delete
7377 /// leaves, the piece in front of it gone and this one slid back to frame 0
7378 /// carrying the in-point the cut gave it. Its head has more source behind it
7379 /// than the timeline has room for, and the timeline's own first frame is the
7380 /// wall: asking is not an overflow, and the answer is 0.
7381 #[test]
7382 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
7383 let mut p = Project::single(FILE, 9);
7384 assert!(p.split(5));
7385 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
7386 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
7387
7388 assert_eq!(
7389 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
7390 Some((0, 3)),
7391 "back to frame 0 at most, and one frame of clip always survives"
7392 );
7393 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
7394 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
7395 assert_eq!(
7396 shape(&p)[0],
7397 vec![clip(2, 7, 9, 0)],
7398 "the in-point followed"
7399 );
7400 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
7401 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
7402 }
7403
7404 /// A still is trimmed from its head exactly as it is from its tail: it has
7405 /// no earlier frame to walk an in-point back to, so the wall is the length
7406 /// the caller's table allows it, measured back from the tail. Measured from
7407 /// the in-point -- which a placed picture has at 0 -- its left edge could
7408 /// never be dragged outwards at all.
7409 #[test]
7410 fn a_stills_head_stretches_out_like_its_tail() {
7411 const STILL: &str = "/nonexistent/card.png";
7412 /// What a still is held to, as `PlaybackSession` fills the table in.
7413 const CAP: &[u32] = &[60];
7414
7415 let mut p = Project::single(STILL, 20);
7416 assert!(p.lift(Lane::A1, 0), "a picture is silent");
7417 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
7418 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
7419
7420 // A source with no entry in the table may not grow, here as at the tail.
7421 assert_eq!(
7422 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
7423 Some((100, 119)),
7424 "a length nobody told us buys no head room"
7425 );
7426 assert_eq!(
7427 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
7428 Some((60, 119)),
7429 "back to a whole cap's worth, one frame of clip surviving"
7430 );
7431 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
7432 assert_eq!(
7433 shape(&p)[0][0],
7434 clip(80, 0, 40, 0),
7435 "twenty frames longer, and still read from the source's first frame"
7436 );
7437 // Past the cap is clamped, exactly as the tail is -- not refused.
7438 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
7439 assert_eq!(
7440 shape(&p)[0][0],
7441 clip(60, 0, 60, 0),
7442 "a cap's worth, no more"
7443 );
7444 // ...and the clip in front is the nearer wall of the two: no head trim
7445 // may open an overlap.
7446 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
7447 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
7448 assert_eq!(
7449 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
7450 Some((85, 119)),
7451 "up to the neighbour's last frame and not over it"
7452 );
7453 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
7454 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
7455 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
7456 }
7457
7458 /// Linked halves trim as one: a link is one span on however many lanes, so
7459 /// the sound follows the picture's edge -- and the tightest wall of the two
7460 /// is what stops both.
7461 #[test]
7462 fn linked_halves_trim_together() {
7463 let mut p = three();
7464 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
7465 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
7466
7467 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
7468 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
7469 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
7470 assert!(
7471 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
7472 "either half drags it"
7473 );
7474 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
7475 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7476
7477 // Something in the way on the *audio* lane stops the picture's tail as
7478 // well: the group can only go as far as its tightest member.
7479 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
7480 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
7481 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
7482 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
7483 links_are_consistent(&p.lanes).expect("still one span");
7484 }
7485
7486 /// A whole drag is one undo step -- the front-end commits once, at the
7487 /// release -- and an edge asked to stay where it is costs none at all.
7488 #[test]
7489 fn a_trim_is_one_undo_step() {
7490 let mut p = three();
7491 let before = shape(&p);
7492 let history = p.history.len();
7493
7494 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
7495 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
7496 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
7497 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
7498 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
7499 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
7500
7501 assert!(p.undo());
7502 assert_eq!(shape(&p), before, "both halves back, in one step");
7503 }
7504
7505 /// A moved half stays in its group: a link names a span, not a lane, so the
7506 /// picture on `V2` is still the same take as the sound under it on `A1`.
7507 #[test]
7508 fn move_clip_keeps_the_group() {
7509 let v2 = Lane::new(LaneKind::Video, 1);
7510 let mut p = three();
7511 p.add_lane(LaneKind::Video);
7512 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
7513 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
7514 assert!(p.move_clip(Lane::V1, 1, v2, 3));
7515 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
7516 links_are_consistent(&p.lanes).expect("one id per lane, one span");
7517 assert_eq!(
7518 p.lane(v2)[0].start,
7519 p.lane(Lane::A1)[1].start,
7520 "and still covers the same span as its sound"
7521 );
7522 }
7523
7524 #[test]
7525 fn ripple_delete_spans_partial_clips() {
7526 let mut p = three();
7527 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
7528 assert!(p.ripple_delete(2, 4));
7529 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
7530 assert_eq!(shape(&p)[1], shape(&p)[0]);
7531 assert_eq!(p.timeline_frames(), 5);
7532 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
7533 assert!(p.undo());
7534 assert_eq!(shape(&p), shape(&three()));
7535 // One that takes everything is a delete like any other: the timeline
7536 // empties, and the undo it cost brings it back whole.
7537 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
7538 assert_eq!(p.timeline_frames(), 0);
7539 assert!(
7540 !p.ripple_delete(0, 100),
7541 "and a delete with nothing left to take is not an undo step"
7542 );
7543 assert!(p.undo());
7544 assert_eq!(shape(&p), shape(&three()));
7545 }
7546
7547 #[test]
7548 fn undo_restores_exactly() {
7549 let mut p = three();
7550 let after_splits = shape(&p);
7551 assert!(p.delete(1));
7552 assert!(p.undo());
7553 assert_eq!(shape(&p), after_splits);
7554
7555 // walk all the way back through both splits, then run dry
7556 assert!(p.undo());
7557 assert_eq!(p.clips().len(), 2);
7558 assert!(p.undo());
7559 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7560 assert!(!p.undo(), "empty history");
7561 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
7562 }
7563
7564 #[test]
7565 fn redo_restores_exactly() {
7566 let mut p = three();
7567 assert!(p.delete(1));
7568 let after_delete = p.parts();
7569 assert!(p.undo());
7570 assert!(p.redo());
7571 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
7572 assert!(!p.redo(), "empty redo stack");
7573 }
7574
7575 #[test]
7576 fn edit_after_undo_empties_redo() {
7577 let mut p = three();
7578 assert!(p.delete(1));
7579 assert!(p.undo());
7580 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
7581 assert!(p.split(1), "a fresh edit");
7582 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
7583 assert!(!p.redo(), "so redo has nothing left");
7584 }
7585
7586 #[test]
7587 fn redo_on_empty_stack_is_false() {
7588 let mut p = three();
7589 assert!(!p.redo(), "nothing has been undone yet");
7590 }
7591
7592 /// Past the cap the *oldest* step goes, so a long session undoes exactly
7593 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
7594 #[test]
7595 fn history_stops_at_the_cap() {
7596 let mut p = Project::single(FILE, 400);
7597 for frame in 1..=150 {
7598 assert!(p.split(frame), "split {frame} is an edit");
7599 }
7600 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
7601 for step in 0..HISTORY_CAP {
7602 assert!(p.undo(), "undo {step} is inside the cap");
7603 }
7604 assert!(!p.undo(), "and the 101st has nothing left to take");
7605 // 100 undos off 150 splits is the timeline after the 50th: the older
7606 // steps were dropped, not the newer ones.
7607 assert_eq!(p.clips().len(), 51);
7608 }
7609
7610 /// Undo/redo by hand across a split must never merge two takes into one
7611 /// group by reusing an id.
7612 #[test]
7613 fn group_ids_are_never_reused() {
7614 let mut p = Project::single(FILE, 9);
7615 assert!(p.split(3));
7616 let first = p.clips()[1].link;
7617 assert!(p.undo());
7618 assert!(p.split(5));
7619 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
7620 }
7621
7622 #[test]
7623 fn segments_from_reads_the_audio_lane() {
7624 let p = three();
7625 // mid-clip: partial first segment, whole clips after it
7626 assert_eq!(
7627 p.segments_from(4, FPS),
7628 vec![
7629 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7630 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7631 ]
7632 );
7633 // on a boundary: nothing partial
7634 assert_eq!(
7635 p.segments_from(3, FPS),
7636 vec![
7637 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
7638 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
7639 ]
7640 );
7641 // from the top: one entry per clip
7642 assert_eq!(p.segments_from(0, FPS).len(), 3);
7643 // last clip only
7644 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
7645 // past the end / unusable fps
7646 assert!(p.segments_from(9, FPS).is_empty());
7647 assert!(p.segments_from(0, 0.0).is_empty());
7648 assert!(p.segments_from(0, f64::NAN).is_empty());
7649 }
7650
7651 #[test]
7652 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
7653 let mut p = three();
7654 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
7655 assert_eq!(
7656 p.segments_from(0, FPS),
7657 vec![
7658 (Some(0), 0.0, 3.0 / 30.0),
7659 (None, 0.0, 2.0 / 30.0),
7660 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7661 ]
7662 );
7663 // The list still covers exactly the timeline: that is what stops the
7664 // master clock stalling at the hole.
7665 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7666 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
7667 // Starting inside the gap trims the silence, not the clip after it.
7668 assert_eq!(
7669 p.segments_from(4, FPS),
7670 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
7671 );
7672 // ...and a lane that is nothing but gap is a run of silence.
7673 assert!(p.lift(Lane::A1, 0));
7674 assert!(p.lift(Lane::A1, 0));
7675 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
7676 }
7677
7678 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
7679 /// of source 0 then [0,4) of source 1.
7680 fn two_sources() -> Project {
7681 let mut p = three();
7682 let s = p.import(FILE2, 0);
7683 assert_eq!(s, 1);
7684 assert!(p.append_clip(s, 4));
7685 p
7686 }
7687
7688 #[test]
7689 fn import_dedups_and_appends() {
7690 let mut p = Project::single(FILE, 9);
7691 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
7692 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
7693 assert_eq!(p.import(FILE2, 0), 1);
7694 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
7695 // ...but the same file on another audio stream is another source: it is
7696 // what a clip names, and a clip plays exactly one stream.
7697 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
7698 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
7699 assert_eq!(p.sources()[2].audio_stream, 1);
7700 assert!(p.append_clip(2, 4), "a stream entry is placeable");
7701 assert!(p.undo());
7702 assert_eq!(p.sources().len(), 3);
7703 assert!(!p.append_clip(3, 5), "unknown source index");
7704 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
7705
7706 // Two spellings of one real file are one source: this is the case the
7707 // raw-path comparison above would get wrong.
7708 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
7709 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
7710 let mut p = Project::single(here, 9);
7711 assert_eq!(p.import(detour, 0), 0);
7712 assert_eq!(p.sources().len(), 1);
7713 }
7714
7715 #[test]
7716 fn append_clip_is_one_undo_step() {
7717 let mut p = two_sources();
7718 assert_eq!(p.timeline_frames(), 13);
7719 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
7720 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
7721 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
7722 assert!(p.undo());
7723 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
7724 assert_eq!(
7725 p.sources().len(),
7726 2,
7727 "the orphan source entry stays -- indexes are forever"
7728 );
7729 // ...and it is still usable, so a redo-by-hand costs no reimport.
7730 assert!(p.append_clip(1, 0));
7731 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
7732 }
7733
7734 #[test]
7735 fn edits_carry_the_source_along() {
7736 let mut p = two_sources();
7737 // A split inside the second source splits into two source-1 clips.
7738 assert!(p.split(11));
7739 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
7740 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
7741
7742 // A source-1 clip pasted into source-0 territory keeps its file, and so
7743 // does the source-0 half that got split off around it.
7744 let copied = p.clips()[4];
7745 assert!(p.paste(1, copied));
7746 assert_eq!(p.clips()[1].source, 1);
7747 assert_eq!(p.clips()[1].in_frame, 2);
7748 assert_eq!(p.clips()[2].source, 0);
7749 assert!(p.undo());
7750 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
7751 }
7752
7753 #[test]
7754 fn segments_from_names_the_source() {
7755 let p = two_sources();
7756 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
7757 assert_eq!(
7758 p.segments_from(4, FPS),
7759 vec![
7760 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
7761 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
7762 (Some(1), 0.0, 4.0 / 30.0),
7763 ]
7764 );
7765 // Mid-clip in source 1: only that source is left.
7766 assert_eq!(
7767 p.segments_from(10, FPS),
7768 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
7769 );
7770 assert!(p.segments_from(13, FPS).is_empty());
7771 // Segments still cover exactly the timeline across the join.
7772 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
7773 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
7774 }
7775
7776 #[test]
7777 fn segments_follow_deletes_and_fps() {
7778 let mut p = three();
7779 assert!(p.delete(0));
7780 // source seconds, not timeline: deleting the head does not shift them
7781 let segs = p.segments_from(0, 25.0);
7782 assert_eq!(
7783 segs,
7784 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
7785 );
7786 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
7787 assert!(
7788 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
7789 "segments must cover exactly the timeline: {played}"
7790 );
7791 }
7792
7793 #[test]
7794 fn orphan_sources_are_pruned_and_the_clips_reindexed() {
7795 // Import a second file, undo it: source 1 is now an orphan.
7796 let mut p = two_sources();
7797 assert!(p.undo());
7798 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7799 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
7800 assert!(eq.is_empty(), "and a project with no equalizer writes none");
7801 assert!(color.is_empty(), "nor a colour it never graded with");
7802 assert_eq!(
7803 lanes,
7804 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
7805 "the clips are untouched"
7806 );
7807
7808 // Three sources where only the middle one is orphaned: the survivors
7809 // renumber, and the clips follow.
7810 let mut p = Project::single(FILE, 9);
7811 assert_eq!(p.import(FILE2, 0), 1);
7812 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
7813 assert!(p.append_clip(2, 4));
7814 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7815 assert_eq!(
7816 sources,
7817 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
7818 );
7819 assert_eq!(
7820 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
7821 [0, 1]
7822 );
7823 // ...and what comes out is loadable, with the same timeline.
7824 let reloaded = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
7825 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
7826 assert_eq!(reloaded.sources().len(), 2);
7827 }
7828
7829 /// Taking a file out of the library: refused by name -- lanes and counts --
7830 /// while a clip still plays from it, and once nothing does, the entry goes
7831 /// and every clip that indexed past it is renumbered onto the short list.
7832 #[test]
7833 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
7834 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
7835 // plus a second stream of FILE as source 2 with a take of its own.
7836 let mut p = two_sources();
7837 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
7838 assert!(p.append_clip(2, 4));
7839
7840 let refusal = p
7841 .remove_source(1)
7842 .expect_err("a source with clips on it cannot go")
7843 .to_string();
7844 assert!(refusal.contains(FILE2), "names the file: {refusal}");
7845 assert!(
7846 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
7847 "names the lanes holding it: {refusal}"
7848 );
7849 assert!(refusal.contains("still plays"), "{refusal}");
7850 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
7851 assert_eq!(shape(&p)[0][3].source, 1);
7852
7853 // Delete FILE2's take -- the whole span, on every lane -- and the entry
7854 // is free to go. Source 2's clips become source 1's.
7855 assert!(p.delete_in(Lane::V1, 3));
7856 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
7857 p.remove_source(1).expect("nothing plays FILE2 any more");
7858 assert_eq!(
7859 p.sources(),
7860 [Source::new(FILE, 0), Source::new(FILE, 1)],
7861 "the middle entry is gone"
7862 );
7863 assert_eq!(
7864 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
7865 [0, 0, 0, 1],
7866 "the clips past it renumbered"
7867 );
7868 assert_eq!(
7869 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
7870 [0, 0, 0, 1],
7871 "on every lane"
7872 );
7873 // What is left is a project that still loads, which is the whole point
7874 // of renumbering rather than leaving a hole.
7875 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
7876 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
7877 }
7878
7879 /// The two edges of a removal: it retires the undo stack (the corner-cut on
7880 /// [`Project::remove_source`]), and the last entry goes like any other
7881 /// once nothing plays it -- a project may name no file at all.
7882 #[test]
7883 fn remove_source_retires_undo_and_empties_the_library() {
7884 let mut p = two_sources();
7885 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
7886 assert!(!p.history.is_empty(), "there is something to undo");
7887 p.remove_source(1).expect("nothing plays FILE2");
7888 assert!(
7889 p.history.is_empty(),
7890 "a snapshot naming the removed source must not survive it"
7891 );
7892 assert!(!p.undo(), "and so there is nothing left to undo");
7893
7894 // The last file standing is held to the one rule every row is -- what
7895 // plays cannot go -- and to no other.
7896 assert_eq!(p.sources().len(), 1);
7897 let refusal = p
7898 .remove_source(0)
7899 .expect_err("its clips are still on the lanes")
7900 .to_string();
7901 assert!(refusal.contains("still plays"), "{refusal}");
7902 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
7903 while p.delete_in(Lane::V1, 0) {}
7904 p.remove_source(0)
7905 .expect("the last row goes like any other");
7906 assert!(
7907 p.sources().is_empty(),
7908 "a project may name no file at all: an empty library over an empty timeline"
7909 );
7910 assert_eq!(p.timeline_frames(), 0);
7911 assert!(
7912 p.remove_source(0).is_err(),
7913 "and an index that is not there is refused, not panicked on"
7914 );
7915 }
7916
7917 /// A clip's equalizer is the clip's: it survives every edit that copies a
7918 /// placement, and it comes back with an undo.
7919 #[test]
7920 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
7921 let mut p = three();
7922 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
7923 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
7924 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7925 assert!(
7926 p.eq_of(Lane::V1, 0).is_none(),
7927 "one clip, not the lane above"
7928 );
7929
7930 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
7931 assert!(p.split(1));
7932 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7933 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
7934 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
7935
7936 // A clipboard copy carries it -- onto another lane, at that.
7937 let copied = p.lane(Lane::A1)[1];
7938 assert!(p.place(Lane::V1, 20, copied));
7939 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
7940 assert!(p.undo());
7941 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
7942
7943 // ...and a change to one is one undo step, in both directions.
7944 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
7945 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
7946 assert!(p.undo());
7947 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7948 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
7949 assert!(p.eq_of(Lane::A1, 0).is_none());
7950 assert!(p.undo());
7951 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7952
7953 // Two refusals, neither of which costs an undo step.
7954 let mut nan = band_at(1);
7955 nan.bands[0].q = f32::INFINITY;
7956 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
7957 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
7958 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
7959 assert!(p.undo());
7960 assert_eq!(
7961 p.lane(Lane::A1).len(),
7962 3,
7963 "one step back is before the split"
7964 );
7965 assert!(p.undo());
7966 assert!(
7967 p.eq_of(Lane::A1, 0).is_none(),
7968 "and the next is before the setting: the refusals pushed none"
7969 );
7970 }
7971
7972 /// The table is append-only within a session, exactly as the sources are, so
7973 /// an undone setting is still in it -- and a save is where it goes.
7974 #[test]
7975 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
7976 let mut p = three();
7977 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
7978 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
7979 assert!(p.undo(), "back to the first setting");
7980 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
7981
7982 let (_, lanes, eq, _, _) = p.without_orphan_sources();
7983 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
7984 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
7985 assert_eq!(lanes[0].1[1].eq, None);
7986
7987 // One curve on three clips is one entry: settings that are equal share.
7988 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
7989 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
7990 let (_, lanes, eq, _, _) = p.without_orphan_sources();
7991 assert_eq!(eq.len(), 1, "equal settings share their entry");
7992 assert_eq!(lanes[1].1[2].eq, Some(0));
7993 reloads(&p, "an equalizer that outlived an undo");
7994 }
7995
7996 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
7997 /// grade is the clip's, through every edit that copies a placement.
7998 #[test]
7999 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
8000 let mut p = three();
8001 assert!(
8002 p.color_of(Lane::V1, 0).is_none(),
8003 "a fresh clip is ungraded"
8004 );
8005 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8006 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8007 assert!(
8008 p.color_of(Lane::A1, 0).is_none(),
8009 "one clip, not the lane below"
8010 );
8011 assert!(
8012 p.eq_of(Lane::V1, 0).is_none(),
8013 "and a grade is not an equalizer"
8014 );
8015
8016 // Cutting a graded clip must not grade half of it: both halves inherit.
8017 assert!(p.split(1));
8018 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8019 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
8020 assert!(
8021 p.color_of(Lane::V1, 2).is_none(),
8022 "the clip after it is ungraded"
8023 );
8024
8025 // A clipboard copy carries it -- onto another lane, at that.
8026 let copied = p.lane(Lane::V1)[1];
8027 assert!(p.place(Lane::A1, 20, copied));
8028 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
8029 assert!(p.undo());
8030 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8031
8032 // ...and a change to one is one undo step, in both directions.
8033 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
8034 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
8035 assert!(p.undo());
8036 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8037 assert!(
8038 p.set_color(Lane::V1, 0, None),
8039 "and taking it off is an edit"
8040 );
8041 assert!(p.color_of(Lane::V1, 0).is_none());
8042 assert!(p.undo());
8043 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8044
8045 // Two refusals, neither of which costs an undo step.
8046 let nan = ColorParams {
8047 contrast: f32::NAN,
8048 ..grade_at(1)
8049 };
8050 assert!(
8051 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
8052 "no clip there"
8053 );
8054 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
8055 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
8056 assert!(p.undo());
8057 assert_eq!(
8058 p.lane(Lane::V1).len(),
8059 3,
8060 "one step back is before the split"
8061 );
8062 assert!(p.undo());
8063 assert!(
8064 p.color_of(Lane::V1, 0).is_none(),
8065 "and the next is before the grade: the refusals pushed none"
8066 );
8067 }
8068
8069 /// A slider drag is one gesture: the press snapshots, every sample after it
8070 /// only regrades, and the single undo lands on what the clip was *before*
8071 /// the hand touched it -- not one step back down the drag.
8072 #[test]
8073 fn a_whole_colour_drag_undoes_in_one_step() {
8074 let mut p = three();
8075 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
8076 for n in 2..=8 {
8077 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
8078 }
8079 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
8080 assert!(p.undo());
8081 assert!(
8082 p.color_of(Lane::V1, 0).is_none(),
8083 "one undo is the whole gesture, back to ungraded"
8084 );
8085
8086 // The live write refuses what the snapshotting one refuses, and a
8087 // refusal still costs no history either way.
8088 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
8089 assert!(!p.set_color_live(
8090 Lane::V1,
8091 0,
8092 Some(ColorParams {
8093 contrast: f32::NAN,
8094 ..grade_at(1)
8095 })
8096 ));
8097 assert!(p.undo());
8098 assert_eq!(
8099 p.lane(Lane::V1).len(),
8100 2,
8101 "the next step back is the split before the drag: no sample pushed one"
8102 );
8103 }
8104
8105 /// The colour table is append-only within a session, exactly as the eq one
8106 /// is -- and a save is where an undone grade goes.
8107 #[test]
8108 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
8109 let mut p = three();
8110 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
8111 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
8112 assert!(p.undo(), "back to the first grade");
8113 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
8114
8115 let (_, lanes, _, color, _) = p.without_orphan_sources();
8116 assert_eq!(
8117 color,
8118 vec![grade_at(1)],
8119 "what nothing plays is not written"
8120 );
8121 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
8122 assert_eq!(lanes[0].1[1].color, None);
8123
8124 // One grade on three clips is one entry: settings that are equal share.
8125 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
8126 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
8127 let (_, lanes, _, color, _) = p.without_orphan_sources();
8128 assert_eq!(color.len(), 1, "equal grades share their entry");
8129 assert_eq!(lanes[1].1[2].color, Some(0));
8130 reloads(&p, "a colour that outlived an undo");
8131
8132 // An equalizer and a grade on one clip are two independent tables.
8133 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
8134 let (_, lanes, eq, color, _) = p.without_orphan_sources();
8135 assert_eq!((eq.len(), color.len()), (1, 1));
8136 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
8137 }
8138
8139 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
8140 /// placement is the clip's, through every edit that copies one.
8141 #[test]
8142 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
8143 let mut p = three();
8144 assert!(
8145 p.transform_of(Lane::V1, 0).is_none(),
8146 "a fresh clip is untransformed"
8147 );
8148 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8149 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8150 assert!(
8151 p.transform_of(Lane::A1, 0).is_none(),
8152 "one clip, not the lane below"
8153 );
8154 assert!(
8155 p.color_of(Lane::V1, 0).is_none(),
8156 "and a placement is not a grade"
8157 );
8158
8159 // Cutting a transformed clip must not transform half of it: both
8160 // halves inherit.
8161 assert!(p.split(1));
8162 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8163 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
8164 assert!(
8165 p.transform_of(Lane::V1, 2).is_none(),
8166 "the clip after it is untransformed"
8167 );
8168
8169 // A clipboard copy carries it -- onto another lane, at that.
8170 let copied = p.lane(Lane::V1)[1];
8171 assert!(p.place(Lane::A1, 20, copied));
8172 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
8173 assert!(p.undo());
8174 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
8175
8176 // ...and a change to one is one undo step, in both directions.
8177 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
8178 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
8179 assert!(p.undo());
8180 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8181 assert!(
8182 p.set_transform(Lane::V1, 0, None),
8183 "and taking it off is an edit"
8184 );
8185 assert!(p.transform_of(Lane::V1, 0).is_none());
8186 assert!(p.undo());
8187 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8188
8189 // Two refusals, neither of which costs an undo step.
8190 let nan = TransformParams {
8191 scale: f32::NAN,
8192 ..transform_at(1)
8193 };
8194 assert!(
8195 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
8196 "no clip there"
8197 );
8198 assert!(
8199 !p.set_transform(Lane::V1, 0, Some(nan)),
8200 "not a finite value"
8201 );
8202 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
8203 assert!(p.undo());
8204 assert_eq!(
8205 p.lane(Lane::V1).len(),
8206 3,
8207 "one step back is before the split"
8208 );
8209 assert!(p.undo());
8210 assert!(
8211 p.transform_of(Lane::V1, 0).is_none(),
8212 "and the next is before the placement: the refusals pushed none"
8213 );
8214 }
8215
8216 /// The transform table is append-only within a session, exactly as the eq
8217 /// and colour ones are -- and a save is where an undone placement goes.
8218 #[test]
8219 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
8220 let mut p = three();
8221 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
8222 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
8223 assert!(p.undo(), "back to the first placement");
8224 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
8225
8226 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8227 assert_eq!(
8228 transform,
8229 vec![transform_at(1)],
8230 "what nothing plays is not written"
8231 );
8232 assert_eq!(
8233 lanes[0].1[0].transform,
8234 Some(0),
8235 "and the survivor renumbers"
8236 );
8237 assert_eq!(lanes[0].1[1].transform, None);
8238
8239 // One placement on three clips is one entry: settings that are equal
8240 // share.
8241 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
8242 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
8243 let (_, lanes, _, _, transform) = p.without_orphan_sources();
8244 assert_eq!(transform.len(), 1, "equal placements share their entry");
8245 assert_eq!(lanes[1].1[2].transform, Some(0));
8246 reloads(&p, "a transform that outlived an undo");
8247
8248 // A grade and a placement on one clip are two independent tables.
8249 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
8250 let (_, lanes, _, color, transform) = p.without_orphan_sources();
8251 assert_eq!((color.len(), transform.len()), (1, 1));
8252 assert_eq!(
8253 (lanes[0].1[0].color, lanes[0].1[0].transform),
8254 (Some(0), Some(0))
8255 );
8256 }
8257
8258 /// Not a claim about correctness but about cost: a clip is copied on every
8259 /// paste, every undo snapshot and every lane clone, so its size is worth
8260 /// knowing. The eq index fit the padding a `Copy` clip already had; the
8261 /// colour one did not, and the struct grew a word. The transform index is
8262 /// a third `Option<u16>`, and it fits the padding the fit policy and the
8263 /// transition byte already left behind, so the struct did not grow again.
8264 #[test]
8265 fn a_clip_is_still_a_small_copy() {
8266 assert_eq!(
8267 std::mem::size_of::<Clip>(),
8268 56,
8269 "Clip changed size -- 32 before the colour index, 40 before the fades, 48 after, 56 with the transition, still 56 with the transform index"
8270 );
8271 }
8272
8273 #[test]
8274 fn from_parts_has_no_history_and_checks_the_invariants() {
8275 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
8276 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
8277 let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone(), Vec::new())
8278 .expect("valid parts");
8279 assert_eq!(p.clips(), three().clips());
8280 assert!(!p.undo(), "a loaded project has nothing to undo");
8281 assert!(p.split(4), "...and is editable from there");
8282 assert!(p.undo());
8283
8284 // A lane may be empty, and so may every lane -- an emptied timeline is a
8285 // project. No lane at all is not one: there would be nothing to place on.
8286 assert!(
8287 Project::from_parts(
8288 sources.clone(),
8289 two(video.clone(), Vec::new()),
8290 Vec::new(),
8291 Vec::new(),
8292 Vec::new(),
8293 )
8294 .is_ok()
8295 );
8296 assert!(
8297 Project::from_parts(
8298 sources.clone(),
8299 two(Vec::new(), Vec::new()),
8300 Vec::new(),
8301 Vec::new(),
8302 Vec::new(),
8303 )
8304 .is_ok()
8305 );
8306 assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new(), Vec::new()).is_err());
8307 let bad: [Vec<Clip>; 5] = [
8308 vec![clip(0, 0, 3, 1)], // source that is not there
8309 vec![clip(0, 3, 3, 0)], // empty clip
8310 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
8311 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
8312 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
8313 ];
8314 for clips in bad {
8315 assert!(
8316 Project::from_parts(
8317 sources.clone(),
8318 two(clips.clone(), Vec::new()),
8319 Vec::new(),
8320 Vec::new(),
8321 Vec::new(),
8322 )
8323 .is_err(),
8324 "{clips:?}"
8325 );
8326 assert!(
8327 Project::from_parts(
8328 sources.clone(),
8329 two(video.clone(), clips.clone()),
8330 Vec::new(),
8331 Vec::new(),
8332 Vec::new(),
8333 )
8334 .is_err()
8335 );
8336 // ...and on a third lane, which is checked by the same walk.
8337 assert!(
8338 Project::from_parts(
8339 sources.clone(),
8340 vec![
8341 (LaneKind::Video, video.clone()),
8342 (LaneKind::Audio, audio.clone()),
8343 (LaneKind::Video, clips),
8344 ],
8345 Vec::new(),
8346 Vec::new(),
8347 Vec::new(),
8348 )
8349 .is_err()
8350 );
8351 }
8352 // An equalizer index no table entry answers, and a table entry the file
8353 // format could not have written, are refused at this door too.
8354 let eqd = |i: u16| {
8355 vec![Clip {
8356 fade_in: 0,
8357 fade_out: 0,
8358 transition_out: 0,
8359 eq: Some(i),
8360 ..video[0]
8361 }]
8362 };
8363 assert!(
8364 Project::from_parts(
8365 sources.clone(),
8366 two(eqd(0), Vec::new()),
8367 Vec::new(),
8368 Vec::new(),
8369 Vec::new(),
8370 )
8371 .is_err()
8372 );
8373 let mut nan = band_at(1);
8374 nan.bands[0].freq_hz = f32::NAN;
8375 assert!(
8376 Project::from_parts(
8377 sources.clone(),
8378 two(eqd(0), Vec::new()),
8379 vec![nan],
8380 Vec::new(),
8381 Vec::new(),
8382 )
8383 .is_err()
8384 );
8385 let loaded = Project::from_parts(
8386 sources.clone(),
8387 two(eqd(0), Vec::new()),
8388 vec![band_at(1)],
8389 Vec::new(),
8390 Vec::new(),
8391 )
8392 .expect("an eq the table holds");
8393 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
8394
8395 // The same two refusals for a colour, at the same door.
8396 let graded = |i: u16| {
8397 vec![Clip {
8398 fade_in: 0,
8399 fade_out: 0,
8400 transition_out: 0,
8401 color: Some(i),
8402 fit: FitPolicy::default(),
8403 speed: Speed::NORMAL,
8404 ..video[0]
8405 }]
8406 };
8407 assert!(
8408 Project::from_parts(
8409 sources.clone(),
8410 two(graded(0), Vec::new()),
8411 Vec::new(),
8412 Vec::new(),
8413 Vec::new(),
8414 )
8415 .is_err(),
8416 "a colour index no entry answers"
8417 );
8418 assert!(
8419 Project::from_parts(
8420 sources.clone(),
8421 two(graded(0), Vec::new()),
8422 Vec::new(),
8423 vec![ColorParams {
8424 tint: f32::NAN,
8425 ..grade_at(1)
8426 }],
8427 Vec::new(),
8428 )
8429 .is_err(),
8430 "a value the file format could not have written"
8431 );
8432 let loaded = Project::from_parts(
8433 sources.clone(),
8434 two(graded(0), Vec::new()),
8435 Vec::new(),
8436 vec![grade_at(1)],
8437 Vec::new(),
8438 )
8439 .expect("a colour the table holds");
8440 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
8441
8442 // Group ids survive a load, and the next split gets a fresh one.
8443 let mut p = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
8444 assert!(p.split(4));
8445 assert!(p.clips().iter().all(|c| c.link.is_some()));
8446 }
8447
8448 /// The grouping rules, at the untrusted door and after every edit that can
8449 /// touch a link. A link id is at most one placement per lane -- a clip or a
8450 /// caption, whichever carries it -- and no sequence of edits may produce
8451 /// otherwise, because what an edit produces is what a save writes and a load
8452 /// reads.
8453 ///
8454 /// Amended for the offset-preserving group: the members keep their own
8455 /// spans, so two placements of one id covering different frames is *legal*
8456 /// -- it is what a hand-built group is -- and the only refusal left is the
8457 /// doubled id inside one lane.
8458 #[test]
8459 fn a_link_id_is_never_two_clips_of_one_lane() {
8460 let sources = vec![Source::new(FILE, 0)];
8461 let linked = |start, in_frame, out_frame, link| Clip {
8462 fade_in: 0,
8463 fade_out: 0,
8464 transition_out: 0,
8465 start,
8466 in_frame,
8467 out_frame,
8468 source: 0,
8469 link: Some(link),
8470 eq: None,
8471 color: None,
8472 transform: None,
8473 fit: FitPolicy::default(),
8474 speed: Speed::NORMAL,
8475 };
8476
8477 // The door: a doubled id inside one lane, refused by name.
8478 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
8479 Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new(), Vec::new())
8480 .expect_err("refused")
8481 .to_string()
8482 };
8483 assert!(
8484 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
8485 .contains("link 7 names two clips in the V1 lane"),
8486 "a duplicate id inside one lane is refused by name"
8487 );
8488 // ...and the same doubling on a subtitle lane, in its own words: a
8489 // caption is the other placement an id may name.
8490 let caption = |start: u32, frames: u32, link| SubClip {
8491 start,
8492 frames,
8493 track: 0,
8494 in_us: 0,
8495 out_us: i64::from(frames) * 1_000_000,
8496 link: Some(link),
8497 };
8498 let subs = LaneData {
8499 clips: Vec::new(),
8500 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
8501 ..LaneData::new(LaneKind::Subtitle, Vec::new())
8502 };
8503 assert_eq!(
8504 links_are_consistent(&[subs]).unwrap_err().to_string(),
8505 "link 7 names two captions in the S1 lane"
8506 );
8507 // A pair covering *different* frames is legal now: the members of a
8508 // hand-built group keep their own spans, and what binds them is the id.
8509 let apart = Project::from_parts(
8510 sources.clone(),
8511 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
8512 Vec::new(),
8513 Vec::new(),
8514 Vec::new(),
8515 );
8516 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
8517 // A one-sided link is *not* an error: it is what a lift leaves behind.
8518 let mut p = Project::single(FILE, 9);
8519 assert!(p.lift(Lane::A1, 0));
8520 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
8521 assert!(
8522 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
8523 "a lifted lane's project has to load again"
8524 );
8525
8526 // The edits: nothing below may break either rule.
8527 let consistent = |p: &Project, what: &str| {
8528 assert!(
8529 links_are_consistent(&p.lanes).is_ok(),
8530 "{what}: {:?}",
8531 p.lanes
8532 );
8533 };
8534 let mut p = three();
8535 let copied = p.clips()[0];
8536 assert!(
8537 copied.link.is_some(),
8538 "the clipboard clip carries its group"
8539 );
8540 assert!(p.lift(Lane::V1, 0));
8541 assert!(p.place(Lane::V1, 0, copied));
8542 assert!(p.place(Lane::V1, 20, copied), "and again, further out");
8543 assert_eq!(
8544 p.clips().iter().filter(|c| c.link == copied.link).count(),
8545 0,
8546 "a placement belongs to no group, so it cannot duplicate one"
8547 );
8548 consistent(&p, "lift + place twice");
8549 assert!(p.place(Lane::A1, 4, copied), "over a linked clip's middle");
8550 consistent(&p, "place through a grouped clip");
8551 assert!(p.paste(6, copied), "a rippling paste through another");
8552 consistent(&p, "paste");
8553 assert!(p.split(2));
8554 consistent(&p, "split");
8555 assert!(p.ripple_delete(1, 3));
8556 consistent(&p, "ripple_delete");
8557 assert!(p.undo());
8558 consistent(&p, "undo");
8559 }
8560
8561 /// What an edit produces is what a save writes, so *every* state the public
8562 /// API can reach has to load again. The two the verifier panel found where
8563 /// it did not: a split and a regroup handed one group id to two clips that
8564 /// were not the same span, because the lanes had been edited apart.
8565 #[test]
8566 fn every_reachable_state_reloads() {
8567 let mut p = Project::single(FILE, 150);
8568 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
8569 assert!(p.split(10), "the lanes are cut apart at 10");
8570 reloads(&p, "place on one lane, then split");
8571
8572 let mut p = Project::single(FILE, 150);
8573 assert!(p.split(30));
8574 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
8575 assert!(p.regroup(30), "only the audio lane can rejoin");
8576 assert!(p.split(60));
8577 reloads(&p, "lift, regroup one lane, split");
8578
8579 // Two audio streams of one file, both placed: two source entries with
8580 // one path between them, which is the state a stream picked out of the
8581 // library reaches -- and the state a save has to write and read back.
8582 let mut p = Project::single(FILE, 150);
8583 let second = p.import(FILE, 1);
8584 assert_eq!(second, 1, "the same file on another stream is a new source");
8585 assert!(p.append_clip(second, 150));
8586 assert!(p.split(200));
8587 reloads(
8588 &p,
8589 "a second audio stream of the same file, placed and split",
8590 );
8591 let (sources, ..) = p.without_orphan_sources();
8592 assert_eq!(
8593 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
8594 [0, 1],
8595 "both entries survive the orphan prune: both are played"
8596 );
8597 }
8598
8599 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
8600 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
8601 /// is the stamp playback puts on a decoded source frame -- and the *last*
8602 /// source frame the pump is still holding at a timeline frame has to be
8603 /// exactly the one the export encoded there, at every rate. Anything else is
8604 /// A/V drift that grows with the clip, and no test of either side alone
8605 /// would see it.
8606 ///
8607 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
8608 /// is a better answer than the floor/floor this had: floor/floor put the
8609 /// preview a whole held frame off the export at slow rates.)
8610 #[test]
8611 fn speed_maps_both_ways() {
8612 for permille in (250..=4000).step_by(1) {
8613 let speed = Speed::from_permille(permille);
8614 assert_eq!(speed.permille(), permille, "no clamping in range");
8615 for d in 0..200u32 {
8616 let want = speed.source_at(d);
8617 // What the pump shows at `d` is the last frame whose stamp has
8618 // come due -- and it is `want`, the frame the export encodes
8619 // there. Slowed, that is the frame it is still holding; sped up,
8620 // it is the newest of the several that arrived.
8621 let held = (0..=want + 8)
8622 .filter(|&s| speed.timeline_at(s) <= d)
8623 .next_back();
8624 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
8625 }
8626 for n in 1..300u32 {
8627 // A footprint is never zero: a clip occupying no timeline frame
8628 // is a placement the lane invariants cannot hold.
8629 let frames = speed.frames(n);
8630 assert!(frames >= 1, "{speed} of {n} frames");
8631 // ...and its last timeline frame never reads past the clip.
8632 assert!(
8633 speed.source_at(frames - 1) < n,
8634 "{speed}: the last timeline frame of {n} reads past the clip"
8635 );
8636 // The trim inverse never overshoots the room it was given, and
8637 // answers for every room a footprint can be.
8638 let fit = speed.fit(frames).expect("a clip fits its own footprint");
8639 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
8640 // A room narrower than one source frame's own footprint holds
8641 // nothing, and says so rather than rounding something into it.
8642 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
8643 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
8644 }
8645 }
8646 // Real time is the identity map, byte for byte.
8647 for d in 0..1000 {
8648 assert_eq!(Speed::NORMAL.source_at(d), d);
8649 assert_eq!(Speed::NORMAL.timeline_at(d), d);
8650 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
8651 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
8652 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
8653 }
8654 // The one door: no zero, no reverse, nothing past the ends.
8655 assert_eq!(Speed::from_permille(0), Speed::MIN);
8656 assert_eq!(Speed::from_permille(249), Speed::MIN);
8657 assert_eq!(Speed::from_permille(4001), Speed::MAX);
8658 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
8659 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
8660 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
8661 }
8662
8663 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
8664 /// export encodes at a timeline frame is the one playback is holding there,
8665 /// a file is as long in timeline frames as the seconds it lasts, and the two
8666 /// compose so a speeded clip at another rate is exactly both.
8667 #[test]
8668 fn rate_composes_with_speed() {
8669 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
8670 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
8671 // the identity map or a single-rate project would move.
8672 for (source_fps, timeline_fps) in [
8673 (24000. / 1001., 30.),
8674 (30., 24000. / 1001.),
8675 (60., 30.),
8676 (25., 30.),
8677 (30., 30.),
8678 ] {
8679 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
8680 for n in 0..2000u32 {
8681 let source = rate.source_at(n);
8682 // The stamp is the *first* timeline-rate frame that shows it, so
8683 // the picture on screen at `n` is the picture encoded at `n`.
8684 let held = (0..=source + 4)
8685 .filter(|&s| rate.timeline_at(s) <= n)
8686 .next_back();
8687 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
8688 }
8689 // A file of `count` frames is `timeline_at(count)` frames long here,
8690 // and its last one still reads a frame the file has.
8691 for count in 1..500u32 {
8692 let frames = rate.timeline_at(count);
8693 assert!(frames >= 1, "a file is never zero frames long");
8694 assert!(
8695 rate.source_at(frames - 1) < count,
8696 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
8697 );
8698 }
8699 // No drift: the mapping is one exact division of the *rate itself*,
8700 // not an accumulation and not a rounded rate, so an hour in is as
8701 // true as the first second. (Held to the real ratio of the two rates
8702 // the caller asked for -- `as_f64` would be true of a wrong rate.)
8703 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
8704 let want = f64::from(n) * source_fps / timeline_fps;
8705 assert!(
8706 (f64::from(rate.source_at(n)) - want).abs() < 1.,
8707 "{source_fps} on {timeline_fps}: frame {n} drifted"
8708 );
8709 }
8710 }
8711 // The timeline's own rate is the identity, whichever way it is written.
8712 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
8713 assert!(
8714 Rate::from_fps(30.0004, 30.)
8715 .expect("30.0004 over 30")
8716 .is_real_time(),
8717 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
8718 );
8719 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
8720 // one thing `matches_timeline` refuses a file for now that the rate gate
8721 // is gone.
8722 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
8723 assert!(Rate::from_fps(30., f64::NAN).is_err());
8724 for n in 0..1000 {
8725 assert_eq!(Rate::REAL_TIME.source_at(n), n);
8726 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
8727 }
8728 // ...and the composition, in the order the decoder's door applies it:
8729 // the speed picks the clip's (timeline-rate) frame, the rate picks the
8730 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
8731 // timeline frames per frame shown, each of them exactly 800/1001 of a
8732 // file frame.
8733 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
8734 let speed = Speed::from_permille(2000);
8735 for d in 0..100u32 {
8736 assert_eq!(
8737 rate.source_at(speed.source_at(d)),
8738 (u64::from(d) * 2 * 800 / 1001) as u32,
8739 "2x of a 23.976 fps file at timeline frame {d}"
8740 );
8741 }
8742 }
8743
8744 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
8745 /// source frames per timeline frame and still starts at its own in-point,
8746 /// and a half-speed one shows every source frame twice.
8747 #[test]
8748 fn a_rate_maps_timeline_frames_onto_source_frames() {
8749 let mut p = Project::single(FILE, 40);
8750 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8751 .expect("room enough");
8752 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
8753 assert_eq!(
8754 p.map(Lane::V1, 0),
8755 Some((0, 0)),
8756 "and it starts where it did"
8757 );
8758 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
8759 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
8760 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
8761 // The span a decoder is handed: as many source frames as it will read,
8762 // which is the last shown frame's own and not one more -- timeline frame
8763 // 19 shows source frame 38, so 39 frames are read and the 40th is a
8764 // picture nothing would display.
8765 let span = p.span_at(Lane::V1, 0).expect("a span");
8766 assert_eq!((span.len, span.source_len()), (20, 39));
8767 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
8768 // ...and the same clip the other way round.
8769 let mut p = Project::single(FILE, 40);
8770 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8771 .expect("room enough");
8772 assert_eq!(p.timeline_frames(), 80);
8773 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
8774 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
8775 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
8776 assert_eq!(
8777 p.map(Lane::V1, 79),
8778 Some((0, 39)),
8779 "and the last timeline frame is still inside the source range"
8780 );
8781 }
8782
8783 /// A trim of a speeded clip is still a trim of its *source*, and the edge
8784 /// still stops at the wall: the room a rate leaves is measured in timeline
8785 /// frames and the range it commits in source ones.
8786 #[test]
8787 fn trimming_a_speeded_clip_stays_inside_its_room() {
8788 let mut p = Project::single(FILE, 40);
8789 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
8790 .expect("room enough");
8791 // A second clip butted against the first, so the wall is a real one.
8792 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
8793 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
8794 assert_eq!(room, (1, 20), "out to the neighbour and no further");
8795 assert!(
8796 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
8797 "clamped to the wall, which is where the edge already is"
8798 );
8799 let c = p.clips()[0];
8800 assert_eq!(c.end(), 20, "so nothing moved");
8801 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
8802 // ...and in: half the timeline frames is half the source range.
8803 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
8804 let c = p.clips()[0];
8805 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
8806 assert_eq!(c.end(), 10, "and ten timeline frames of them");
8807 assert!(sorted_disjoint(p.clips()));
8808 }
8809
8810 /// The frames a rate cannot address: at half speed each source frame is on
8811 /// screen twice, and the cut between the two showings is not a cut in the
8812 /// file. Refused, so the two halves always add up to the clip that was cut.
8813 #[test]
8814 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
8815 let mut p = Project::single(FILE, 10);
8816 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
8817 .expect("room enough");
8818 assert_eq!(p.timeline_frames(), 20);
8819 assert!(
8820 !p.split(3),
8821 "an odd frame is between two showings of one frame"
8822 );
8823 assert_eq!(p.clips().len(), 1, "and nothing was cut");
8824 assert!(p.split(4), "an even one is a frame boundary");
8825 let halves = p.clips().to_vec();
8826 assert_eq!(
8827 (halves[0].end(), halves[1].start, halves[1].end()),
8828 (4, 4, 20),
8829 "the halves meet, and still end where the clip did"
8830 );
8831 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
8832 assert!(p.regroup(4), "and the inverse puts it back");
8833 assert_eq!(p.clips().len(), 1);
8834 }
8835
8836 /// The same claim, swept: random op sequences off the public surface, the
8837 /// project reloaded after every one of them. A failure prints its seed, and
8838 /// the seed replays the whole sequence.
8839 #[test]
8840 fn random_edit_sequences_reload() {
8841 // Two thousand, not two hundred: the overlap a hole punched into a slow
8842 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
8843 // sequences, and a 200-seed sweep walked straight past it (it took a
8844 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
8845 // has no business being the narrow one.
8846 for seed in 0..2000u64 {
8847 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
8848 let mut next = move |n: u32| {
8849 // xorshift64*: no dependency, and the seed replays it exactly.
8850 rng ^= rng << 13;
8851 rng ^= rng >> 7;
8852 rng ^= rng << 17;
8853 (rng >> 33) as u32 % n
8854 };
8855 let mut p = Project::single(FILE, 40);
8856 for step in 0..24 {
8857 let frame = next(44);
8858 // A clipboard copy carries the group id of the take it came from
8859 // -- the input that made a placement duplicate an id -- and, one
8860 // time in three, a rate of its own: a *speeded clip placed over
8861 // a speeded clip* is the shape whose remainders have to be run
8862 // through `Speed::fit`, and it is not a shape the lanes hand out
8863 // on their own often enough to be sure of.
8864 let mut copied = *p
8865 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
8866 .get(next(4) as usize)
8867 .unwrap_or(&clip(0, 0, 5, 0));
8868 if next(3) == 0 {
8869 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
8870 }
8871 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
8872 let idx = next(4) as usize;
8873 let _ = match next(16) {
8874 // A clip dragged along its own lane to wherever the pointer
8875 // let it go: the op that moves a placement without changing
8876 // what it plays, so what it may not do is land on top of the
8877 // neighbour it was dragged at.
8878 15 => p.move_clip(lane, idx, lane, frame),
8879 // ...and a second `place`, so a punch lands inside a clip
8880 // far more often than one op in fourteen would put it there.
8881 14 => p.place(lane, frame, copied),
8882 0 => p.split(frame),
8883 1 => p.regroup(frame),
8884 2 => p.lift(lane, idx),
8885 3 => p.place(lane, frame, copied),
8886 4 => p.paste(frame, copied),
8887 5 => p.ripple_delete(frame, next(9)),
8888 6 => p.delete(idx),
8889 7 => p.undo(),
8890 // An equalizer put on and taken off in the mix: what a clip
8891 // carries has to reload with it, and the entries an undo
8892 // orphans must not come back out of the prune.
8893 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
8894 9 => p.set_eq(lane, idx, None),
8895 // ...and a colour grade in the same mix, for the same
8896 // reason: it rides on the clip and its orphans must go.
8897 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
8898 11 => p.set_color(lane, idx, None),
8899 // ...and a rate in with them, which is the one of the three
8900 // that moves *placements*: a clip that grew has to be
8901 // refused rather than overlap, and one that shrank leaves a
8902 // lane that still loads. Both are what `reloads` asks.
8903 12 => p
8904 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
8905 .is_ok(),
8906 _ => p.append_clip(0, 1 + next(9)),
8907 };
8908 reloads(&p, &format!("seed {seed}, step {step}"));
8909 }
8910 }
8911 }
8912
8913 /// The save/load round trip a project must survive: the parts a save writes,
8914 /// handed back to the constructor a load goes through -- every lane of them,
8915 /// and the reloaded timeline has to be the same lanes in the same order.
8916 fn reloads(p: &Project, what: &str) {
8917 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
8918 match Project::from_parts(sources, lanes, eq, color, transform) {
8919 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
8920 Ok(back) => {
8921 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
8922 // Placements, not whole clips: an orphan prune renumbers the
8923 // sources a clip names, which is the point of it.
8924 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
8925 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
8926 };
8927 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
8928 // The prune renumbers the eq table too, so what has to survive
8929 // is the settings themselves, clip by clip.
8930 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
8931 p.lanes()
8932 .into_iter()
8933 .map(|l| {
8934 (0..p.lane(l).len())
8935 .map(|i| p.eq_of(l, i).cloned())
8936 .collect()
8937 })
8938 .collect()
8939 };
8940 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
8941 // The colour table renumbers in the same prune, so the same
8942 // claim: the params a clip names, not the index it names them by.
8943 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
8944 p.lanes()
8945 .into_iter()
8946 .map(|l| {
8947 (0..p.lane(l).len())
8948 .map(|i| p.color_of(l, i).copied())
8949 .collect()
8950 })
8951 .collect()
8952 };
8953 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
8954 // ...and the transform table, by the same claim again.
8955 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
8956 p.lanes()
8957 .into_iter()
8958 .map(|l| {
8959 (0..p.lane(l).len())
8960 .map(|i| p.transform_of(l, i).copied())
8961 .collect()
8962 })
8963 .collect()
8964 };
8965 assert_eq!(
8966 transforms(&back),
8967 transforms(p),
8968 "{what}: the transforms changed"
8969 );
8970 }
8971 }
8972 }
8973
8974 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
8975 /// -- each one sorted and disjoint, and one span per group id -- asserted
8976 /// directly, where the point is the invariant rather than the round trip.
8977 fn invariants_hold(p: &Project, what: &str) {
8978 for lane in p.lanes() {
8979 assert!(
8980 sorted_disjoint(p.lane(lane)),
8981 "{what}: {} is out of order or overlaps itself: {:?}",
8982 lane.label(),
8983 p.lane(lane)
8984 );
8985 }
8986 if let Err(e) = links_are_consistent(&p.lanes) {
8987 panic!("{what}: {e}\n{:?}", p.lanes);
8988 }
8989 }
8990
8991 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
8992 /// edited without any other lane hearing about it. A handle naming a lane
8993 /// that is not there reads as empty and refuses to mutate.
8994 #[test]
8995 fn a_third_lane_is_a_peer() {
8996 let mut p = three();
8997 assert_eq!(p.lane_count(LaneKind::Video), 1);
8998 assert_eq!(p.lane_count(LaneKind::Audio), 1);
8999 let v2 = p.add_lane(LaneKind::Video);
9000 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
9001 assert_eq!(v2.label(), "V2");
9002 assert_eq!(p.lane_count(LaneKind::Video), 2);
9003 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9004 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
9005
9006 // A handle for a lane that is not there: empty, and no mutation takes.
9007 let v3 = Lane::new(LaneKind::Video, 2);
9008 assert!(p.lane(v3).is_empty());
9009 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
9010 assert!(!p.lift(v3, 0));
9011 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
9012
9013 // Placing on V2 moves nothing else, and the lane can outrun the rest.
9014 let before = shape(&p);
9015 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9016 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
9017 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
9018 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9019 assert_eq!(
9020 p.timeline_frames(),
9021 16,
9022 "the last lane to end sets the length"
9023 );
9024 assert_eq!(p.map(v2, 5), Some((0, 21)));
9025 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
9026 assert_eq!(
9027 p.span_at(v2, 0),
9028 Some(Span {
9029 start: 0,
9030 len: 4,
9031 from: None,
9032 speed: Speed::NORMAL
9033 })
9034 );
9035 // Every lane still covers the whole timeline, gaps included.
9036 for l in p.lanes() {
9037 let spans = p.spans_from(l, 0);
9038 assert_eq!(
9039 spans.iter().map(|s| s.len).sum::<u32>(),
9040 16,
9041 "{}",
9042 l.label()
9043 );
9044 }
9045 // ...and playback still reads V1 and A1, whatever else is there.
9046 assert_eq!(p.clips(), p.lane(Lane::V1));
9047 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
9048 let segments = p.segments_from(0, FPS);
9049 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
9050 assert_eq!(
9051 segments[3],
9052 (None, 0.0, 7.0 / FPS),
9053 "A1 keeps the clock counting over the picture V2 added"
9054 );
9055 invariants_hold(&p, "place on V2");
9056
9057 // A lift is that lane's business too, and the lane list undoes.
9058 assert!(p.lift(v2, 0));
9059 assert!(p.lane(v2).is_empty());
9060 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
9061 assert!(p.undo());
9062 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
9063 assert!(p.undo());
9064 assert!(p.lane(v2).is_empty(), "the placement came off V2");
9065 assert!(p.undo(), "and one more step takes the lane itself back");
9066 assert_eq!(p.lane_count(LaneKind::Video), 1);
9067 assert_eq!(shape(&p), shape(&three()));
9068 }
9069
9070 /// The add taken back: an empty lane comes off, a lane holding clips never
9071 /// does (and says which clips), the last lane of a kind never does, the
9072 /// lanes below the one that went move up an `ord`, and one undo puts it
9073 /// back where it stood.
9074 #[test]
9075 fn an_empty_lane_comes_off_again() {
9076 let mut p = three();
9077 let v2 = p.add_lane(LaneKind::Video);
9078 let v3 = p.add_lane(LaneKind::Video);
9079 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
9080 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
9081 let history = p.history.len();
9082
9083 // The last lane of its kind stays: `V1`/`A1` are where an import and a
9084 // paste land, and a project missing one would swallow half of a file
9085 // dropped on it.
9086 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
9087 assert_eq!(
9088 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
9089 "there is no V10 to remove"
9090 );
9091
9092 // A lane with clips on it refuses and names them: a track removal never
9093 // deletes a take.
9094 let refusal = why(p.remove_lane(v3));
9095 assert!(refusal.contains("V3 still holds"), "{refusal}");
9096 assert!(refusal.contains(FILE), "{refusal}");
9097 assert!(refusal.contains("at frame 0"), "{refusal}");
9098 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
9099 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
9100
9101 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
9102 // all.
9103 p.remove_lane(v2).expect("V2 is empty");
9104 assert_eq!(p.lane_count(LaneKind::Video), 2);
9105 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
9106 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
9107 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
9108 invariants_hold(&p, "remove V2");
9109
9110 // ...and one stroke puts the empty lane back above it.
9111 assert!(p.undo());
9112 assert_eq!(p.lane_count(LaneKind::Video), 3);
9113 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
9114 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
9115 }
9116
9117 /// A track dragged to another place in the stack: the whole lane travels --
9118 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
9119 /// a video one, a lane that crosses one of its own kind swaps names with it
9120 /// (and swaps the composite with it), one undo puts the order back, and a
9121 /// save carries it.
9122 #[test]
9123 fn a_track_is_dragged_to_another_place_in_the_stack() {
9124 let mut p = three();
9125 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
9126 let before = shape(&p);
9127 let history = p.history.len();
9128
9129 // A1 over V1: the screen is rearranged and nothing else is. Both keep
9130 // their names -- neither crossed a lane of its own kind -- so every
9131 // handle a front-end holds still names the track it named before.
9132 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
9133 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
9134 assert_eq!(
9135 shape(&p),
9136 vec![before[1].clone(), before[0].clone()],
9137 "each lane's clips travelled with it, and none was remapped"
9138 );
9139 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
9140 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
9141 invariants_hold(&p, "A1 over V1");
9142
9143 // Nothing moves for a lane that is not there, a slot that is not, or a
9144 // lane already standing in the one it was pointed at.
9145 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
9146 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
9147 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
9148 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
9149
9150 // ...and one stroke puts the order back.
9151 assert!(p.undo());
9152 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
9153 assert_eq!(shape(&p), before);
9154
9155 // A second video lane over the first: display order *is* the stack, so
9156 // the last video lane covering a frame is the picture that shows.
9157 let v2 = p.add_lane(LaneKind::Video);
9158 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
9159 let over = shape(&p)[2].clone();
9160 assert_eq!(
9161 p.composite_span_at(0).map(|s| s.len),
9162 Some(5),
9163 "V2's five frames are what frame 0 shows"
9164 );
9165
9166 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
9167 // a position among the lanes of its kind. The picture that wins changes
9168 // with it: the take that was covering is the covered one now.
9169 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
9170 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
9171 assert_eq!(
9172 shape(&p),
9173 vec![over.clone(), before[0].clone(), before[1].clone()],
9174 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
9175 );
9176 assert_eq!(
9177 p.composite_span_at(0).map(|s| s.len),
9178 Some(3),
9179 "the lower video lane wins, and it is the old V1 now"
9180 );
9181 invariants_hold(&p, "V2 over V1");
9182
9183 // A save writes that order and a load takes it back.
9184 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9185 assert_eq!(
9186 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9187 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
9188 );
9189 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
9190 assert_eq!(back.lanes(), p.lanes());
9191 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
9192
9193 assert!(p.undo(), "and the stack goes back to how it stood");
9194 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
9195 }
9196
9197 /// The grouping rule across more than two lanes, under the offset model: a
9198 /// split *keeps* the group on the left halves and hands the right halves of
9199 /// that group one fresh id of their own -- a clip in no group comes out of
9200 /// the cut in none. So a take cut apart is two takes, one per side, and a
9201 /// lane that was never part of it stays out of both.
9202 #[test]
9203 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
9204 let mut p = Project::single(FILE, 9);
9205 let take = p.clips()[0].link.expect("a fresh project is one take");
9206 let v2 = p.add_lane(LaneKind::Video);
9207 assert!(p.place(v2, 0, clip(0, 0, 9, 0)), "a placement joins no group");
9208 assert!(p.split(4));
9209 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
9210 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
9211 };
9212 let (left, right) = (side(&p, 0), side(&p, 1));
9213 // The lanes in order are V1, A1, V2: the take's two keep its id on the
9214 // left, and the placed clip never had one for the cut to keep.
9215 assert_eq!(
9216 left,
9217 vec![Some(take), Some(take), None],
9218 "the left halves keep the take"
9219 );
9220 // ...and the right halves of that take are one fresh group.
9221 assert_eq!(right[0], right[1]);
9222 assert_ne!(right[0], Some(take));
9223 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
9224 invariants_hold(&p, "split across three lanes");
9225
9226 // V2 ends early: the left halves still keep what each clip carried --
9227 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
9228 // shared by exactly the take's lanes.
9229 let mut p = Project::single(FILE, 9);
9230 let v2 = p.add_lane(LaneKind::Video);
9231 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
9232 assert!(p.split(3));
9233 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
9234 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
9235 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
9236 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
9237 invariants_hold(&p, "split where one lane ends early");
9238
9239 // The inverse rejoins each lane into the group its left half kept.
9240 assert!(p.regroup(3));
9241 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
9242 assert_eq!(
9243 p.lane(Lane::V1)[0].link,
9244 Some(take),
9245 "the take's id is back, not a fresh one"
9246 );
9247 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
9248 invariants_hold(&p, "regroup across three lanes");
9249 }
9250
9251 /// A group is one placement per lane, on however many lanes carry the id --
9252 /// not a video/audio pair and not a pairing by `ord` -- and the members may
9253 /// cover whatever frames they cover: the offset between them is what a
9254 /// hand-built group keeps. Lanes built by hand, because the rule is checked
9255 /// at the untrusted door and no edit can produce the one thing it refuses.
9256 #[test]
9257 fn a_group_may_span_any_lane() {
9258 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
9259 let one = |start: u32, end: u32, link| Clip {
9260 fade_in: 0,
9261 fade_out: 0,
9262 transition_out: 0,
9263 start,
9264 in_frame: start,
9265 out_frame: end,
9266 source: 0,
9267 link: Some(link),
9268 eq: None,
9269 color: None,
9270 transform: None,
9271 fit: FitPolicy::default(),
9272 speed: Speed::NORMAL,
9273 };
9274 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
9275 let kinds = [
9276 LaneKind::Video,
9277 LaneKind::Audio,
9278 LaneKind::Video,
9279 LaneKind::Audio,
9280 ];
9281 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
9282 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
9283 };
9284 let take = || vec![one(0, 4, 7)];
9285 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
9286 // The same take on V1 + A2 only, the lanes between it empty: legal, the
9287 // way a lifted half is legal.
9288 let across = build([take(), Vec::new(), Vec::new(), take()]);
9289 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
9290 // ...and so is a group whose members disagree about their spans: the
9291 // offset between them is the hand's business, not the loader's.
9292 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
9293 assert!(
9294 links_are_consistent(&apart).is_ok(),
9295 "[0, 4) on V1 and [2, 6) on A2 are one group"
9296 );
9297 // One id twice in one lane is still that lane's error, by name.
9298 let twice = build([
9299 Vec::new(),
9300 Vec::new(),
9301 vec![one(0, 4, 7), one(4, 8, 7)],
9302 Vec::new(),
9303 ]);
9304 assert_eq!(
9305 links_are_consistent(&twice).unwrap_err().to_string(),
9306 "link 7 names two clips in the V2 lane"
9307 );
9308 }
9309
9310 /// Every lane a save writes comes out, in display order and with its kind --
9311 /// an empty one included, since it is state a front-end shows -- and a
9312 /// two-lane project still writes exactly the parts it always did.
9313 #[test]
9314 fn a_save_writes_every_lane_it_has() {
9315 let mut p = three();
9316 let before = p.without_orphan_sources();
9317 assert_eq!(before.1.len(), 2, "V1 and A1");
9318 let v2 = p.add_lane(LaneKind::Video);
9319 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
9320 let a2 = p.add_lane(LaneKind::Audio);
9321 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
9322 assert_eq!(
9323 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
9324 [
9325 LaneKind::Video,
9326 LaneKind::Audio,
9327 LaneKind::Video,
9328 LaneKind::Audio
9329 ],
9330 "display order, not video-then-audio"
9331 );
9332 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
9333 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
9334 // ...and all four load again as the same four.
9335 let back = Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
9336 assert_eq!(back.lanes(), p.lanes());
9337 assert_eq!(back.lane(a2), p.lane(a2));
9338
9339 // Taking the lanes back leaves exactly what a two-lane save wrote.
9340 for _ in 0..3 {
9341 assert!(p.undo());
9342 }
9343 assert_eq!(
9344 p.without_orphan_sources(),
9345 before,
9346 "byte for byte the same parts a two-lane save always wrote"
9347 );
9348 }
9349
9350 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
9351 /// three lanes and grows more: every lane's own order and the one
9352 /// span-per-id rule after every op, *and* the reload the v4 format restored
9353 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
9354 /// project of any number of lanes.
9355 #[test]
9356 fn random_edit_sequences_keep_many_lanes_consistent() {
9357 for seed in 0..2000u64 {
9358 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
9359 let mut next = move |n: u32| {
9360 rng ^= rng << 13;
9361 rng ^= rng >> 7;
9362 rng ^= rng << 17;
9363 (rng >> 33) as u32 % n
9364 };
9365 let mut p = Project::single(FILE, 40);
9366 let v2 = p.add_lane(LaneKind::Video);
9367 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
9368 let lanes = [Lane::V1, Lane::A1, v2];
9369 for step in 0..24 {
9370 let frame = next(44);
9371 let copied = *p
9372 .lane(lanes[next(3) as usize])
9373 .get(next(4) as usize)
9374 .unwrap_or(&clip(0, 0, 5, 0));
9375 let lane = lanes[next(3) as usize];
9376 let idx = next(4) as usize;
9377 let _ = match next(14) {
9378 // The drag, in the mix: a clip dragged along its own lane
9379 // and onto another one, at a frame the pointer picked --
9380 // which is where the group rule and the sorted+disjoint one
9381 // meet, since every half travels the same distance.
9382 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
9383 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
9384 11 => p.set_eq(lane, idx, None),
9385 // A rate, which on many lanes is the group rule as well:
9386 // every clip carrying the link moves together or none of
9387 // them does, and `invariants_hold` is what says so.
9388 12 => p
9389 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
9390 .is_ok(),
9391 0 => p.split(frame),
9392 1 => p.regroup(frame),
9393 2 => p.lift(lane, idx),
9394 3 => p.place(lane, frame, copied),
9395 4 => p.paste(frame, copied),
9396 5 => p.ripple_delete(frame, next(9)),
9397 6 => p.delete(idx),
9398 7 => p.undo(),
9399 8 => {
9400 p.add_lane(if next(2) == 0 {
9401 LaneKind::Video
9402 } else {
9403 LaneKind::Audio
9404 });
9405 true
9406 }
9407 _ => p.append_clip(0, 1 + next(9)),
9408 };
9409 invariants_hold(&p, &format!("seed {seed}, step {step}"));
9410 reloads(&p, &format!("seed {seed}, step {step}"));
9411 }
9412 }
9413 }
9414
9415 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
9416 /// there, `V1` shows again on either side of it, and a frame no video lane
9417 /// covers is a gap however many lanes there are.
9418 #[test]
9419 fn the_composite_is_the_topmost_lane_with_a_clip() {
9420 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9421 let lanes = vec![
9422 // V1: the whole 30 frames of source 0.
9423 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9424 // V2: source 1 over the middle third.
9425 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
9426 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9427 ];
9428 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9429 assert_eq!(
9430 p.composite_spans_from(0),
9431 vec![
9432 Span {
9433 start: 0,
9434 len: 10,
9435 from: Some((0, 0)),
9436 speed: Speed::NORMAL
9437 },
9438 Span {
9439 start: 10,
9440 len: 10,
9441 from: Some((1, 5)),
9442 speed: Speed::NORMAL
9443 },
9444 Span {
9445 start: 20,
9446 len: 10,
9447 from: Some((0, 20)),
9448 speed: Speed::NORMAL
9449 },
9450 ],
9451 "V2 takes over for its own span and hands V1 back"
9452 );
9453 // A mid-span ask resolves the same way, which is what a seek does.
9454 assert_eq!(
9455 p.composite_span_at(15),
9456 Some(Span {
9457 start: 15,
9458 len: 5,
9459 from: Some((1, 10)),
9460 speed: Speed::NORMAL
9461 })
9462 );
9463 assert_eq!(p.composite_span_at(30), None, "past the end");
9464
9465 // A hole in V1 under V2's clip: black between the two, and black after
9466 // both run out (the audio lane is still holding the timeline open).
9467 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9468 let holed = vec![
9469 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
9470 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
9471 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9472 ];
9473 let p = Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
9474 assert_eq!(
9475 p.composite_spans_from(0),
9476 vec![
9477 Span {
9478 start: 0,
9479 len: 5,
9480 from: Some((0, 0)),
9481 speed: Speed::NORMAL
9482 },
9483 Span {
9484 start: 5,
9485 len: 5,
9486 from: None,
9487 speed: Speed::NORMAL
9488 },
9489 Span {
9490 start: 10,
9491 len: 10,
9492 from: Some((1, 0)),
9493 speed: Speed::NORMAL
9494 },
9495 Span {
9496 start: 20,
9497 len: 10,
9498 from: None,
9499 speed: Speed::NORMAL
9500 },
9501 ]
9502 );
9503
9504 // One video lane: the composite *is* that lane, span for span -- the
9505 // promise every existing two-lane project rests on.
9506 let p = Project::single(FILE, 30);
9507 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
9508 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
9509 }
9510
9511 /// Every audio lane holding something gets a play list, and only those.
9512 #[test]
9513 fn audio_segments_cover_every_lane_that_holds_something() {
9514 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
9515 let lanes = vec![
9516 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9517 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
9518 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
9519 (LaneKind::Audio, Vec::new()),
9520 ];
9521 let p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
9522 let lists = p.audio_segments_from(0, FPS);
9523 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
9524 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
9525 // A2 is a gap up to frame 15, then the whole of source 1.
9526 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
9527
9528 // No audio lane holds anything: one all-gap list, so such a timeline
9529 // still plays silence against a master clock.
9530 let p = Project::from_parts(
9531 vec![Source::new(FILE, 0)],
9532 vec![
9533 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
9534 (LaneKind::Audio, Vec::new()),
9535 ],
9536 vec![],
9537 vec![],
9538 Vec::new(),
9539 )
9540 .expect("valid parts");
9541 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
9542 }
9543}