forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

project.rs20722 lines, 906.8 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::duck::Duck;
81use crate::voice::VoiceFx;
82use crate::eq::EqParams;
83use crate::limiter::{Limiter, db_to_linear};
84use crate::scale::FitPolicy;
85use crate::subtitle::{Cue as SubtitleCue, SubtitleTrack};
86
87mod multicam;
88pub use multicam::{AngleSpec, MAX_ANGLES, MulticamMade, MulticamUnder};
89mod sequence;
90pub use sequence::{
91 MAX_SEQUENCES, MAX_SEQUENCE_NAME_CHARS, Nested, RenderView, SEQ_BASE, SequenceInfo, is_sequence_source,
92 sequence_id_of, sequence_source,
93};
94use sequence::{FlatCache, Seqs};
95
96/// The shortest a cue a cut or trim shortened may be on the timeline, in
97/// frames (about 0.15 s at 30 fps). Shorter, and [`Project::sub_lane_cue_refs`]
98/// drops it.
99const CUT_SLIVER_FRAMES: f64 = 4.0;
100use crate::text::{Align, HPlace, Outline, Place, SIZE_RANGE, TextStyle, Weight};
101use crate::titleanim::TitleAnim;
102use crate::color::{ColorKey, MAX_COLOR_KEYS, evaluate_color};
103use crate::transform::{
104 KeyEase, Keyed, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, TransformParams, ease_shape,
105 evaluate as keyed_transform, evaluate_opacity, keys_after_still_head, keys_within,
106 sample,
107};
108
109/// How far down a lane's own volume goes ([`Project::set_lane_gain_db`]).
110/// -60 dB is a thousandth of the amplitude -- a track that is out of the mix
111/// for every purpose but the honest one, which is that it is still a level and
112/// not a mute.
113pub const MIN_GAIN_DB: f32 = -60.0;
114/// ...and how far up. +12 dB is four times the amplitude, which is as much as
115/// a mix bus can take before the limiter is doing all the work.
116pub const MAX_GAIN_DB: f32 = 12.0;
117
118/// The longest `[in_us, out_us)` window a [`SubClip`] may show, in
119/// microseconds: **30 days** of track.
120///
121/// A window is a stretch of *source media*, not of the timeline, so its width
122/// is the length of the recording a caption was cut from -- and that is not
123/// bounded by anything a day. A two-day conference stream, a lecture archive, a
124/// long interview session: all produce a palette row whose `out_us` is tens of
125/// hours, and a ceiling that refuses those refuses the user's own media back at
126/// them. The value is therefore "past any recording", and nothing more
127/// sophisticated: 30 days is a round number four orders of magnitude above the
128/// longest thing anybody captions and three orders below the point where a
129/// typed number becomes plausible as a duration at all.
130///
131/// What it has to clear, concretely, and the honest arithmetic for each:
132///
133/// - **The i64 multiply in [`SubClip::window_at`].** `window_us() * into`,
134/// where `into` is a `u32` frame offset, so at most 4.29e9. It is a
135/// `saturating_mul`, so this is not about safety -- saturation is total --
136/// but about the result still *meaning* something: 30 days x 4.29e9 is
137/// 1.1e22, which does NOT fit an i64. So the multiply saturates for any
138/// window above `i64::MAX / u32::MAX` = 2.1e9 us (~35 minutes), and 30 days
139/// is 1200x past that. The value is then finite but the proportion is not
140/// exact, and `set_window`'s clamp on the answer keeps the result inside the
141/// window rather than trusting it. That is the real precision cost, and it
142/// is why this is not "unlimited": past 35 minutes the cut degrades, past
143/// this it has degraded to "the far end of the window".
144/// - **`sub_lane_cues`'s f64 mapping.** `(t - in_us) as f64 * per`, where `per`
145/// is `frames / fps * 1e6 / window_us`. Here f64 exactness genuinely does
146/// apply: an i64 is exact in f64 to 2^53 = 9.0e15, and 30 days is 2.6e12 --
147/// about 3.5 orders of magnitude inside it, so the cue mapping is exact and
148/// not merely close.
149/// - **Nothing else.** There is no allocation, no index and no length derived
150/// from a window, so a wider value costs no memory. The ceiling is a claim
151/// about meaning, not about resource.
152///
153/// Past it, the value is not a caption any project holds -- a `.edith` a hand
154/// edited (or a hostile actor wrote) reaches this with a line the never-empty
155/// check at the parser cannot see past, because `out_us > in_us` says the
156/// window is *open* and never how wide it is. Every door -- the parse,
157/// [`Project::with_subs`], [`Project::place_sub`] -- refuses such a line by
158/// name, next to every other range check a `.edith` line has to pass. Every
159/// *composer* instead clamps to it through [`set_window`], which is the only
160/// function that writes a window; a trim that ran out of window stops at the
161/// window's end rather than failing, exactly like the frame walls it already
162/// has.
163pub const MAX_WINDOW_US: i64 = 30 * 24 * 60 * 60 * 1_000_000;
164
165/// How fast a clip plays, in **thousandths of real time**: 1000 is the speed it
166/// was shot at, 2000 twice that, 500 half. An integer and not an `f32` for
167/// [`Clip`]'s sake -- a clip is `Copy` *and* `Eq`, a float is neither exactly
168/// comparable nor exactly writable, and `.edith` has to read back the very
169/// number that was set. A thousandth is finer than any card can drag and coarser
170/// than any rounding anyone can hear.
171///
172/// The rate alone: the audio path time-stretches a speeded clip
173/// (`crate::stretch`), so its pitch stays where it was recorded while its
174/// seconds compress or stretch -- the tape effect this used to be is gone.
175/// Nothing here plays backwards -- [`Speed::MIN`] is a quarter speed,
176/// [`Speed::MAX`] four times.
177#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
178pub struct Speed(u16);
179
180/// What [`Project::parts`] hands back: the comparable shape of everything an
181/// edit can change, for the sweep's undo round-trip. Test-only, like every
182/// accessor it exists for: the sweep lives behind `cfg(test)`.
183#[cfg(test)]
184#[derive(Clone, Debug, PartialEq)]
185pub(crate) struct SweepParts(
186 pub(crate) usize,
187 pub(crate) Vec<(LaneKind, Vec<Clip>)>,
188 pub(crate) Vec<Vec<SubClip>>,
189 /// The palette, which the history holds beside the lanes and an undo
190 /// therefore restores ([`Project::undo`]). Left out of this shape, a
191 /// round-trip check passed with the palette restore deleted outright.
192 pub(crate) Vec<SubtitleTrack>,
193 pub(crate) ProjectSettings,
194);
195
196impl Speed {
197 /// Real time -- what every clip is until something says otherwise, and the
198 /// value every path in this engine short-circuits on.
199 pub const NORMAL: Speed = Speed(1000);
200 pub const MIN: Speed = Speed(250);
201 pub const MAX: Speed = Speed(4000);
202
203 /// Clamped into `[MIN, MAX]`, which is what makes a zero (or a reverse)
204 /// unrepresentable rather than merely refused: nothing downstream divides
205 /// by a speed that could be nothing.
206 pub fn from_permille(permille: u16) -> Self {
207 Speed(permille.clamp(Self::MIN.0, Self::MAX.0))
208 }
209
210 pub fn permille(self) -> u16 {
211 self.0
212 }
213
214 pub fn is_normal(self) -> bool {
215 self == Self::NORMAL
216 }
217
218 /// As a multiplier, for the sound worker and for a label.
219 pub fn as_f64(self) -> f64 {
220 f64::from(self.0) / 1000.
221 }
222
223 /// How many *timeline* frames `source` source frames occupy at this rate --
224 /// the clip's footprint. Rounded to the nearest frame and **never zero**: a
225 /// clip that occupied no frames would be an empty placement, which the lane
226 /// invariant forbids and which nothing could ever click on again.
227 pub fn frames(self, source: u32) -> u32 {
228 let n = (u64::from(source) * 1000 + u64::from(self.0) / 2) / u64::from(self.0);
229 n.clamp(1, u64::from(u32::MAX)) as u32
230 }
231
232 /// The mapping itself: which source frame of a clip the `offset`th timeline
233 /// frame of it plays. Floored, so the first timeline frame is the clip's own
234 /// in-point at every rate.
235 pub fn source_at(self, offset: u32) -> u32 {
236 (u64::from(offset) * u64::from(self.0) / 1000).min(u64::from(u32::MAX)) as u32
237 }
238
239 /// Its inverse, for a decoder's frames on their way back out: which timeline
240 /// frame of the clip the `offset`th *source* frame of it lands on.
241 ///
242 /// **Ceil, and that is the whole point of the pair.** Playback stamps every
243 /// decoded frame with this and shows the newest whose stamp has come due, so
244 /// what is on screen at timeline offset `d` is the last source frame with
245 /// `timeline_at(s) <= d` -- and with the floor above and the ceil here that
246 /// frame is exactly [`source_at`](Speed::source_at)`(d)`, the frame an
247 /// export encodes there, at every rate (`speed_maps_both_ways`). Rounding
248 /// the two the same way would put the preview a frame off the export at some
249 /// speeds and a whole held frame off at slow ones -- drift that no test of
250 /// either side alone would catch.
251 pub fn timeline_at(self, offset: u32) -> u32 {
252 (u64::from(offset) * 1000)
253 .div_ceil(u64::from(self.0))
254 .min(u64::from(u32::MAX)) as u32
255 }
256
257 /// The longest source range that still *fits* in `frames` timeline frames at
258 /// this rate -- and `None` when **nothing** does, which at a quarter speed is
259 /// any room narrower than the four timeline frames one source frame occupies.
260 ///
261 /// What a trim commits and what a hole-punch leaves behind: rounding could
262 /// otherwise hand back a range wider than the room, and a clip that outgrew
263 /// its room would overlap its neighbour -- the one thing a lane may never do.
264 /// `None` is not an error, it is "no remainder": the caller drops that piece
265 /// (see [`clear`]) or refuses the edit ([`Project::trim`]). At real time this
266 /// is `frames` itself, so nothing about an unspeeded edit changes.
267 pub fn fit(self, frames: u32) -> Option<u32> {
268 if frames == 0 || self.frames(1) > frames {
269 return None;
270 }
271 // The floored estimate is a step or two off in either direction: `frames`
272 // rounds, so at a slow rate the estimate can sit one short of the longest
273 // range that fits (0.333x: 48 source frames take 144 timeline frames, and
274 // `source_at(144)` is 47), and at a fast one one over. Both walked, so the
275 // answer is the longest range that fits, exactly -- which is what a wall
276 // ([`Project::trim_room`]) promises an edge can reach.
277 let mut src = self.source_at(frames).max(1);
278 while self.frames(src + 1) <= frames {
279 src += 1;
280 }
281 while src > 1 && self.frames(src) > frames {
282 src -= 1;
283 }
284 Some(src)
285 }
286
287 /// How many timeline frames `source` source frames of head (or tail) are
288 /// worth -- what [`Project::trim_room`] measures a wall in. Zero for none of
289 /// them, which is why this is not [`frames`](Speed::frames): a clip is never
290 /// empty, but the room in front of one may well be.
291 pub fn room(self, source: u32) -> u32 {
292 match source {
293 0 => 0,
294 n => self.frames(n),
295 }
296 }
297
298 /// How many timeline frames from `offset` on show the **same** source frame:
299 /// one at real time and faster, more when the clip is slowed. What an export
300 /// encodes without decoding the same picture twice, and the count that makes
301 /// its frame walk exactly as long as the span.
302 pub fn repeats(self, offset: u32, len: u32) -> u32 {
303 let want = self.source_at(offset);
304 (offset..len)
305 .take_while(|&t| self.source_at(t) == want)
306 .count() as u32
307 }
308
309 /// Where in the source a cut `offset` timeline frames into a clip of `len`
310 /// source frames falls -- and `None` when this rate cannot address that
311 /// frame at all.
312 ///
313 /// At half speed a clip of ten source frames is twenty timeline frames long
314 /// and every source frame is on screen twice, so a cut between the two
315 /// showings of one frame is not a cut in the *file*: taking it would leave
316 /// two halves whose lengths no longer add up to the clip that was cut --
317 /// a hole in the lane, or an overlap of the next clip. Refused instead, so
318 /// the model stays exact and the front-end can say why. At real time every
319 /// interior frame answers, which is the path a project without speeds is on.
320 pub fn split_at(self, len: u32, offset: u32) -> Option<u32> {
321 let src = self.source_at(offset);
322 (src > 0
323 && src < len
324 && self.frames(src) == offset
325 && self.frames(len - src) == self.frames(len) - offset)
326 .then_some(src)
327 }
328}
329
330/// Most keys a speed ramp may hold ([`Clip::speed_keys`]). A fixed cap, so that a
331/// [`Span`] carrying a ramp stays `Copy`.
332pub const MAX_SPEED_KEYS: usize = 8;
333
334/// How long a still image is placed for when the project does not say (the 5 s every project had
335/// before v52), and the shortest and longest length a project may set for one.
336pub const STILL_DEFAULT_SECS: f64 = 5.0;
337pub const STILL_MIN_SECS: f64 = 0.5;
338pub const STILL_MAX_SECS: f64 = 600.0;
339
340/// One point of a clip's speed ramp ([`Clip::speed_keys`]): the speed `speed` at
341/// the clip-relative timeline frame `at`. Between points the speed is linear and
342/// it holds before the first and after the last. Speeds are [`Speed`]s, in
343/// thousandths like the constant one, so a ramp reads back exactly as it was set.
344#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
345pub struct SpeedKey {
346 pub at: u32,
347 pub speed: Speed,
348}
349
350/// The source position a speed ramp has carried a clip through by its clip-relative
351/// timeline frame `t`: the integral of the piecewise-linear speed from frame 0 to
352/// `t`, in source frames (fractional). Each segment's integral is the trapezoid of
353/// its two ends, exact for a linear speed, so this is the closed form and needs no
354/// table. `keys` must be sorted by `at` with no two alike (see
355/// [`valid_speed_keys`]); empty keys are real time.
356///
357/// A 1x-to-2x ramp over 60 frames -- keys `(0, 1x), (60, 2x)` -- gives 90 at frame 60.
358pub fn ramp_source_at(keys: &[SpeedKey], t: f64) -> f64 {
359 let Some(first) = keys.first() else {
360 return t.max(0.0);
361 };
362 let t = t.max(0.0);
363 // Held before the first key at its speed.
364 let mut acc = t.min(f64::from(first.at)) * first.speed.as_f64();
365 for w in keys.windows(2) {
366 let (a, b) = (w[0], w[1]);
367 let (ta, tb) = (f64::from(a.at), f64::from(b.at));
368 if t <= ta {
369 return acc;
370 }
371 let (ra, rb) = (a.speed.as_f64(), b.speed.as_f64());
372 let d = t.min(tb) - ta;
373 // The speed at the end of the part walked: linear between the two keys.
374 let rate_there = ra + (rb - ra) * d / (tb - ta);
375 acc += d * (ra + rate_there) / 2.;
376 if t <= tb {
377 return acc;
378 }
379 }
380 // Held after the last key.
381 let last = keys[keys.len() - 1];
382 acc + (t - f64::from(last.at)).max(0.) * last.speed.as_f64()
383}
384
385/// The inverse of [`ramp_source_at`]: the clip-relative timeline frame (fractional) at
386/// which a ramp has carried the clip through `source` source frames. Exact to the
387/// float -- the integral is strictly increasing, so the bisection has one answer.
388/// Empty keys are real time.
389pub fn ramp_timeline_at(keys: &[SpeedKey], source: f64) -> f64 {
390 if keys.is_empty() || source <= 0.0 {
391 return source.max(0.0);
392 }
393 let (mut lo, mut hi) = (0., 4. * source + 1.);
394 for _ in 0..64 {
395 let mid = (lo + hi) / 2.;
396 if ramp_source_at(keys, mid) < source {
397 lo = mid;
398 } else {
399 hi = mid;
400 }
401 }
402 (lo + hi) / 2.
403}
404
405/// Timeline frames a ramped clip of `source` source frames occupies: the clip-relative
406/// frame at which [`ramp_source_at`] reaches `source`, rounded, and never zero. The
407/// ramp's own footprint, the way [`Speed::frames`] is the constant one's.
408///
409/// Solved by bisection: the integral is strictly increasing (every speed is at least
410/// [`Speed::MIN`]), so the answer is unique and the bisection is exact to the float.
411pub fn ramp_frames(keys: &[SpeedKey], source: u32) -> u32 {
412 let target = f64::from(source);
413 // Every speed is at least a quarter, so frame `4 * source` has covered `source`.
414 let (mut lo, mut hi) = (0., 4. * target + 1.);
415 for _ in 0..64 {
416 let mid = (lo + hi) / 2.;
417 if ramp_source_at(keys, mid) < target {
418 lo = mid;
419 } else {
420 hi = mid;
421 }
422 }
423 ((lo + hi) / 2.).round().max(1.) as u32
424}
425
426/// Whether `keys` is a ramp the engine will play: between one and
427/// [`MAX_SPEED_KEYS`] keys, strictly increasing in `at`. The speeds are in range by
428/// construction.
429pub fn valid_speed_keys(keys: &[SpeedKey]) -> bool {
430 (1..=MAX_SPEED_KEYS).contains(&keys.len()) && keys.windows(2).all(|w| w[0].at < w[1].at)
431}
432
433/// A clip's speed ramp as a [`Span`] carries it: the keys in a fixed array (so the
434/// span stays `Copy`) and the clip-relative frame the span starts at, which is what
435/// its own offsets are counted from.
436#[derive(Clone, Copy, PartialEq, Eq, Debug)]
437pub struct SpeedRamp {
438 keys: [SpeedKey; MAX_SPEED_KEYS],
439 len: u8,
440 base: u32,
441}
442
443impl SpeedRamp {
444 /// The ramp `keys` (valid, see [`valid_speed_keys`]) for a span starting `base`
445 /// clip-relative frames into the clip.
446 pub fn new(keys: &[SpeedKey], base: u32) -> Self {
447 let mut arr = [SpeedKey::default(); MAX_SPEED_KEYS];
448 arr[..keys.len()].copy_from_slice(keys);
449 Self {
450 keys: arr,
451 len: keys.len() as u8,
452 base,
453 }
454 }
455
456 fn keys(&self) -> &[SpeedKey] {
457 &self.keys[..usize::from(self.len)]
458 }
459
460 /// The same ramp with every speed multiplied by `by`: what a pitch shift asks of the
461 /// stretch that follows a ramp, which runs `1 / 2^(pitch/12)` times as fast.
462 pub fn scaled(self, by: f64) -> Self {
463 let mut keys = self.keys;
464 for k in &mut keys[..usize::from(self.len)] {
465 k.speed = Speed::from_permille((k.speed.as_f64() * by * 1000.0).round() as u16);
466 }
467 Self { keys, ..self }
468 }
469
470 /// The same ramp for a span that starts `by` timeline frames later on it, which is
471 /// what a cut at the span's head does to where its offsets are counted from.
472 pub fn advanced(self, by: u32) -> Self {
473 Self {
474 base: self.base + by,
475 ..self
476 }
477 }
478
479 /// Source frames from the span's first frame to its `offset`th, as the difference
480 /// of two floored source positions -- so `from + source_offset(o)` is the same
481 /// frame [`source_pos`] puts `base + o` on, with no rounding drift between them.
482 pub fn source_offset(&self, offset: u32) -> u32 {
483 let at = |o: u32| ramp_source_at(self.keys(), f64::from(self.base) + f64::from(o)).floor();
484 (at(offset) - at(0)).max(0.) as u32
485 }
486
487 /// Source frames (fractional) from the floored source position of the span's first
488 /// frame to the position `offset` timeline frames (fractional) into the span: what
489 /// [`source_offset`](SpeedRamp::source_offset) is without the floors, from the very
490 /// frame `from` names. The audio follows the ramp through this.
491 pub fn source_frames(&self, offset: f64) -> f64 {
492 let base = f64::from(self.base);
493 ramp_source_at(self.keys(), base + offset.max(0.0)) - ramp_source_at(self.keys(), base).floor()
494 }
495
496 /// The inverse of [`source_frames`](SpeedRamp::source_frames): the timeline frame
497 /// (fractional) into the span at which the ramp has read `source` source frames
498 /// of it.
499 pub fn timeline_frames(&self, source: f64) -> f64 {
500 let base = f64::from(self.base);
501 let target = source.max(0.0) + ramp_source_at(self.keys(), base).floor();
502 (ramp_timeline_at(self.keys(), target) - base).max(0.0)
503 }
504
505 /// The inverse of [`source_offset`](SpeedRamp::source_offset): the first offset
506 /// whose frame is `source` or past it, which is [`Speed::timeline_at`] for a ramp.
507 pub fn timeline_at(&self, source: u32) -> u32 {
508 let (mut lo, mut hi) = (0u32, source.saturating_mul(4).saturating_add(8));
509 while lo < hi {
510 let mid = lo + (hi - lo) / 2;
511 if self.source_offset(mid) >= source {
512 hi = mid;
513 } else {
514 lo = mid + 1;
515 }
516 }
517 lo
518 }
519}
520
521impl Default for Speed {
522 fn default() -> Self {
523 Self::NORMAL
524 }
525}
526
527impl std::fmt::Display for Speed {
528 /// `2.00x` -- what a card prints and what a clip box is marked with.
529 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530 write!(f, "{:.2}x", self.as_f64())
531 }
532}
533
534/// What a file's own frame rate is against the timeline's, as an exact
535/// rational: how many frames of the *file* one frame of the timeline is worth.
536///
537/// Every frame number in this module counts **timeline** frames -- a clip's
538/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps
539/// timeline is as many frames long as the seconds it lasts, and every edit
540/// (trim, split, speed, paste) is the same arithmetic it always was. This is the
541/// one conversion, and it happens at the decoder's door: [`PlaybackSession`]
542/// opens a worker with it and [`crate::export`] pulls pictures through it. The
543/// file's own numbering exists nowhere else.
544///
545/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an
546/// export encodes at a timeline frame has to be the frame playback is holding
547/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps
548/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`).
549///
550/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and
551/// stays `800/1001` however far the timeline runs, where a rate rounded to
552/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a
553/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`).
554///
555/// [`PlaybackSession`]: crate::PlaybackSession
556#[derive(Clone, Copy, PartialEq, Eq, Debug)]
557pub struct Rate {
558 /// Frames of the file...
559 source: u32,
560 /// ...per this many frames of the timeline it plays on. Never zero.
561 timeline: u32,
562}
563
564impl Rate {
565 /// A file shot at the timeline's own rate: every conversion below is the
566 /// identity, which is the path a single-rate project is on.
567 pub const REAL_TIME: Self = Self {
568 source: 1,
569 timeline: 1,
570 };
571
572 /// The rate of a file at `source_fps` on a timeline at `timeline_fps`,
573 /// exactly.
574 ///
575 /// Both rates come out of a container as a division, so neither is ever the
576 /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what
577 /// already knows how to name one exactly -- it is the same pair the muxer
578 /// counts an export's frames in -- and this is that pair divided by that
579 /// pair, reduced. A rate no timescale can name is an `Err` in that
580 /// function's own words rather than a silent 1:1 -- `matches_timeline` is
581 /// where a file carrying one is refused by name, beside the codec.
582 ///
583 /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every
584 /// timeline that had ever opened in this editor before mixed rates.
585 pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> {
586 let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?;
587 let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?;
588 // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks).
589 let num = u64::from(src_scale) * u64::from(tl_ticks);
590 let den = u64::from(src_ticks) * u64::from(tl_scale);
591 Ok(Self::reduced(num, den))
592 }
593
594 /// `num` frames of a file per `den` frames of a timeline, in lowest terms.
595 fn reduced(num: u64, den: u64) -> Self {
596 let g = gcd(num, den);
597 let (mut num, mut den) = (num / g, den / g);
598 // A ratio no pair of real frame rates produces, but the fields are `u32`
599 // so that every multiplication below fits a `u64` at any frame count.
600 while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) {
601 (num, den) = (num.div_ceil(2), den.div_ceil(2));
602 }
603 Self {
604 source: num.max(1) as u32,
605 timeline: den.max(1) as u32,
606 }
607 }
608
609 /// The same file against a timeline that has itself been retimed: `self` is
610 /// its frames per frame of the old timeline and `k` is old frames per new
611 /// one, so this is its frames per frame of the *new* one -- exactly, without
612 /// going back through an `f64` fps that names neither rate
613 /// ([`crate::PlaybackSession::set_frame_rate`]).
614 pub fn then(self, k: Rate) -> Self {
615 Self::reduced(
616 u64::from(self.source) * u64::from(k.source),
617 u64::from(self.timeline) * u64::from(k.timeline),
618 )
619 }
620
621 pub fn is_real_time(self) -> bool {
622 self.source == self.timeline
623 }
624
625 /// As a multiplier of the timeline's rate: what a *file's* own frame rate
626 /// is, given the timeline's, for a library row that names it.
627 pub fn as_f64(self) -> f64 {
628 f64::from(self.source) / f64::from(self.timeline)
629 }
630
631 /// Which frame of the file the `frame`th timeline-rate frame of it is:
632 /// floored, [`Speed::source_at`]'s half of the pair.
633 pub fn source_at(self, frame: u32) -> u32 {
634 (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline))
635 .min(u64::from(u32::MAX)) as u32
636 }
637
638 /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first
639 /// timeline-rate frame that shows source frame `source_frame` -- which is
640 /// the stamp playback puts on a decoded picture, and, applied to a file's
641 /// frame *count*, how long that file is in timeline frames.
642 pub fn timeline_at(self, source_frame: u32) -> u32 {
643 (u64::from(source_frame) * u64::from(self.timeline))
644 .div_ceil(u64::from(self.source))
645 .min(u64::from(u32::MAX)) as u32
646 }
647
648 /// The same map rounded to the *nearest* timeline frame, halves up, instead
649 /// of up: what a retime ([`Project::retime`]) lands every boundary, length
650 /// and envelope on. Ceiling every one of them biased each round trip later
651 /// by up to a frame per boundary, so a dissolve and a voiceover clip grew;
652 /// rounding to nearest is unbiased, so a boundary is never more than half a
653 /// frame from where its seconds put it, and a round trip through a grid that
654 /// holds the frame exactly returns it exactly.
655 pub fn timeline_nearest(self, source_frame: u32) -> u32 {
656 let num = u64::from(source_frame) * u64::from(self.timeline) * 2 + u64::from(self.source);
657 (num / (2 * u64::from(self.source))).min(u64::from(u32::MAX)) as u32
658 }
659}
660
661/// The source frames a clip has left past its in-point, on a table of `frames`
662/// (its lane's length of the source): the wall an end edge is measured to
663/// ([`Project::clip_walls`]), as a count. Never less than one frame.
664fn source_left(clip: &Clip, frames: &[u32]) -> u32 {
665 frames
666 .get(clip.source)
667 .copied()
668 .unwrap_or(clip.out_frame)
669 .saturating_sub(clip.in_frame)
670 .max(1)
671}
672
673/// Timeline frames `n` source frames of `c` occupy: [`Speed::room`] at its constant
674/// rate, the ramp's footprint for a ramped clip. Zero for none.
675fn footprint(c: &Clip, n: u32) -> u32 {
676 match n {
677 0 => 0,
678 n if c.speed_keys.is_empty() => c.speed.frames(n),
679 n => ramp_frames(&c.speed_keys, n),
680 }
681}
682
683/// The most source an `edge` trim of `clip` may keep, on a table of `frames`: the
684/// side of the window the trim grows is the out-point at a forward clip's end and at
685/// a reversed clip's start (its head is the window's far end), and the in-point
686/// (which cannot go below the file's first frame) at a reversed clip's end.
687/// Unbounded where the edge's own wall already is the bound.
688fn keep_cap(clip: &Clip, edge: Edge, frames: &[u32]) -> u32 {
689 match (edge, clip.reversed) {
690 (Edge::End, false) | (Edge::Start, true) => source_left(clip, frames),
691 (Edge::Start, false) => u32::MAX,
692 (Edge::End, true) => clip.out_frame.max(1),
693 }
694}
695
696/// Writes the trim of `c`'s `edge` to timeline frame `to`, keeping `keep` source
697/// frames: the frames that stay play what they played, so the window's end that is
698/// *not* at the edge is the one held still.
699fn write_trim(c: &mut Clip, edge: Edge, to: u32, keep: u32, still: bool) {
700 match (edge, c.reversed && !still) {
701 // A still has no earlier frame to walk an in-point back to --
702 // every frame of it is the same picture -- so its head grows
703 // *forward*: the range it plays is however long the new room is,
704 // anchored at the source's frame 0. Bounded by `lo`, which is where
705 // the cap in `source_frames` is applied.
706 (Edge::Start, _) if still => {
707 c.in_frame = 0;
708 c.out_frame = keep;
709 c.start = to;
710 }
711 // Non-negative by `lo`, which is what keeps the in-point on the source.
712 (Edge::Start, false) => {
713 c.in_frame = c.out_frame - keep.min(c.out_frame);
714 c.start = to;
715 }
716 (Edge::Start, true) => {
717 c.out_frame = c.in_frame + keep;
718 c.start = to;
719 }
720 // Never wider than the room the edge was clamped to: see [`Speed::fit`].
721 (Edge::End, false) => c.out_frame = c.in_frame + keep,
722 (Edge::End, true) => c.in_frame = c.out_frame - keep.min(c.out_frame),
723 }
724}
725
726/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its
727/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it.
728fn gcd(a: u64, b: u64) -> u64 {
729 match b {
730 0 => a.max(1),
731 b => gcd(b, a % b),
732 }
733}
734
735/// A half-open `[in_frame, out_frame)` range of frames of source
736/// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
737/// Never empty.
738///
739/// Counted at the **timeline's** frame rate, not the file's: a source shot at
740/// another rate is converted at the decoder's door ([`Rate`]), so every edit
741/// here is frames of one clock.
742#[derive(Clone, PartialEq, Debug)]
743pub struct Clip {
744 /// Timeline frame the clip's first frame is shown at. Meaningless on a
745 /// clipboard copy -- [`Project::paste`] and [`Project::place`] overwrite it
746 /// with where the caller asked for.
747 pub start: u32,
748 pub in_frame: u32,
749 pub out_frame: u32,
750 /// Index into [`Project::sources`].
751 pub source: usize,
752 /// Group id: clips sharing one were split from the same take. `None` for a
753 /// clip that belongs to no group.
754 pub link: Option<u32>,
755 /// Index into the project's equalizer table
756 /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
757 /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
758 /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
759 /// plain assignment. The table is append-only within a session, so an index
760 /// on a clipboard clip or inside an undo snapshot can never dangle.
761 pub eq: Option<u16>,
762 /// Index into the project's colour table
763 /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
764 /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
765 /// promises: `Copy`, append-only within a session, never dangling.
766 pub color: Option<u16>,
767 /// Index into the project's transform table
768 /// ([`Project::transform_of`]/[`Project::set_transform`]), or `None` for a
769 /// clip that plays at its fit policy's own placement. An index for
770 /// [`Clip::color`]'s reason and with the same promises.
771 pub transform: Option<u16>,
772 /// How this clip's picture meets a project canvas of another shape
773 /// ([`crate::scale::FitPolicy`]). Inline rather than a table index like the
774 /// two above: it is one byte with no parameters, so there is nothing for a
775 /// table to share, and a clip that is the project's own size never consults
776 /// it at all. [`FitPolicy::Fit`] is the default -- the whole picture, bars
777 /// where the aspect does not agree.
778 pub fit: FitPolicy,
779 /// How fast it plays ([`Speed`]). Inline like [`Clip::fit`] and unlike the
780 /// eq and colour indexes: it is two bytes with nothing to share, and a table
781 /// would put a level of indirection between the mapping and the one number
782 /// every frame of it is divided by.
783 ///
784 /// It does **not** move `in_frame`/`out_frame`: those stay the source range
785 /// the clip plays, so a trim and a split still address the file. What it
786 /// changes is how many *timeline* frames that range is spread over
787 /// ([`Clip::frames`]).
788 pub speed: Speed,
789 /// Timeline frames of ramp-up from silence at the clip's own start, inline
790 /// like [`Clip::fit`] and [`Clip::speed`] for the same reason: one small
791 /// number with nothing to share, and every consumer (mixer, exporter) wants
792 /// it sitting right next to the frame range it shapes. Clamped to the
793 /// clip's own length by the setter -- never wider than the clip is long.
794 pub fade_in: u32,
795 /// Timeline frames of ramp-down to silence at the clip's own end. Same
796 /// promises as [`Clip::fade_in`].
797 pub fade_out: u32,
798 /// Timeline frames of cross-dissolve into the clip immediately after this
799 /// one on the same video lane, at this clip's own end -- `0` for a hard
800 /// cut. Inline like [`Clip::fade_in`]/[`Clip::fade_out`] for the same
801 /// reason, and clamped the same way by its setter
802 /// ([`Project::set_transition_out`]): never wider than this clip's own
803 /// length, nor than the successor it dissolves into. Meaningless -- and
804 /// left as whatever it was -- the moment the next clip stops abutting
805 /// this one; a reader that cares checks adjacency itself rather than
806 /// trusting this field alone, exactly as a stored fade is trusted only
807 /// because a clip's own length is checked beside it.
808 pub transition_out: u32,
809 /// How [`Clip::transition_out`] is drawn: the picture's blend over the
810 /// overlap ([`crate::transitions`]). The sound is a crossfade whatever it
811 /// is. Older project files have no field and mean a dissolve.
812 pub transition_kind: crate::transitions::TransitionKind,
813 /// Non-zero: this clip is a waveform of its source's sound, painted
814 /// onto a video lane. Bit 0 is the flag; bits 1-2 style; bit 3 fast.
815 /// Zero is an ordinary picture. Older project files have no field and
816 /// mean zero.
817 pub visualizer: u8,
818 /// Packed look: hue 0-255, sat 0-255, strands 0-255, glow 0-255 in the
819 /// low four bytes as they have been since v22, then the strand colour's
820 /// own bytes above them -- its hue at 32 and sat at 40
821 /// ([`crate::decode::viz_strand_hue_ui`]) -- with the top bit as
822 /// [`crate::decode::viz_strand_set`]. All-zero is the default (timeline
823 /// azure, full sat, 8 strands, glow 2, no strand colour of its own).
824 /// Older files have no field and mean zero; a v22 file's 32-bit value
825 /// is the low half of this one, byte for byte.
826 pub viz_paint: u64,
827 /// The clip's own volume in dB, on top of its lane's
828 /// ([`Project::lane_gain_db`]). `0.0` is unity and the default; the setter
829 /// keeps it within [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. It is
830 /// applied as a linear multiplier inside the clip's own envelope
831 /// ([`Fade`]), so playback and export hear the same number. Audio clips
832 /// only. Not `Eq`: a float, and nothing compared clips by it.
833 pub gain_db: f32,
834 /// The clip's volume envelope: points of dB keyed to SOURCE frames, sorted
835 /// by [`GainKey::at`] with no two alike. Empty is 0 dB. Source-keyed, so a
836 /// move, a trim or a ripple keeps each point on the same audio, and a split
837 /// keeps the whole curve on both halves. It rides on top of
838 /// [`Clip::gain_db`] and the fades, inside the same [`Fade`]. Audio clips
839 /// only ([`Project::set_gain_keys`]). Capped at [`MAX_GAIN_KEYS`].
840 pub gain_keys: Vec<GainKey>,
841 /// Where the clip sits between the speakers, in whole percent: `-100` (left) to
842 /// `100` (right), `0` the default and the middle. One byte, because it sits in the
843 /// padding where an `f32` would have grown the clip. A balance on a stereo mix: the far
844 /// side is turned down, the near one left alone. Rides in the clip's [`Fade`] like its
845 /// gain. Audio clips only ([`Project::set_clip_pan`]); [`Clip::pan_value`] reads it as
846 /// `-1.0..=1.0`.
847 pub pan: i8,
848 /// The clip's pitch in whole semitones, `-12` (an octave down) to `12` (up), `0` the
849 /// default and the original sound. Changes the pitch and keeps the speed: the
850 /// stretch and the resample that make it are built by [`Project::lane_speeds_from`],
851 /// so playback and export hear the same thing. Audio clips only
852 /// ([`Project::set_clip_pitch`]). One byte, in the same padding as [`Clip::pan`].
853 pub pitch: i8,
854 /// The clip's placement animation: whole [`TransformParams`] at SOURCE
855 /// frames, sorted by [`TransformKey::at`] with no two alike. Empty is the
856 /// single [`Clip::transform`] for the whole clip. Video lanes only
857 /// ([`Project::set_transform_keys`]). Kept on the footage the way the
858 /// volume points are: a trim leaves them, and a split divides them with a
859 /// key at the cut ([`split_transform_keys`]).
860 pub transform_keys: Vec<TransformKey>,
861 /// The clip's opacity animation: `0..=1` at SOURCE frames, sorted by
862 /// [`OpacityKey::at`] with no two alike. With keys present they give the
863 /// opacity (replacing [`TransformParams::opacity`], whose own keys are then
864 /// not read for it); the fades still multiply on top. Empty is the
865 /// transform's constant opacity. Video lanes only
866 /// ([`Project::set_opacity_keys`]); kept on the footage as the placement
867 /// keys are.
868 pub opacity_keys: Vec<OpacityKey>,
869 /// The clip's colour animation: the whole grade at SOURCE frames, sorted by
870 /// [`ColorKey::at`] with no two alike. With keys present they give the
871 /// grade (replacing the clip's constant one). Video lanes only
872 /// ([`Project::set_color_keys`]); kept on the footage as the placement keys are.
873 pub color_keys: Vec<ColorKey>,
874 /// The clip's speed ramp: keys of speed at CLIP-relative timeline frames, sorted
875 /// by [`SpeedKey::at`] with no two alike, at most [`MAX_SPEED_KEYS`]. Empty is
876 /// the constant [`Clip::speed`], which every path not named otherwise keeps. With
877 /// keys present the ramp replaces the constant: [`Clip::frames`] is the ramp's
878 /// footprint and [`source_pos`] the ramp's mapping, and [`Clip::speed`] is left
879 /// as it was, to come back when the ramp is cleared.
880 pub speed_keys: Vec<SpeedKey>,
881 /// Whether the clip plays its source window backwards: the timeline's first
882 /// frame shows the window's last source frame, the picture and the sound both.
883 /// Composes with [`Clip::speed`] and [`Clip::speed_keys`] (the rate is how fast
884 /// the window is walked, from its far end), leaves the window ([`Clip::in_frame`]
885 /// and [`Clip::out_frame`]) and the footprint ([`Clip::frames`]) as they were, and
886 /// keeps every key where it plays on the timeline ([`Project::set_reverse`]
887 /// mirrors the source-keyed ones when it flips). Fades are timeline-relative and
888 /// need nothing.
889 pub reversed: bool,
890 /// The clip's effects stack ([`crate::effects`]), drawn in order on its
891 /// picture before it is laid over the lanes beneath. Empty, or every effect
892 /// switched off, is no effect. Video lanes only ([`Project::set_effects`]); a
893 /// split gives both halves the whole stack.
894 pub effects: Vec<crate::effects::Effect>,
895 /// The clip's stabilisation, `None` for off ([`crate::stabilise`]): the
896 /// camera shake measured from its footage is taken out of each picture
897 /// before its placement ([`Clip::transform`], [`Clip::transform_keys`]) is
898 /// applied, read by the file frame shown, so it survives trims, speed,
899 /// ramps and reverse.
900 pub stabilise: Option<crate::stabilise::Stabilise>,
901 /// Which angle of a multicam clip this clip shows ([`Angle`]); the default, angle 1, for
902 /// every clip that is not a multicam clip.
903 pub angle: Angle,
904 /// How an interlaced source is made progressive ([`Deinterlace`]). Only
905 /// matters for a clip whose source is interlaced; kept on the clip so a
906 /// split, a copy, a nest and an undo carry it like any other setting.
907 pub deinterlace: Deinterlace,
908 /// The clip's colour label and whether it is switched off ([`ClipMark`]).
909 pub mark: ClipMark,
910}
911
912/// The number of colour labels a clip can carry ([`LABELS`]); label 0 is none.
913pub const LABEL_COUNT: u8 = 8;
914
915/// The fixed palette of clip labels, as Premiere names them: a clip with label `n` (1-based) is
916/// tinted `LABELS[n - 1]`. Label 0 is no label.
917pub const LABELS: [(&str, [u8; 3]); LABEL_COUNT as usize] = [
918 ("Violet", [0x9a, 0x6a, 0xd0]),
919 ("Iris", [0x5a, 0x6c, 0xd8]),
920 ("Caribbean", [0x2a, 0xa5, 0x9a]),
921 ("Lavender", [0xc0, 0x8a, 0xc4]),
922 ("Cerulean", [0x3a, 0x9a, 0xd6]),
923 ("Forest", [0x3e, 0x8a, 0x4a]),
924 ("Rose", [0xd8, 0x5a, 0x8a]),
925 ("Mango", [0xe0, 0x93, 0x2c]),
926];
927
928/// The name of label `n` (1-based), `None` for no label or one past the palette.
929pub fn label_name(n: u8) -> Option<&'static str> {
930 LABELS.get(usize::from(n).checked_sub(1)?).map(|l| l.0)
931}
932
933/// The label number a name (any case) or a number spells; `Some(0)` for `none`.
934pub fn label_by_name(name: &str) -> Option<u8> {
935 let name = name.trim();
936 if name.eq_ignore_ascii_case("none") || name == "0" {
937 return Some(0);
938 }
939 if let Ok(n) = name.parse::<u8>() {
940 return (n <= LABEL_COUNT).then_some(n);
941 }
942 LABELS.iter().position(|l| l.0.eq_ignore_ascii_case(name)).map(|i| i as u8 + 1)
943}
944
945/// What a clip carries that no render reads but the person editing does -- its colour label --
946/// and the switch that takes it out of the render ([`Clip::mark`]).
947#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
948pub struct ClipMark {
949 /// 0 for none, else 1..=[`LABEL_COUNT`] ([`LABELS`]).
950 pub label: u8,
951 /// Switched off: the clip stays on the timeline but is skipped by playback, export and the
952 /// mix, as if its stretch were a gap.
953 pub off: bool,
954}
955
956impl ClipMark {
957 /// Whether this is the default (nothing to write to a file).
958 pub fn is_default(self) -> bool {
959 self == ClipMark::default()
960 }
961}
962
963/// The angle a multicam clip ([`Project::make_multicam`]) shows: `video` picks the picture
964/// and, unless `audio` is set, the sound too (audio follows video). Angles count from 0.
965#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
966pub struct Angle {
967 pub video: u8,
968 /// The angle the sound is taken from when it does not follow the picture.
969 pub audio: Option<u8>,
970}
971
972impl Angle {
973 /// The angle `kind` plays: the picture's own, or the sound's (which follows the picture
974 /// unless pinned).
975 pub fn of(self, kind: LaneKind) -> u8 {
976 match kind {
977 LaneKind::Audio => self.audio.unwrap_or(self.video),
978 _ => self.video,
979 }
980 }
981
982 /// Whether this is the default (nothing to write to a file).
983 pub fn is_default(self) -> bool {
984 self == Angle::default()
985 }
986}
987
988
989/// How a clip's interlaced source is turned into progressive pictures.
990#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
991pub enum Deinterlace {
992 /// One picture per frame (the two fields blended by the deinterlacer).
993 #[default]
994 Frame,
995 /// One picture per field (double rate).
996 Field,
997 /// Leave the fields woven as they are.
998 Off,
999 /// Remove pulldown when the file shows a stable 3:2 cadence (or states soft
1000 /// pulldown), otherwise deinterlace as `Frame` ([`crate::ivtc`]).
1001 IvtcAuto,
1002 /// Remove pulldown: 23.976p film frames back out of 29.97i, whether or not the
1003 /// cadence is clear ([`crate::ivtc`]).
1004 Ivtc,
1005}
1006
1007impl Deinterlace {
1008 pub const ALL: [Deinterlace; 5] =
1009 [Deinterlace::Frame, Deinterlace::Field, Deinterlace::Off, Deinterlace::IvtcAuto, Deinterlace::Ivtc];
1010
1011 /// The word a file and the MCP use: `frame`, `field`, `off`.
1012 pub fn name(self) -> &'static str {
1013 match self {
1014 Deinterlace::Frame => "frame",
1015 Deinterlace::Field => "field",
1016 Deinterlace::Off => "off",
1017 Deinterlace::IvtcAuto => "ivtc-auto",
1018 Deinterlace::Ivtc => "ivtc",
1019 }
1020 }
1021
1022 pub fn from_name(name: &str) -> Option<Self> {
1023 Self::ALL.into_iter().find(|d| d.name() == name)
1024 }
1025}
1026
1027/// The quietest a clip's own gain can be set, in dB ([`Project::set_clip_gain`]).
1028pub const MIN_CLIP_GAIN_DB: f32 = -60.0;
1029/// The loudest a clip's own gain can be set, in dB ([`Project::set_clip_gain`]).
1030pub const MAX_CLIP_GAIN_DB: f32 = 24.0;
1031
1032/// The widest a clip's pitch shift may be, in semitones either way ([`Clip::pitch`]).
1033pub const MAX_CLIP_PITCH: i8 = 12;
1034/// The lowest a clip's pitch shift may be ([`Clip::pitch`]).
1035pub const MIN_CLIP_PITCH: i8 = -12;
1036/// The most points a clip's gain envelope may hold ([`Clip::gain_keys`]).
1037pub const MAX_GAIN_KEYS: usize = 256;
1038
1039/// One point of a clip's volume envelope ([`Clip::gain_keys`]): `db` at the
1040/// source frame `at`, which is the clip's in/out unit -- media time, counted at
1041/// the timeline's fps. Between points the dB is linear; before the first and
1042/// after the last it holds.
1043#[derive(Clone, Copy, PartialEq, Debug)]
1044pub struct GainKey {
1045 /// Source frame of the point.
1046 pub at: u32,
1047 /// Gain there, in dB, within [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`].
1048 pub db: f32,
1049 /// The easing of the segment that leaves this point ([`KeyEase::Linear`]
1050 /// unless set).
1051 pub ease: KeyEase,
1052}
1053
1054/// Which animation a keyframe button or action is about: the placement
1055/// ([`Clip::transform_keys`]), the opacity ([`Clip::opacity_keys`]) or the grade
1056/// ([`Clip::color_keys`]).
1057#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1058pub enum KeyKind {
1059 Placement,
1060 Opacity,
1061 Color,
1062}
1063
1064impl GainKey {
1065 /// A linear point: `db` at source frame `at`.
1066 pub fn new(at: u32, db: f32) -> Self {
1067 Self { at, db, ease: KeyEase::Linear }
1068 }
1069}
1070
1071/// The envelope's dB at source position `src` (fractional, in source frames)
1072/// over `points`, which are `(position, dB)` pairs sorted by position with no
1073/// two alike. Eased in dB between neighbours by the earlier point's ease
1074/// (linear by default), held flat outside the first and last point, and `0.0` for no points at all. The one interpolation both
1075/// [`Clip::gain_keys`] and the playback [`Fade`] evaluate.
1076fn lerp_db<T>(points: &[T], at: impl Fn(&T) -> (f64, f32, KeyEase), src: f64) -> f32 {
1077 let (Some(first), Some(last)) = (points.first(), points.last()) else {
1078 return 0.0;
1079 };
1080 let (x0, db0, _) = at(first);
1081 if src <= x0 {
1082 return db0;
1083 }
1084 let (xn, dbn, _) = at(last);
1085 if src >= xn {
1086 return dbn;
1087 }
1088 // The first point strictly after `src`: its predecessor is the left end
1089 // of the segment `src` is in, and both exist by the two checks above.
1090 let i = points.partition_point(|p| at(p).0 <= src);
1091 let (xa, dba, ease) = at(&points[i - 1]);
1092 let (xb, dbb, _) = at(&points[i]);
1093 let t = ease_shape(ease, ((src - xa) / (xb - xa)) as f32);
1094 dba + (dbb - dba) * t
1095}
1096
1097/// The placement `clip` shows at timeline `timeline_frame`, given its base
1098/// `base` ([`Clip::transform`] resolved): its [`Clip::transform_keys`] at the
1099/// source frame that frame plays, the same way [`Project::gain_db_at`] reads
1100/// the volume envelope, or `base` with no keys. Timeline frames before the
1101/// clip read as its first frame.
1102pub fn clip_transform_at(clip: &Clip, base: TransformParams, timeline_frame: u32) -> TransformParams {
1103 if clip.transform_keys.is_empty() {
1104 return base;
1105 }
1106 keyed_transform(&base, &clip.transform_keys, key_sample_pos(clip, timeline_frame))
1107}
1108
1109/// The opacity `clip` shows at timeline `timeline_frame`, given the opacity
1110/// `base` its transform gives there: its [`Clip::opacity_keys`] when it has
1111/// any, otherwise `base`. The fades are not in it; they multiply on top.
1112pub fn clip_opacity_at(clip: &Clip, base: f32, timeline_frame: u32) -> f32 {
1113 if clip.opacity_keys.is_empty() {
1114 return base;
1115 }
1116 evaluate_opacity(base, &clip.opacity_keys, key_sample_pos(clip, timeline_frame))
1117}
1118
1119/// The grade `clip` shows at timeline `timeline_frame`, given its constant
1120/// grade `base` ([`Project::color_of`] resolved, identity for none): its
1121/// [`Clip::color_keys`] interpolated at the source frame that frame plays, or
1122/// `base` with no keys.
1123pub fn clip_color_at(clip: &Clip, base: ColorParams, timeline_frame: u32) -> ColorParams {
1124 if clip.color_keys.is_empty() {
1125 return base;
1126 }
1127 evaluate_color(base, &clip.color_keys, key_sample_pos(clip, timeline_frame))
1128}
1129
1130/// Whether `clip` has any animation that changes the picture per frame
1131/// (placement, opacity or colour keys): the clips a layered path composes.
1132pub fn clip_animated(clip: &Clip) -> bool {
1133 !(clip.transform_keys.is_empty() && clip.opacity_keys.is_empty() && clip.color_keys.is_empty())
1134 || crate::effects::active(&clip.effects)
1135 || clip.stabilise.is_some()
1136}
1137
1138/// `c`'s placement keys after a trim that moved its `edge` from the state in
1139/// `old` (see [`keys_within`]). A still's head keeps the keys on the timeline
1140/// ([`keys_after_still_head`]); everything else keeps them on their footage.
1141fn rekey_trimmed(c: &mut Clip, old: &Clip, edge: Edge, still: bool) {
1142 fn rekey<K: Keyed>(old_keys: &[K], oc: &Clip, c: &Clip, edge: Edge, still: bool) -> Vec<K> {
1143 match edge {
1144 Edge::Start if still => keys_after_still_head(
1145 old_keys,
1146 oc.start,
1147 oc.in_frame,
1148 c.start,
1149 c.out_frame,
1150 oc.speed.as_f64(),
1151 ),
1152 _ => keys_within(old_keys, c.in_frame, c.out_frame),
1153 }
1154 }
1155 if !old.transform_keys.is_empty() {
1156 c.transform_keys = rekey(&old.transform_keys, old, c, edge, still);
1157 }
1158 if !old.opacity_keys.is_empty() {
1159 c.opacity_keys = rekey(&old.opacity_keys, old, c, edge, still);
1160 }
1161 if !old.color_keys.is_empty() {
1162 c.color_keys = rekey(&old.color_keys, old, c, edge, still);
1163 }
1164 // A mask's keys follow its stack position: the same effect, rekeyed the same way.
1165 let masks: Vec<Option<Vec<crate::effects::MaskKey>>> = old
1166 .effects
1167 .iter()
1168 .map(|e| (!e.keys.is_empty()).then(|| rekey(&e.keys, old, c, edge, still)))
1169 .collect();
1170 for (e, keys) in c.effects.iter_mut().zip(masks) {
1171 if let Some(keys) = keys {
1172 e.keys = keys;
1173 }
1174 }
1175}
1176
1177/// The split of a clip's placement animation at source frame `cut`: the left
1178/// half keeps the keys before the cut and the right half the keys after it,
1179/// and both get a key at `cut` holding the placement the whole animation gives
1180/// there, so each half still moves exactly as the clip did over its own frames.
1181/// The cut key takes the easing of the segment it sits in. Empty in, empty out.
1182pub fn split_transform_keys<K: Keyed>(keys: &[K], cut: u32) -> (Vec<K>, Vec<K>) {
1183 let Some(at) = sample(keys, f64::from(cut)) else {
1184 return (Vec::new(), Vec::new());
1185 };
1186 let ease = keys
1187 .iter()
1188 .rev()
1189 .find(|k| k.at() <= cut)
1190 .map_or(KeyEase::Linear, |k| k.ease());
1191 let boundary = at.placed(cut, ease);
1192 let mut left: Vec<K> = keys.iter().copied().filter(|k| k.at() < cut).collect();
1193 left.push(boundary);
1194 let mut right = vec![boundary];
1195 right.extend(keys.iter().copied().filter(|k| k.at() > cut));
1196 (left, right)
1197}
1198
1199/// The gain envelope's dB at source frame `src` over `keys`
1200/// ([`Clip::gain_keys`]): linear between points, held outside them, `0.0`
1201/// when there are none. Exact at a point, and the midpoint of two points is
1202/// the midpoint of their dB.
1203pub fn gain_keys_db_at(keys: &[GainKey], src: f64) -> f32 {
1204 lerp_db(keys, |k| (f64::from(k.at), k.db, k.ease), src)
1205}
1206
1207impl Clip {
1208 /// A plain clip of `source` reading `in_frame..out_frame`, at start 0, normal
1209 /// speed and no look: the shape a front-end hands
1210 /// [`Project::edit_from_source`] for one half of a take.
1211 pub fn source_range(source: usize, in_frame: u32, out_frame: u32) -> Clip {
1212 Clip {
1213 speed_keys: Vec::new(),
1214 reversed: false,
1215 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1216 angle: Default::default(),
1217 start: 0,
1218 in_frame,
1219 out_frame,
1220 source,
1221 link: None,
1222 eq: None,
1223 color: None,
1224 transform: None,
1225 transform_keys: Vec::new(),
1226 opacity_keys: Vec::new(),
1227 color_keys: Vec::new(),
1228 effects: Vec::new(),
1229 fit: FitPolicy::default(),
1230 speed: Speed::NORMAL,
1231 fade_in: 0,
1232 fade_out: 0,
1233 transition_out: 0,
1234 transition_kind: Default::default(),
1235 visualizer: 0,
1236 viz_paint: 0,
1237 gain_db: 0.0,
1238 gain_keys: Vec::new(),
1239 pan: 0,
1240 pitch: 0,
1241 }
1242 }
1243
1244 /// Source frame count; `>= 1` by the never-empty invariant. What the clip
1245 /// reads out of its file -- not how long it is on the timeline, which is
1246 /// [`Clip::frames`] and differs the moment it is speeded.
1247 pub fn len(&self) -> u32 {
1248 self.out_frame - self.in_frame
1249 }
1250
1251 /// Always false: a clip reads at least one source frame.
1252 pub fn is_empty(&self) -> bool {
1253 self.len() == 0
1254 }
1255
1256 /// Timeline frames it occupies: its source range at its own speed, never
1257 /// zero (see [`Speed::frames`]). Every placement question -- where it ends,
1258 /// what it overlaps, how wide its box is -- is asked of this and not of
1259 /// [`Clip::len`].
1260 pub fn frames(&self) -> u32 {
1261 if self.speed_keys.is_empty() {
1262 self.speed.frames(self.len())
1263 } else {
1264 ramp_frames(&self.speed_keys, self.len())
1265 }
1266 }
1267
1268 /// One past the last timeline frame it covers.
1269 pub fn end(&self) -> u32 {
1270 self.start + self.frames()
1271 }
1272
1273 /// Whether a cut at `frame` lands cleanly on this clip: outside it, or inside at a frame
1274 /// its rate (or ramp) can address. What the razor asks before it offers to cut.
1275 pub fn splits_at(&self, frame: u32) -> bool {
1276 (self.start < frame && frame < self.end()) && split_source(self, frame).is_some()
1277 }
1278
1279 /// Source frames from the clip's in point to the one its `clip_frame`th timeline
1280 /// frame plays: [`Speed::source_at`], or for a ramped clip the ramp's integral
1281 /// floored ([`source_pos`]). What every "which source frame is on screen" asks,
1282 /// at a constant speed or not.
1283 pub fn source_offset(&self, clip_frame: u32) -> u32 {
1284 if self.speed_keys.is_empty() {
1285 self.speed.source_at(clip_frame)
1286 } else {
1287 ramp_source_at(&self.speed_keys, f64::from(clip_frame)).floor() as u32
1288 }
1289 }
1290
1291 /// The inverse of [`source_offset`](Clip::source_offset), ceiled: the first
1292 /// clip-relative timeline frame whose source frame is `source_offset` or past it
1293 /// -- [`Speed::timeline_at`], or the ramp's. Where a source instant that starts
1294 /// something (a word, a speech region) lands.
1295 pub fn timeline_offset(&self, source_offset: u32) -> u32 {
1296 if self.speed_keys.is_empty() {
1297 self.speed.timeline_at(source_offset)
1298 } else {
1299 SpeedRamp::new(&self.speed_keys, 0).timeline_at(source_offset)
1300 }
1301 }
1302
1303 /// [`timeline_offset`](Clip::timeline_offset) floored instead: the rounding an
1304 /// *end* needs, so a region never eats the frame the next thing starts on.
1305 pub fn timeline_offset_floor(&self, source_offset: u32) -> u32 {
1306 if self.speed_keys.is_empty() {
1307 (u64::from(source_offset) * 1000 / u64::from(self.speed.permille())).min(u64::from(u32::MAX))
1308 as u32
1309 } else {
1310 ramp_timeline_at(&self.speed_keys, f64::from(source_offset)).floor() as u32
1311 }
1312 }
1313
1314 /// [`source_offset`](Clip::source_offset) without the floor, for a fractional
1315 /// clip-relative timeline frame: source frames from the in point, continuous.
1316 pub fn source_offset_f(&self, clip_frame: f64) -> f64 {
1317 if self.speed_keys.is_empty() {
1318 clip_frame.max(0.0) * self.speed.as_f64()
1319 } else {
1320 ramp_source_at(&self.speed_keys, clip_frame)
1321 }
1322 }
1323
1324 /// The inverse of [`source_offset_f`](Clip::source_offset_f): the clip-relative
1325 /// timeline frame (fractional) at which the clip has played `source_frames` source
1326 /// frames of itself.
1327 pub fn timeline_offset_f(&self, source_frames: f64) -> f64 {
1328 if self.speed_keys.is_empty() {
1329 source_frames / self.speed.as_f64()
1330 } else {
1331 ramp_timeline_at(&self.speed_keys, source_frames)
1332 }
1333 }
1334
1335 /// The longest source range that fits in `frames` timeline frames at this clip's
1336 /// speed -- [`Speed::fit`], or for a ramped clip the largest length whose ramp
1337 /// footprint ([`ramp_frames`]) fits. `None` when nothing does.
1338 pub fn fit_source(&self, frames: u32) -> Option<u32> {
1339 if self.speed_keys.is_empty() {
1340 return self.speed.fit(frames);
1341 }
1342 if frames == 0 || ramp_frames(&self.speed_keys, 1) > frames {
1343 return None;
1344 }
1345 // The footprint is monotone in the source length, so bisect for the largest
1346 // that still fits. Doubling first bounds the search.
1347 let (mut lo, mut hi) = (1u32, 2u32);
1348 while ramp_frames(&self.speed_keys, hi) <= frames && hi < u32::MAX / 2 {
1349 lo = hi;
1350 hi *= 2;
1351 }
1352 while lo < hi {
1353 let mid = lo + (hi - lo).div_ceil(2);
1354 if ramp_frames(&self.speed_keys, mid) <= frames {
1355 lo = mid;
1356 } else {
1357 hi = mid - 1;
1358 }
1359 }
1360 Some(lo)
1361 }
1362}
1363
1364/// The speed a ramp runs at clip-relative frame `t`, linear between keys and held at
1365/// the ends, rounded to a [`Speed`] (thousandths).
1366pub fn ramp_speed_at(keys: &[SpeedKey], t: u32) -> Speed {
1367 let Some(first) = keys.first() else {
1368 return Speed::NORMAL;
1369 };
1370 if t <= first.at {
1371 return first.speed;
1372 }
1373 for w in keys.windows(2) {
1374 let (a, b) = (w[0], w[1]);
1375 if t <= b.at {
1376 let f = f64::from(t - a.at) / f64::from(b.at - a.at);
1377 let (ra, rb) = (a.speed.as_f64(), b.speed.as_f64());
1378 return Speed::from_permille(((ra + (rb - ra) * f) * 1000.).round() as u16);
1379 }
1380 }
1381 keys[keys.len() - 1].speed
1382}
1383
1384/// The keys of the part of a ramped clip from clip-relative frame `cut` on, rebased so
1385/// that `cut` is frame 0: the speed there first, then the keys after it, shifted.
1386/// What a clip's tail keeps when its head is cut away.
1387pub fn ramp_keys_from(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
1388 let mut out = vec![SpeedKey {
1389 at: 0,
1390 speed: ramp_speed_at(keys, cut),
1391 }];
1392 out.extend(
1393 keys.iter()
1394 .filter(|k| k.at > cut)
1395 .map(|k| SpeedKey { at: k.at - cut, speed: k.speed }),
1396 );
1397 out
1398}
1399
1400/// A file the timeline plays from, and *which* of its audio streams it plays:
1401/// a file carrying one track per language is several sources, one per stream,
1402/// sharing a path. Two entries differing only in the stream are two sources --
1403/// they are what a clip names, and a clip plays exactly one stream.
1404///
1405/// The path is always canonical ([`Source::new`]), so the same file reached by
1406/// two paths is one source.
1407#[derive(Clone, Debug, Default)]
1408pub struct Source {
1409 pub path: PathBuf,
1410 /// Position among the file's audio tracks in file order, the numbering
1411 /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
1412 /// single track, and for a silent one.
1413 pub audio_stream: usize,
1414 /// Starred in the library (v51). Not part of the source's identity.
1415 pub fav: bool,
1416 /// The [`Bin`] this source is filed in (v51); `0` for none, the library's top level.
1417 pub bin: u32,
1418}
1419
1420/// A source is the file and the stream: starring it or filing it in a bin does not make it
1421/// another source.
1422impl PartialEq for Source {
1423 fn eq(&self, other: &Self) -> bool {
1424 self.path == other.path && self.audio_stream == other.audio_stream
1425 }
1426}
1427impl Eq for Source {}
1428
1429/// A named folder in the media library (v51). Ids start at 1 and are never reused in a session.
1430/// `parent` is `0` for a top-level bin, or the id of a top-level bin: one level of nesting.
1431#[derive(Clone, Debug, PartialEq, Eq)]
1432pub struct Bin {
1433 pub id: u32,
1434 pub parent: u32,
1435 pub name: String,
1436}
1437
1438/// The longest bin name.
1439pub const MAX_BIN_NAME_CHARS: usize = 60;
1440/// The most bins a project holds.
1441pub const MAX_BINS: usize = 1_000;
1442
1443/// A bin name as the library keeps it: trimmed, non-empty, short, no control characters.
1444pub fn clean_bin_name(name: &str) -> Result<String, String> {
1445 let name = name.trim();
1446 if name.is_empty() {
1447 return Err("a bin needs a name".into());
1448 }
1449 if name.chars().count() > MAX_BIN_NAME_CHARS {
1450 return Err(format!("a bin name is at most {MAX_BIN_NAME_CHARS} characters"));
1451 }
1452 if name.chars().any(char::is_control) {
1453 return Err("a bin name holds no control characters".into());
1454 }
1455 Ok(name.to_string())
1456}
1457
1458impl Project {
1459 /// The library's bins, in creation order (v51).
1460 pub fn bins(&self) -> &[Bin] {
1461 &self.bins
1462 }
1463
1464 /// The bins a load puts back, with no undo step. Ids are kept; new ones start past the largest.
1465 pub fn with_bins(mut self, bins: Vec<Bin>) -> Self {
1466 self.bin_next = bins.iter().map(|b| b.id).max().unwrap_or(0) + 1;
1467 self.bins = bins;
1468 self
1469 }
1470
1471 fn bin_name_taken(&self, parent: u32, name: &str, except: u32) -> bool {
1472 self.bins.iter().any(|b| b.parent == parent && b.id != except && b.name.eq_ignore_ascii_case(name))
1473 }
1474
1475 /// Makes a bin named `name` inside bin `parent` (`0`: at the top level). Only a top-level bin
1476 /// holds bins, and two bins in one place cannot share a name. One undo step; returns the id.
1477 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
1478 let name = clean_bin_name(name)?;
1479 if parent != 0 {
1480 match self.bins.iter().find(|b| b.id == parent) {
1481 None => return Err(format!("there is no bin {parent}")),
1482 Some(b) if b.parent != 0 => return Err("bins nest one level deep: that bin is already inside another".into()),
1483 Some(_) => {}
1484 }
1485 }
1486 if self.bin_name_taken(parent, &name, 0) {
1487 return Err(format!("there is already a bin named {name} there"));
1488 }
1489 if self.bins.len() >= MAX_BINS {
1490 return Err(format!("a project holds at most {MAX_BINS} bins"));
1491 }
1492 self.snapshot();
1493 let id = self.bin_next;
1494 self.bin_next += 1;
1495 self.bins.push(Bin { id, parent, name });
1496 Ok(id)
1497 }
1498
1499 /// Renames bin `id`. `Ok(false)`, and no undo step, when the name is already that.
1500 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
1501 let name = clean_bin_name(name)?;
1502 let Some(at) = self.bins.iter().position(|b| b.id == id) else {
1503 return Err(format!("there is no bin {id}"));
1504 };
1505 if self.bins[at].name == name {
1506 return Ok(false);
1507 }
1508 if self.bin_name_taken(self.bins[at].parent, &name, id) {
1509 return Err(format!("there is already a bin named {name} there"));
1510 }
1511 self.snapshot();
1512 self.bins[at].name = name;
1513 Ok(true)
1514 }
1515
1516 /// Removes bin `id`. What it held is not lost: its sources go to the bin it was in (the top
1517 /// level for a top-level one) and the bins inside it come out to the top level. Returns how
1518 /// many sources moved. One undo step.
1519 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
1520 let Some(bin) = self.bins.iter().find(|b| b.id == id).cloned() else {
1521 return Err(format!("there is no bin {id}"));
1522 };
1523 self.snapshot();
1524 let mut moved = 0;
1525 for s in self.sources.iter_mut().filter(|s| s.bin == id) {
1526 s.bin = bin.parent;
1527 moved += 1;
1528 }
1529 self.bins.retain(|b| b.id != id);
1530 let children: Vec<u32> = self.bins.iter().filter(|b| b.parent == id).map(|b| b.id).collect();
1531 for c in children {
1532 let at = self.bins.iter().position(|b| b.id == c).expect("listed above");
1533 let mut name = self.bins[at].name.clone();
1534 let mut n = 1;
1535 while self.bin_name_taken(0, &name, c) {
1536 n += 1;
1537 name = format!("{} {n}", self.bins[at].name);
1538 }
1539 self.bins[at].name = name;
1540 self.bins[at].parent = 0;
1541 }
1542 Ok(moved)
1543 }
1544
1545 /// Files sources `srcs` in bin `bin` (`0`: out of every bin, to the top level). Returns how
1546 /// many changed; one undo step, none when nothing changes.
1547 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
1548 if bin != 0 && !self.bins.iter().any(|b| b.id == bin) {
1549 return Err(format!("there is no bin {bin}"));
1550 }
1551 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1552 return Err(format!("there is no source {bad}"));
1553 }
1554 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].bin != bin).collect();
1555 todo.sort_unstable();
1556 todo.dedup();
1557 if todo.is_empty() {
1558 return Ok(0);
1559 }
1560 self.snapshot();
1561 for &i in &todo {
1562 self.sources[i].bin = bin;
1563 }
1564 Ok(todo.len())
1565 }
1566
1567 /// Stars or unstars sources `srcs`. Returns how many changed; one undo step, none when
1568 /// nothing changes.
1569 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
1570 if let Some(bad) = srcs.iter().find(|&&i| i >= self.sources.len()) {
1571 return Err(format!("there is no source {bad}"));
1572 }
1573 let mut todo: Vec<usize> = srcs.iter().copied().filter(|&i| self.sources[i].fav != on).collect();
1574 todo.sort_unstable();
1575 todo.dedup();
1576 if todo.is_empty() {
1577 return Ok(0);
1578 }
1579 self.snapshot();
1580 for &i in &todo {
1581 self.sources[i].fav = on;
1582 }
1583 Ok(todo.len())
1584 }
1585}
1586
1587impl Source {
1588 pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
1589 Self {
1590 path: canonical(path.as_ref()),
1591 audio_stream,
1592 fav: false,
1593 bin: 0,
1594 }
1595 }
1596}
1597
1598/// Which three-point edit [`Project::edit_from_source`] makes.
1599#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1600pub enum SourceEdit {
1601 /// Opens room: what is at and after the frame moves later.
1602 Insert,
1603 /// Replaces what is there for the take's length; nothing moves.
1604 Overwrite,
1605}
1606
1607/// What a lane carries, which is what a *gap* in it means: black frames on a
1608/// video lane, silence on an audio one, nothing over the picture on a subtitle
1609/// one.
1610#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1611pub enum LaneKind {
1612 Video,
1613 Audio,
1614 /// Words over the picture, placed and trimmed like everything else
1615 /// ([`SubClip`]). A lane of its own rather than a setting on the project,
1616 /// so a caption is dragged, cut, rippled and undone by the machinery every
1617 /// other clip already goes through.
1618 ///
1619 /// It carries no [`Clip`] at all, and that is what keeps the media paths
1620 /// free of it: [`Project::lane`] hands back an empty slice, so every
1621 /// clip-indexed call ([`Project::trim`], [`Project::set_eq`],
1622 /// [`Project::set_speed`], [`Project::lift`]) refuses it by the bounds
1623 /// check it already had, [`Project::composite_span_at`] and
1624 /// [`Project::audio_lanes`] never look at it, and the three doors that
1625 /// could still put a picture on one -- [`Project::from_parts`],
1626 /// [`Project::place`], [`Project::append_clip`] -- say so by name.
1627 Subtitle,
1628}
1629
1630/// Which lane an operation acts on: a kind plus a 0-based position among the
1631/// lanes of that kind, so [`Lane::V1`] is the first video lane and
1632/// `Lane::new(LaneKind::Audio, 1)` is `A2`.
1633///
1634/// A handle, not the lane itself. It stays meaningful while lanes are added,
1635/// and one naming a lane that is not there reads as an empty lane and refuses
1636/// every mutation -- a front-end that always asks for `V1`/`A1` needs no
1637/// bounds check of its own.
1638#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1639pub struct Lane {
1640 pub kind: LaneKind,
1641 pub ord: usize,
1642}
1643
1644impl Lane {
1645 /// The first video lane: what a decoder plays and what an export renders.
1646 pub const V1: Lane = Lane::new(LaneKind::Video, 0);
1647 /// The first audio lane: what the audio worker plays.
1648 pub const A1: Lane = Lane::new(LaneKind::Audio, 0);
1649 /// The first subtitle lane -- the one a project has only once something
1650 /// added it ([`Project::add_lane`]); a project starts with `V1` and `A1`
1651 /// alone.
1652 pub const S1: Lane = Lane::new(LaneKind::Subtitle, 0);
1653
1654 pub const fn new(kind: LaneKind, ord: usize) -> Self {
1655 Self { kind, ord }
1656 }
1657
1658 /// `V1`, `A2`: how a lane is written in a header column and named in an
1659 /// error about it.
1660 pub fn label(self) -> String {
1661 let kind = match self.kind {
1662 LaneKind::Video => 'V',
1663 LaneKind::Audio => 'A',
1664 LaneKind::Subtitle => 'S',
1665 };
1666 format!("{kind}{}", self.ord + 1)
1667 }
1668}
1669
1670/// The shortest a cue may be trimmed to, in microseconds.
1671pub const MIN_CUE_US: i64 = 100_000;
1672
1673/// One cue of a caption lane as the timeline shows it: where it lands, which cue of which track it
1674/// is, and the part `window` of the cue's own clock that is shown.
1675#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1676pub struct CueSpan {
1677 pub start_us: i64,
1678 pub end_us: i64,
1679 pub track: usize,
1680 pub cue: usize,
1681 pub window: (i64, i64),
1682}
1683
1684/// One cue's saved word times: `(track, cue, [(start_us, end_us, word)])`.
1685pub type CueWordRow = (usize, usize, Vec<(i64, i64, String)>);
1686
1687/// A placed subtitle: a `[in_us, out_us)` window of one of the project's
1688/// subtitle tracks ([`Project::subtitles`], which is the *palette*), shown from
1689/// timeline frame [`start`](SubClip::start) for [`frames`](SubClip::frames)
1690/// frames. Never empty at either end.
1691///
1692/// A [`Clip`] with the two frame spaces swapped for the two clocks a subtitle
1693/// actually has, and placed by the same one number: the window is in the
1694/// microseconds every parser here speaks ([`crate::subtitle::Cue`]), the
1695/// placement is in timeline frames like everything else on a lane. So the lane
1696/// invariant is the lane's ([`subs_sorted_disjoint`] is
1697/// [`sorted_disjoint`] over the same arithmetic), a move is `start` and nothing
1698/// else, and only the two calls that change a *duration* -- a trim, and the
1699/// mapping out -- ever need the timeline's rate.
1700///
1701/// `Copy` for [`Clip`]'s reason: the palette is named by index, so a copy, a
1702/// paste and an undo snapshot are a plain assignment and can never dangle.
1703#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1704pub struct SubClip {
1705 /// Timeline frame its first frame is shown at.
1706 pub start: u32,
1707 /// How many timeline frames it covers; `>= 1`. Held rather than derived
1708 /// from the window because a [`Project`] has no frame rate -- the rate
1709 /// enters at the door of the two calls that need it -- and every placement
1710 /// question (where it ends, what it overlaps) is asked in frames.
1711 pub frames: u32,
1712 /// Index into [`Project::subtitles`]: *which* track's words these are.
1713 pub track: usize,
1714 /// The half-open window of that track it shows, in microseconds from the
1715 /// start of the track -- exactly the clock its [`crate::subtitle::Cue`]s are
1716 /// timed in, so no conversion stands between a cue and the window that
1717 /// keeps it.
1718 pub in_us: i64,
1719 pub out_us: i64,
1720 /// Group id: `Some` exactly when a hand put this caption in a group with
1721 /// clips on other lanes ([`Project::group_all`]) -- a caption arrives in
1722 /// no group, and what a cut cuts apart loses the one it had
1723 /// ([`sub_open_room`], for [`Clip::link`]'s reason). Sharing an id with a
1724 /// clip is what makes the caption move, trim and delete with it.
1725 pub link: Option<u32>,
1726}
1727
1728impl SubClip {
1729 /// One past the last timeline frame it covers -- [`Clip::end`]'s twin, and
1730 /// what every overlap question is asked of.
1731 pub fn end(&self) -> u32 {
1732 self.start + self.frames
1733 }
1734
1735 /// The whole of caption track `track`, whose last cue ends at `end_us`, as
1736 /// one placement at `fps` -- what a palette row dropped on a subtitle lane
1737 /// carries. The window is the frames' own length, not the track's: a track
1738 /// that ends between two frames (4.750 s on 143 frames) would otherwise be
1739 /// stretched over the frames it occupies, and every cue would show late by
1740 /// that fraction. The frames are the fewest that hold the last cue.
1741 pub fn whole_track(track: usize, end_us: i64, fps: f64) -> SubClip {
1742 let us_of = |f: u32| (f64::from(f) / fps * 1e6).round() as i64;
1743 let mut frames = ((end_us as f64) * fps / 1e6).ceil().clamp(1., f64::from(u32::MAX)) as u32;
1744 // The ceiling is at most one frame short, once the microsecond rounding is counted.
1745 if us_of(frames) < end_us {
1746 frames += 1;
1747 }
1748 let out_us = us_of(frames);
1749 SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }
1750 }
1751
1752 /// How much of its track it shows, in microseconds; `>= 1` by the
1753 /// never-empty invariant, and never more than [`MAX_WINDOW_US`] for one
1754 /// that came through a door.
1755 pub fn window_us(&self) -> i64 {
1756 self.out_us.saturating_sub(self.in_us)
1757 }
1758
1759 /// Where in its window the timeline frame `frame` falls, in microseconds --
1760 /// the cut a split, a ripple and a trim all land on.
1761 ///
1762 /// By proportion and not by the timeline's rate: the window and the frame
1763 /// count measure the same stretch of time, so the fraction of the frames
1764 /// before `frame` is the fraction of the microseconds before it. That is
1765 /// what lets a subtitle be cut by [`clear`]'s and [`open_room`]'s twins
1766 /// without either of them learning an fps.
1767 ///
1768 /// Total arithmetic, and clamped to the window it is cutting: the
1769 /// `saturating_mul` is what a `SubClip` built by a caller rather than a
1770 /// door gets (a hand-built one, a unit test, a future door that forgot the
1771 /// bound) -- a wrapped window would put a caption's clock *before* its own
1772 /// start, and the split that produced it would then hand back two halves
1773 /// whose windows do not meet. The clamp is the never-empty invariant
1774 /// restated: the answer is a point inside `[in_us, out_us]` or nothing.
1775 fn window_at(&self, frame: u32) -> i64 {
1776 let into = i64::from(frame.saturating_sub(self.start));
1777 let window = self.window_us().max(0);
1778 let at = window.saturating_mul(into) / i64::from(self.frames.max(1));
1779 self.in_us.saturating_add(at.min(window))
1780 }
1781}
1782
1783/// One lane: what it is and what it holds. A struct rather than a bare
1784/// `Vec<Clip>` because per-lane state is what the next slices add -- mute, a
1785/// compositing mode, a name -- and it belongs next to the clips it applies to.
1786#[derive(Clone, Debug, PartialEq)]
1787struct LaneData {
1788 kind: LaneKind,
1789 /// Sorted by `start` and disjoint ([`sorted_disjoint`]). Always empty on a
1790 /// [`LaneKind::Subtitle`] lane, which is what keeps every media path from
1791 /// ever seeing a subtitle: they all read this list.
1792 clips: Vec<Clip>,
1793 /// The same, for a subtitle lane ([`subs_sorted_disjoint`]), and always
1794 /// empty on a video or audio one. Beside the clips rather than an enum over
1795 /// them so that everything a lane *is* -- its place in the stack, its
1796 /// label, its undo snapshot, its removal -- stays one code path for all
1797 /// three kinds.
1798 subs: Vec<SubClip>,
1799 /// How loud this lane plays, in dB, `0.0` for one nobody has touched --
1800 /// [`Project::lane_gain_db`]. Whole-lane and whole-band, which is what
1801 /// makes it a different thing from a clip's equalizer: it moves everything
1802 /// on the track by the same amount, cuts included. Meaningless on a video
1803 /// lane, where it is kept at 0 and asked by nothing.
1804 gain_db: f32,
1805 /// Where this audio lane sits between the speakers, `-1.0..=1.0`, `0.0` the
1806 /// middle ([`Project::lane_pan`]); applied on top of each clip's own pan.
1807 pan: f32,
1808 /// The auto-ducks on this audio lane ([`Project::lane_duck_list`]): each
1809 /// drops the lane while the key lane it names is loud, so a lane can be
1810 /// ducked under several keys at once and the drops multiply. At most one per
1811 /// key, in the order they were set. Empty for every other lane.
1812 ducks: Vec<Duck>,
1813 /// The voice processors of this audio lane ([`Project::lane_voice`]): gate,
1814 /// noise reduction, compressor and de-esser, all off for a lane nobody has
1815 /// cleaned. Default on every other lane.
1816 voice: VoiceFx,
1817 /// Whether a video lane is left out of the picture, or a subtitle lane's
1818 /// words are left out of the screen and the export
1819 /// ([`Project::lane_hidden`]). Kept on the lane, not in a view, so that the
1820 /// editor and an export read one answer.
1821 hidden: bool,
1822 /// Whether an audio lane is silenced in the mix ([`Project::lane_muted`]).
1823 /// Its clips and its volume are untouched, so unmuting restores exactly
1824 /// what was there.
1825 muted: bool,
1826 /// Pure state for the front-end, which refuses edits to a locked lane. The
1827 /// engine's own operations ignore it ([`Project::lane_locked`]).
1828 locked: bool,
1829 /// The display label the user gave this lane ([`Project::lane_name`]); empty
1830 /// for none. The address (V1, A2) is unchanged by it.
1831 name: String,
1832}
1833
1834/// The longest lane name, in characters.
1835pub const MAX_LANE_NAME_CHARS: usize = 40;
1836
1837/// The three per-lane switches a save writes ([`Project::lane_flags`]), as one
1838/// value so that the file and the editor name them the same way.
1839#[derive(Clone, Copy, Debug, Default, PartialEq)]
1840pub struct LaneFlags {
1841 pub hidden: bool,
1842 pub muted: bool,
1843 pub locked: bool,
1844 /// An audio lane's pan ([`Project::lane_pan`]); carried here because it is saved and
1845 /// loaded with the switches.
1846 pub pan: f32,
1847}
1848
1849impl LaneData {
1850 fn new(kind: LaneKind, clips: Vec<Clip>) -> Self {
1851 Self {
1852 kind,
1853 clips,
1854 subs: Vec::new(),
1855 gain_db: 0.0,
1856 pan: 0.0,
1857 ducks: Vec::new(),
1858 voice: VoiceFx::default(),
1859 hidden: false,
1860 muted: false,
1861 locked: false,
1862 name: String::new(),
1863 }
1864 }
1865
1866 /// The two lanes a project starts with: `V1` then `A1`, in display order.
1867 /// One place, because a freshly opened file is exactly this pair.
1868 fn two_lanes(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<LaneData> {
1869 vec![
1870 LaneData::new(LaneKind::Video, video),
1871 LaneData::new(LaneKind::Audio, audio),
1872 ]
1873 }
1874}
1875
1876/// The placements one group id names, split by the two lists a lane holds:
1877/// what a drag, a trim and a delete each have to walk, now that a group may
1878/// hold a caption beside its clips ([`Project::group_all`]). A clip and a
1879/// caption of one group never share a lane -- a subtitle lane holds no `Clip`
1880/// -- so the pairs are `(lane storage index, index into that lane's list)`.
1881#[derive(Default)]
1882struct Members {
1883 clips: Vec<(usize, usize)>,
1884 subs: Vec<(usize, usize)>,
1885}
1886
1887impl Members {
1888 /// Whether the group is the one placement and no more: what a lift leaves
1889 /// behind, and what every whole-group question answers "not one" for.
1890 fn alone(&self) -> bool {
1891 self.clips.len() + self.subs.len() < 2
1892 }
1893}
1894
1895/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
1896#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1897pub enum Edge {
1898 /// Its first timeline frame; moving it changes where in the source the clip
1899 /// starts reading, so the picture behind the edge slides with it.
1900 Start,
1901 /// One past its last timeline frame; moving it only says how much of the
1902 /// source to keep.
1903 End,
1904}
1905
1906/// The two walls an edge may travel between, `(first, last)` timeline frame
1907/// inclusive, and which of them is the source's own media limit: its head
1908/// (for a start edge) or its tail (for an end edge). The other wall is a
1909/// neighbouring clip, the timeline's first frame, or the clip's own minimum
1910/// length -- never media. `lo_media`/`hi_media` say which, so a front-end can
1911/// tell a trim that ran out of source from one that ran into a clip.
1912#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1913pub struct TrimWalls {
1914 pub lo: u32,
1915 pub hi: u32,
1916 pub lo_media: bool,
1917 pub hi_media: bool,
1918}
1919
1920/// What stops an edge at one of its walls ([`Project::trim_bounds`]): the thing a
1921/// front-end names when a drag or a trim comes to rest there. Wherever a wall is
1922/// the frame a neighbour or the timeline sets, the clip sitting at that wall does
1923/// not say which, so this does.
1924#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1925pub enum WallBound {
1926 /// The source's own limit: its head for a start edge, its tail for an end
1927 /// edge. A clip that has run out of source.
1928 Source,
1929 /// The neighbouring clip on the same lane: the end of the one in front of a
1930 /// start edge, or the start of the one behind an end edge -- at this timeline
1931 /// frame.
1932 Neighbour(u32),
1933 /// The timeline's first frame, with no clip in front of the edge.
1934 Timeline,
1935 /// The clip's own minimum length: one source frame, at its rate.
1936 MinLength,
1937 /// The length a still image is held to -- the table's cap, which is not a
1938 /// source's end (a still has none to run out of).
1939 Cap,
1940}
1941
1942/// The length each source has on each kind of lane, in timeline frames: what a
1943/// trim measures its walls against. A picture and a sound of one file need not
1944/// end on the same frame ([`crate::playback`]'s audio-lane table), and a linked
1945/// take drags both edges together, so a trim of one lane has to hold the other
1946/// to the other's own length.
1947#[derive(Clone, Copy, Debug)]
1948pub struct SourceWalls<'a> {
1949 /// The length on a video lane (and on a subtitle lane, which has none).
1950 pub picture: &'a [u32],
1951 /// The length on an audio lane.
1952 pub sound: &'a [u32],
1953}
1954
1955impl<'a> SourceWalls<'a> {
1956 /// One table for both kinds of lane: for a caller that has only the one.
1957 pub fn same(frames: &'a [u32]) -> Self {
1958 Self {
1959 picture: frames,
1960 sound: frames,
1961 }
1962 }
1963
1964 /// The table a clip on a lane of `kind` is walled by.
1965 fn for_kind(&self, kind: LaneKind) -> &'a [u32] {
1966 if kind == LaneKind::Audio {
1967 self.sound
1968 } else {
1969 self.picture
1970 }
1971 }
1972}
1973
1974/// What a lane holds over one stretch of the timeline: either a placed clip or
1975/// a gap. Returned already trimmed to the position it was asked about, so a
1976/// caller can hand `len` straight to a decoder (or to a black-frame generator).
1977#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1978pub struct Span {
1979 /// Timeline frame the span starts at.
1980 pub start: u32,
1981 /// Frames it covers; `>= 1`.
1982 pub len: u32,
1983 /// `(source index, first source frame)`, or `None` for a gap -- which the
1984 /// engine renders as black frames and as silence.
1985 pub from: Option<(usize, u32)>,
1986 /// The rate the clip this came off plays at ([`Clip::speed`]);
1987 /// [`Speed::NORMAL`] for a gap, which has no source to run fast. `len` is
1988 /// timeline frames whatever it says -- the speed is how many *source* frames
1989 /// those cover ([`Span::source_len`]) and how a decoder's own frame numbers
1990 /// come back to the timeline.
1991 pub speed: Speed,
1992 /// The speed ramp of the clip this came off, when it has one ([`Clip::speed_keys`]),
1993 /// based at this span's first frame. A ramped span's [`speed`](Span::speed) is
1994 /// [`Speed::NORMAL`]: a constant rate would be wrong for it, and real time is what
1995 /// a decoder reads every frame at, so every mapping goes through
1996 /// [`source_offset`](Span::source_offset) instead.
1997 pub ramp: Option<SpeedRamp>,
1998 /// Whether the clip this came off plays backwards ([`Clip::reversed`]). Then
1999 /// `from` still names the source frame the span's first timeline frame shows --
2000 /// the highest of the frames it reads -- and every later frame is
2001 /// [`source_offset`](Span::source_offset) *below* it ([`Span::source_at`]); the
2002 /// offsets themselves, [`source_len`](Span::source_len) and
2003 /// [`timeline_at`](Span::timeline_at) count distance walked, as they do forwards.
2004 /// `false` for a gap.
2005 pub reverse: bool,
2006 /// The pitch in semitones of the clip this came off ([`Clip::pitch`]); `0` for a gap.
2007 pub pitch: i8,
2008}
2009
2010impl Span {
2011 /// One past the last timeline frame it covers.
2012 pub fn end(&self) -> u32 {
2013 self.start + self.len
2014 }
2015
2016 /// Source frames from this span's first frame to its `offset`th: the mapping
2017 /// `speed.source_at(offset)` is for a constant rate, and the ramp's integral when
2018 /// the span carries one. Added to the span's `from` source frame it gives the
2019 /// frame the timeline frame at `offset` shows.
2020 pub fn source_offset(&self, offset: u32) -> u32 {
2021 match &self.ramp {
2022 None => self.speed.source_at(offset),
2023 Some(ramp) => ramp.source_offset(offset),
2024 }
2025 }
2026
2027 /// The source frame the timeline frame `offset` into the span shows, given
2028 /// `first`, the span's own first one (`from`'s): up for a span that plays
2029 /// forwards, down for a reversed one.
2030 pub fn source_at(&self, first: u32, offset: u32) -> u32 {
2031 match self.reverse {
2032 false => first + self.source_offset(offset),
2033 true => first.saturating_sub(self.source_offset(offset)),
2034 }
2035 }
2036
2037 /// The half-open range of source frames this span reads, `first..end`, in the
2038 /// order they are numbered in the file whichever way they are played. `None` for
2039 /// a gap. The window a decoder is opened over, and an audio segment's.
2040 pub fn source_window(&self) -> Option<(usize, u32, u32)> {
2041 let (source, first) = self.from?;
2042 let len = self.source_len();
2043 Some(match self.reverse {
2044 false => (source, first, first + len),
2045 true => (source, (first + 1).saturating_sub(len), first + 1),
2046 })
2047 }
2048
2049 /// How many source frames it reads: what a decoder is asked for and how wide
2050 /// an audio window is. `len` at real time, and the one arithmetic both the
2051 /// picture and the sound go through, so they cannot disagree about where a
2052 /// speeded clip ends.
2053 pub fn source_len(&self) -> u32 {
2054 match self.from {
2055 // The last timeline frame's own source frame is the last one needed
2056 // -- never one more, which at a slow rate would read a frame the
2057 // next clip owns and at a fast one would decode a picture nothing
2058 // shows.
2059 Some(_) => self.source_offset(self.len.saturating_sub(1)) + 1,
2060 None => self.len,
2061 }
2062 }
2063
2064 /// Where a source frame of this span lands on the timeline: the stamp
2065 /// playback puts on a decoded frame, through the ceil half of the pair
2066 /// ([`Speed::timeline_at`]). `in_frame` is the span's own first source
2067 /// frame, so a frame before it stamps at the span's start.
2068 pub fn timeline_at(&self, source_frame: u32) -> u32 {
2069 let base = self.from.map_or(0, |(_, in_frame)| in_frame);
2070 let rel = source_frame.saturating_sub(base);
2071 self.start
2072 + match &self.ramp {
2073 None => self.speed.timeline_at(rel),
2074 Some(ramp) => ramp.timeline_at(rel),
2075 }
2076 }
2077}
2078
2079/// What one speeded audio segment asks of the worker: how many source frames to
2080/// consume per output frame, and how many seconds of timeline it has to fill.
2081/// [`Project::audio_speeds_from`] builds it; `None` there means real time and no
2082/// resampling at all.
2083#[derive(Clone, Copy, PartialEq, Debug)]
2084pub struct Stretch {
2085 /// Source frames per output frame -- the speed as a multiplier.
2086 pub step: f64,
2087 /// What the segment owes the timeline, which is what it is padded or
2088 /// trimmed to.
2089 pub timeline_secs: f64,
2090 /// The segment's speed ramp, when it has one: the stretch then follows the ramp's
2091 /// instantaneous rate rather than `step`, which is only the mean it falls back to.
2092 pub ramp: Option<SpeedRamp>,
2093 /// The timeline's frame rate, which the ramp's frames are counted in. The
2094 /// openers do not all know it, so the stretch carries it.
2095 pub fps: f64,
2096 /// Whether the segment's samples are played last to first
2097 /// ([`Clip::reversed`]). Then `step` is `1.0` when only the direction asks for a
2098 /// rate chain at all, and the window the segment names is the one to be reversed.
2099 pub reverse: bool,
2100 /// The pitch in semitones the segment is shifted by ([`Clip::pitch`]), `0` for none.
2101 /// The stretch then runs at `step / 2^(pitch/12)` and the resample at the same ratio
2102 /// up: the pitch moves, the length does not.
2103 pub pitch: i8,
2104}
2105
2106impl Stretch {
2107 /// Whether the segment is only played backwards, at the rate it was recorded:
2108 /// no change of time, so no stretch is built for it.
2109 pub fn is_straight(&self) -> bool {
2110 self.reverse && self.step == 1.0 && self.ramp.is_none() && self.pitch == 0
2111 }
2112
2113 /// The frequency ratio the segment's pitch shift is: `2^(pitch/12)`, `1.0` for none.
2114 pub fn pitch_ratio(&self) -> f64 {
2115 pitch_ratio(self.pitch)
2116 }
2117}
2118
2119/// The frequency ratio of a shift of `semitones`: `2^(semitones/12)`, so `12` is an octave up.
2120pub fn pitch_ratio(semitones: i8) -> f64 {
2121 (f64::from(semitones) / 12.0).exp2()
2122}
2123
2124/// What one audio segment's gain envelope is: [`Project::audio_fades_from`]
2125/// builds it off the clip's own [`Clip::fade_in`]/[`Clip::fade_out`], resolved
2126/// against where in the *clip* -- not the segment, which may start mid-clip
2127/// on a seek -- this segment's first frame lands.
2128#[derive(Clone, PartialEq, Debug)]
2129pub struct Fade {
2130 /// How many of the clip's own frames already played before this
2131 /// segment's first frame: `0` unless playback started mid-clip.
2132 pub elapsed: u32,
2133 /// The clip's [`Clip::fade_in`].
2134 pub fade_in: u32,
2135 /// The clip's [`Clip::fade_out`].
2136 pub fade_out: u32,
2137 /// The clip's own [`Clip::frames`] -- the envelope's whole width, of
2138 /// which this segment may only cover the tail.
2139 pub total: u32,
2140 /// The clip's [`Clip::gain_db`] as a linear multiplier, `1.0` for unity.
2141 /// It rides in the envelope because the envelope is what both the
2142 /// playback feeder and the export are handed, so the two cannot disagree.
2143 pub gain: f32,
2144 /// The left and right multipliers of the clip's pan and its lane's
2145 /// ([`pan_gains`]), `(1.0, 1.0)` for the middle. Only a stereo mix has a
2146 /// side to turn down; any other width plays it as it is.
2147 pub pan: (f32, f32),
2148 /// The clip's [`Clip::gain_keys`] as `(position, dB, ease)` triples, `None` for a
2149 /// clip with none. The position is clip-relative and in this envelope's own
2150 /// unit: timeline frames when [`Project::lane_fades_from`] builds it, audio
2151 /// frames once [`Fade::scaled`] has counted it. Shared, so the envelope
2152 /// stays cheap to hand around.
2153 pub curve: Option<std::sync::Arc<[(f64, f32, KeyEase)]>>,
2154}
2155
2156/// The left and right multipliers of a clip pan and a lane pan, each `-1.0..=1.0`: a
2157/// balance, where the side away from the pan is turned down along a quarter sine
2158/// (`cos(pan * pi/2)`, silent at the far end) and the near side is left alone,
2159/// so the middle is exactly unity.
2160impl Clip {
2161 /// [`Clip::pan`] as `-1.0..=1.0`.
2162 pub fn pan_value(&self) -> f32 {
2163 f32::from(self.pan) / 100.0
2164 }
2165}
2166
2167pub fn pan_gains(clip: f32, lane: f32) -> (f32, f32) {
2168 let side = |p: f32| {
2169 let p = p.clamp(-1.0, 1.0);
2170 (p.max(0.0) * std::f32::consts::FRAC_PI_2, (-p).max(0.0) * std::f32::consts::FRAC_PI_2)
2171 };
2172 let (cl, cr) = side(clip);
2173 let (ll, lr) = side(lane);
2174 // cos(pi/2) is not exactly 0 in f32: the far end is silence, so say so.
2175 let snap = |g: f32| if g < 1e-6 { 0.0 } else { g };
2176 (snap(cl.cos() * ll.cos()), snap(cr.cos() * lr.cos()))
2177}
2178
2179impl Fade {
2180 /// The gain at clip-relative frame `pos`, an equal-power curve on each
2181 /// edge that plays through unchanged (gain `1.0`) wherever neither ramp
2182 /// reaches: `sin(t * pi/2)` for `t` the fraction of the way through the
2183 /// ramp, so a fade lands on silence at its very first (or very last)
2184 /// frame and reaches unity smoothly rather than at a constant slope --
2185 /// the same curve [`Project::crossfade`] relies on to keep two clips'
2186 /// sum around one level through the join. Both ramps multiply where a
2187 /// clip is short enough for them to overlap.
2188 fn gain_at(&self, pos: u32) -> f32 {
2189 let mut g = self.gain;
2190 if let Some(curve) = &self.curve {
2191 g *= db_to_linear(lerp_db(curve, |&p| p, f64::from(pos)));
2192 }
2193 if self.fade_in > 0 && pos < self.fade_in {
2194 let t = pos as f32 / self.fade_in as f32;
2195 g *= (t * std::f32::consts::FRAC_PI_2).sin();
2196 }
2197 if self.fade_out > 0 {
2198 let out_start = self.total.saturating_sub(self.fade_out);
2199 if pos >= out_start {
2200 let remaining = self.total.saturating_sub(pos);
2201 let t = remaining as f32 / self.fade_out as f32;
2202 g *= (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin();
2203 }
2204 }
2205 g
2206 }
2207
2208 /// Multiplies `frames` in place -- `channels`-wide interleaved samples,
2209 /// starting at this segment's own frame `0` -- by [`Self::gain_at`].
2210 pub fn apply(&self, frames: &mut [f32], channels: usize) {
2211 for (i, block) in frames.chunks_mut(channels).enumerate() {
2212 let g = self.gain_at(self.elapsed.saturating_add(i as u32));
2213 for s in block.iter_mut() {
2214 *s *= g;
2215 }
2216 if channels == 2 && block.len() == 2 {
2217 block[0] *= self.pan.0;
2218 block[1] *= self.pan.1;
2219 }
2220 }
2221 }
2222
2223 /// Every field re-counted at `ratio` frames-out per frame-in, rounded to
2224 /// the nearest whole frame. [`Project::lane_fades_from`] builds a `Fade`
2225 /// in *timeline* frames ([`Clip::fade_in`]'s own unit, the fps every clip
2226 /// position is in) but [`Self::apply`] multiplies *audio* frames --
2227 /// `channels`-wide sample blocks at whatever rate the mix is running at,
2228 /// which is almost never the video's fps. Left unconverted, `elapsed` (an
2229 /// audio-frame count) raced past `total`/`fade_out` (fps-frame counts) a
2230 /// few milliseconds into any clip, so a fade-out silenced the rest of the
2231 /// clip outright and a fade-in finished before a listener's ear caught up
2232 /// -- audible on nothing shorter than a clip a few fps-frames long, which
2233 /// is why 338 green tests never once ran the two curves out of step.
2234 /// `ratio` is `sample_rate / fps`, applied once where the audio session
2235 /// first learns its own rate ([`crate::AudioSession::open_multi_streams_speed_at_fade`]).
2236 pub fn scaled(self, ratio: f64) -> Fade {
2237 let conv = |f: u32| (f64::from(f) * ratio).round() as u32;
2238 Fade {
2239 elapsed: conv(self.elapsed),
2240 fade_in: conv(self.fade_in),
2241 fade_out: conv(self.fade_out),
2242 total: conv(self.total),
2243 gain: self.gain,
2244 pan: self.pan,
2245 curve: self.curve.as_ref().map(|c| {
2246 c.iter()
2247 .map(|&(x, db, ease)| (x * ratio, db, ease))
2248 .collect::<Vec<_>>()
2249 .into()
2250 }),
2251 }
2252 }
2253}
2254
2255/// What a save writes and a load takes back: the sources, every lane in
2256/// display order with its kind, and the equalizer and colour tables their clips
2257/// index into -- [`Project::without_orphan_sources`] out,
2258/// [`Project::from_parts`] in.
2259pub type Parts = (
2260 Vec<Source>,
2261 Vec<(LaneKind, Vec<Clip>)>,
2262 Vec<EqParams>,
2263 Vec<ColorParams>,
2264 Vec<TransformParams>,
2265);
2266
2267/// The next revision id to hand out. Process-wide, so two projects never share
2268/// an id and a revision read from one session means nothing in another.
2269static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2270
2271fn next_revision() -> u64 {
2272 NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2273}
2274
2275/// How many undo steps a project keeps. One gesture is one step, so 100 is past
2276/// any chain a person walks back by hand, and the oldest step is dropped rather
2277/// than the history growing without end: a snapshot is the whole lane list plus
2278/// the palette and the project's own settings, so on a 1394-clip jumpcut
2279/// timeline this is a bounded ~10 MB instead of a leak that grows for as long
2280/// as the session lasts.
2281const HISTORY_CAP: usize = 100;
2282
2283/// The project's own settings, as one value: the header a `.edith` file carries
2284/// beside the edit list, and what every undo step restores beside the lanes.
2285/// None of it is the media's own -- the scaffolding file's picture and rate
2286/// ([`PlaybackSession::native`]) stay on the session and are never rolled back.
2287#[derive(Clone, Debug, PartialEq)]
2288pub(crate) struct ProjectSettings {
2289 /// The canvas every clip is composed onto: the project resolution, which a
2290 /// clip of another size is placed onto rather than refused for.
2291 pub(crate) resolution: (u32, u32),
2292 /// The rate the timeline is cut at, which every clip and source is
2293 /// conformed to ([`Project::retime`]).
2294 pub(crate) frame_rate: f64,
2295 /// Which encoder an export of this project opens its picture on
2296 /// ([`crate::export::EncoderSeat`]).
2297 pub(crate) encoder_seat: crate::export::EncoderSeat,
2298 /// The rate the mix was picked to run at, or `None` for the one the first
2299 /// audio source derives.
2300 pub(crate) sample_rate: Option<u32>,
2301 /// Whether the picture is decoded from the stand-ins ([`crate::proxy`]).
2302 pub(crate) proxies: bool,
2303 /// Whether a source that wants a stand-in gets one made for it as it
2304 /// arrives ([`crate::proxy::wanted`]).
2305 pub(crate) auto_proxies: bool,
2306 /// Which HDR-to-SDR rendition the picture is watched and exported in.
2307 pub(crate) tone: crate::tonemap::Preset,
2308 /// The master limiter every lane's sound is summed through.
2309 pub(crate) limiter: Limiter,
2310 /// How burned captions animate, the default for `burn_captions`.
2311 pub(crate) caption_style: crate::captionanim::CaptionStyle,
2312 /// The free-text notes the project carries (v52). Empty until somebody writes one.
2313 pub(crate) notes: String,
2314 /// How long a still image is placed for, in seconds (v52).
2315 pub(crate) still_secs: f64,
2316}
2317
2318impl ProjectSettings {
2319 /// What a project built by hand carries before its constructor names the
2320 /// canvas: the defaults every fresh open has -- nobody has picked stand-ins
2321 /// (the films themselves are cut), an encoder or a mix rate, and the
2322 /// rendition and limiter are the reference ones. Every door that builds a
2323 /// session chains [`Project::with_canvas`] straight after, so the zero
2324 /// canvas here is never a project anybody plays from.
2325 fn placeholder() -> Self {
2326 Self {
2327 resolution: (0, 0),
2328 frame_rate: 0.0,
2329 encoder_seat: crate::export::EncoderSeat::default(),
2330 sample_rate: None,
2331 proxies: false,
2332 auto_proxies: true,
2333 tone: crate::tonemap::Preset::default(),
2334 limiter: Limiter::default(),
2335 caption_style: crate::captionanim::CaptionStyle::default(),
2336 notes: String::new(),
2337 still_secs: STILL_DEFAULT_SECS,
2338 }
2339 }
2340}
2341
2342/// One undo step: the lanes, the subtitle palette and the project's own
2343/// settings exactly as they were before the edit that pushed it. Whole values
2344/// rather than the lane list alone, so an undo (or a redo) restores all three
2345/// together and no half of one edit can come back without the others -- which
2346/// is what lets a subtitle removal reindex every placement and still undo: the
2347/// restored palette names the very tracks the restored placements index.
2348/// What a freshly pushed undo step displaced: the redo branch its edit cleared
2349/// and, when the cap was full, the oldest step it evicted. Moved, never cloned.
2350#[derive(Clone, Debug)]
2351struct PendingStep {
2352 redo: Vec<Snapshot>,
2353 evicted: Option<Snapshot>,
2354}
2355
2356#[derive(Clone, Debug)]
2357struct Snapshot {
2358 /// The revision of the state this step restores ([`Project::revision`]).
2359 revision: u64,
2360 /// The name of the edit that pushed this step ([`Project::name_step`]): what
2361 /// Undo and Redo say. `None` for a step nobody named, which reads as plain "Undo".
2362 /// It travels with the step, so an undo's redo entry carries the same name.
2363 label: Option<String>,
2364 lanes: Vec<LaneData>,
2365 subtitles: Vec<SubtitleTrack>,
2366 cue_edits: Vec<(usize, usize, String)>,
2367 cue_adds: Vec<AddedCue>,
2368 titles: Vec<Title>,
2369 chapters: Vec<Chapter>,
2370 markers: Vec<Marker>,
2371 settings: ProjectSettings,
2372 /// The files the clips index into, as the step had them: a relink is undone by putting the
2373 /// old path back here. A [`Source`] is a path and a stream index, so a copy is cheap.
2374 sources: Vec<Source>,
2375 /// The library's bins (v51).
2376 bins: Vec<Bin>,
2377 /// The sequence list: which is active, every name, and the parked ones' data.
2378 seq: Seqs,
2379}
2380
2381/// The source list an undo or redo step puts back: the step's own list, and past its end the
2382/// entries the step never knew of (imported after it). No clip in the step names one of those,
2383/// so keeping them leaves every index the step holds valid, and an undone edit leaves an import
2384/// in the library as an import always does.
2385fn restored_sources(step: Vec<Source>, now: &[Source]) -> Vec<Source> {
2386 let mut out = step;
2387 if now.len() > out.len() {
2388 out.extend_from_slice(&now[out.len()..]);
2389 }
2390 out
2391}
2392
2393/// The redo stack moved out by [`Project::take_redo`]: opaque, and only
2394/// [`Project::restore_redo`] reads it back.
2395pub struct RedoCheckpoint(Vec<Snapshot>);
2396
2397/// A cue somebody added to a subtitle track, which no file has: its track, its
2398/// times on the track's own clock and its words. Kept beside the file's cue
2399/// overrides ([`Project::cue_adds`]) because a `(track, cue, text)` override
2400/// names a cue by where the file has it, and an added cue has no such place.
2401#[derive(Clone, Debug, PartialEq, Eq)]
2402pub struct AddedCue {
2403 pub track: usize,
2404 pub start_us: i64,
2405 pub end_us: i64,
2406 pub text: String,
2407}
2408
2409/// One gap a close-all sweep left open, with the frame it still starts on and
2410/// the same refusal a single [`Project::gap_take_scope`] close would have said.
2411#[derive(Clone, Debug, PartialEq, Eq)]
2412pub struct GapSkip {
2413 pub start: u32,
2414 pub reason: String,
2415}
2416
2417/// What [`Project::close_all_gaps_on_lane`] did: closed gaps count as edits,
2418/// skipped gaps are the take-safety refusals the sweep did not hide.
2419#[derive(Clone, Debug, Default, PartialEq, Eq)]
2420pub struct GapSweep {
2421 pub closed: usize,
2422 pub skipped: Vec<GapSkip>,
2423}
2424
2425/// A chapter marker: a named frame on the timeline, the point a viewer's chapter
2426/// list jumps to. Sorted by frame, at most one per frame ([`Project::chapters`]).
2427/// Saved as `chapter` lines ([`crate::edith`]).
2428#[derive(Clone, Debug, PartialEq, Eq)]
2429pub struct Chapter {
2430 /// The timeline frame the chapter starts on.
2431 pub frame: u32,
2432 /// What the chapter is called in the list.
2433 pub title: String,
2434}
2435
2436/// The longest chapter name, in characters: the most a video platform's chapter
2437/// list shows.
2438pub const MAX_CHAPTER_CHARS: usize = 100;
2439
2440/// Whether `chapter` is a chapter the project may hold: the checks
2441/// [`Project::add_chapter`] makes and the `.edith` loader makes of every `chapter` line.
2442pub fn check_chapter(chapter: &Chapter) -> crate::Result<()> {
2443 if chapter.title.trim().is_empty() {
2444 return Err("a chapter needs a name".into());
2445 }
2446 if chapter.title.chars().count() > MAX_CHAPTER_CHARS {
2447 return Err(format!("a chapter name holds at most {MAX_CHAPTER_CHARS} characters").into());
2448 }
2449 Ok(())
2450}
2451
2452/// A marker's colour: the small fixed palette an editor's marker strip draws.
2453#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2454pub enum MarkerColor {
2455 Red,
2456 Orange,
2457 Yellow,
2458 Green,
2459 #[default]
2460 Blue,
2461 Purple,
2462}
2463
2464impl MarkerColor {
2465 /// Every colour, in palette order.
2466 pub const ALL: [MarkerColor; 6] = [
2467 MarkerColor::Red,
2468 MarkerColor::Orange,
2469 MarkerColor::Yellow,
2470 MarkerColor::Green,
2471 MarkerColor::Blue,
2472 MarkerColor::Purple,
2473 ];
2474
2475 /// The name the `.edith` file and the MCP tools use.
2476 pub fn name(self) -> &'static str {
2477 match self {
2478 MarkerColor::Red => "red",
2479 MarkerColor::Orange => "orange",
2480 MarkerColor::Yellow => "yellow",
2481 MarkerColor::Green => "green",
2482 MarkerColor::Blue => "blue",
2483 MarkerColor::Purple => "purple",
2484 }
2485 }
2486
2487 /// The colour called `name` (any case), if it is one of the palette.
2488 pub fn from_name(name: &str) -> Option<MarkerColor> {
2489 MarkerColor::ALL.into_iter().find(|c| c.name().eq_ignore_ascii_case(name.trim()))
2490 }
2491
2492 /// The colour after this one in the palette, wrapping: what the GUI's "next colour" steps through.
2493 pub fn next(self) -> MarkerColor {
2494 let i = MarkerColor::ALL.iter().position(|c| *c == self).unwrap_or(0);
2495 MarkerColor::ALL[(i + 1) % MarkerColor::ALL.len()]
2496 }
2497}
2498
2499/// A comment marker: a named, coloured point on the timeline with an optional note, or a
2500/// range when `length` is not 0. Separate from a [`Chapter`]; it moves with the picture the
2501/// same way. Sorted by frame; several may share a frame ([`Project::markers`]). Saved as
2502/// `marker` lines ([`crate::edith`]).
2503#[derive(Clone, Debug, PartialEq, Eq)]
2504pub struct Marker {
2505 /// The timeline frame the marker starts on.
2506 pub frame: u32,
2507 /// How many frames it spans; 0 is a point.
2508 pub length: u32,
2509 pub name: String,
2510 /// A free-text note; may be empty.
2511 pub note: String,
2512 pub color: MarkerColor,
2513}
2514
2515impl Marker {
2516 /// The frame a range marker ends on (exclusive); its start for a point.
2517 pub fn end(&self) -> u32 {
2518 self.frame.saturating_add(self.length)
2519 }
2520}
2521
2522/// The longest marker name, in characters.
2523pub const MAX_MARKER_NAME_CHARS: usize = 100;
2524/// The longest marker note, in characters.
2525pub const MAX_MARKER_NOTE_CHARS: usize = 2000;
2526
2527/// Whether `marker` is a marker the project may hold: the checks [`Project::add_marker`]
2528/// makes and the `.edith` loader makes of every `marker` line.
2529pub fn check_marker(marker: &Marker) -> crate::Result<()> {
2530 if marker.name.trim().is_empty() {
2531 return Err("a marker needs a name".into());
2532 }
2533 if marker.name.chars().count() > MAX_MARKER_NAME_CHARS {
2534 return Err(format!("a marker name holds at most {MAX_MARKER_NAME_CHARS} characters").into());
2535 }
2536 if marker.note.chars().count() > MAX_MARKER_NOTE_CHARS {
2537 return Err(format!("a marker note holds at most {MAX_MARKER_NOTE_CHARS} characters").into());
2538 }
2539 if marker.frame.checked_add(marker.length).is_none_or(|e| e > MAX_TITLE_END) {
2540 return Err("a marker runs past the last frame there is".into());
2541 }
2542 Ok(())
2543}
2544
2545/// The longest text a title can hold, in characters.
2546pub const MAX_TITLE_CHARS: usize = 500;
2547
2548/// The furthest frame a title may end on. Far past any timeline anyone cuts,
2549/// and far below `u32::MAX`, so `start + frames` cannot wrap.
2550pub const MAX_TITLE_END: u32 = 100_000_000;
2551
2552/// A text overlay on the timeline: a title card over black, or a caption such
2553/// as a lower third over the picture. Titles are a project-level list, not a
2554/// lane: they are drawn over the composed picture (black where no clip plays),
2555/// in list order, so a later title sits on top of an earlier one. Saved as
2556/// `title` lines ([`crate::edith`]).
2557#[derive(Clone, Debug, PartialEq, Eq)]
2558pub struct Title {
2559 /// The first timeline frame the title shows on.
2560 pub start: u32,
2561 /// How many frames it shows for; `>= 1`.
2562 pub frames: u32,
2563 /// The words, with `\n` as a line break. Non-empty, at most
2564 /// [`MAX_TITLE_CHARS`] characters.
2565 pub text: String,
2566 /// How the words are set. Its size is kept inside [`SIZE_RANGE`].
2567 pub style: TextStyle,
2568 /// Frames the title takes to come up from nothing: the first frame shows
2569 /// `1 / (fade_in + 1)` of it. `0` for no fade-in.
2570 pub fade_in: u32,
2571 /// Frames the title takes to go back to nothing, counted off the end.
2572 /// `0` for no fade-out.
2573 pub fade_out: u32,
2574 /// The animation it comes in with ([`crate::titleanim`]); `None` for none.
2575 pub in_anim: TitleAnim,
2576 /// The animation it goes out with; the reverse of `in_anim`'s motion.
2577 pub out_anim: TitleAnim,
2578 /// How many frames each animation takes; `>= 1` when either is set and at most `frames`.
2579 pub anim_frames: u32,
2580}
2581
2582impl Title {
2583 /// One past the last frame the title covers.
2584 pub fn end(&self) -> u32 {
2585 self.start.saturating_add(self.frames)
2586 }
2587
2588 /// How much of the title shows on timeline frame `frame`, 0 to 255: its
2589 /// fades and animations ramp it up and down, and a frame outside the title shows none.
2590 pub fn alpha_at(&self, frame: u32) -> u8 {
2591 self.motion_at(frame).map_or(0, |m| m.alpha)
2592 }
2593}
2594
2595/// A one-click look for a title. The app's title card and MCP's `preset` argument both
2596/// apply these, so the two never disagree on what "lower third" means.
2597#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2598pub enum TitlePreset {
2599 LowerThird,
2600 Centered,
2601 CaptionBar,
2602}
2603
2604impl TitlePreset {
2605 /// Every preset, in the order the app lists them.
2606 pub const ALL: [TitlePreset; 3] = [TitlePreset::LowerThird, TitlePreset::Centered, TitlePreset::CaptionBar];
2607
2608 /// The word that names the preset in MCP: `lower_third`, `centered` or `caption_bar`.
2609 pub fn key(self) -> &'static str {
2610 match self {
2611 TitlePreset::LowerThird => "lower_third",
2612 TitlePreset::Centered => "centered",
2613 TitlePreset::CaptionBar => "caption_bar",
2614 }
2615 }
2616
2617 /// The preset a word names, if it names one.
2618 pub fn from_key(word: &str) -> Option<TitlePreset> {
2619 TitlePreset::ALL.into_iter().find(|p| p.key() == word)
2620 }
2621
2622 /// The style and the fade length in seconds (in and out).
2623 pub fn look(self) -> (TextStyle, f64) {
2624 let base = TextStyle::default();
2625 match self {
2626 TitlePreset::LowerThird => (
2627 TextStyle {
2628 size: 45,
2629 outline: Outline::None,
2630 boxed: true,
2631 place: Place::Bottom,
2632 hplace: HPlace::Left,
2633 align: Align::Left,
2634 weight: Weight::Bold,
2635 ..base
2636 },
2637 0.5,
2638 ),
2639 TitlePreset::Centered => (TextStyle { size: 100, outline: Outline::Thin, boxed: false, place: Place::Centre, ..base }, 0.5),
2640 TitlePreset::CaptionBar => (TextStyle { size: 40, outline: Outline::None, boxed: true, place: Place::Bottom, ..base }, 0.0),
2641 }
2642 }
2643}
2644
2645impl Title {
2646 /// `self` in `preset`'s look. The words and timing stay; fades are held to half the
2647 /// title's length, so in and out never cross.
2648 pub fn apply_preset(&mut self, preset: TitlePreset, fps: f64) {
2649 let (style, fade) = preset.look();
2650 let fade = ((fade * fps).round() as u32).min(self.frames / 2);
2651 self.style = style;
2652 self.fade_in = fade;
2653 self.fade_out = fade;
2654 }
2655}
2656
2657/// Whether `title` is a title the project may hold: the checks [`Project::add_title`]
2658/// makes and the `.edith` loader makes of every `title` line.
2659pub fn check_title(title: &Title) -> crate::Result<()> {
2660 if title.frames == 0 {
2661 return Err("a title must show for at least one frame".into());
2662 }
2663 if title.text.trim().is_empty() {
2664 return Err("a title needs some text".into());
2665 }
2666 if title.text.chars().count() > MAX_TITLE_CHARS {
2667 return Err(format!("a title holds at most {MAX_TITLE_CHARS} characters").into());
2668 }
2669 if title.end() > MAX_TITLE_END {
2670 return Err(format!("a title ends past frame {MAX_TITLE_END}").into());
2671 }
2672 if title.fade_in > title.frames || title.fade_out > title.frames {
2673 return Err("a title's fades are no longer than the title".into());
2674 }
2675 let animated = title.in_anim != TitleAnim::None || title.out_anim != TitleAnim::None;
2676 if animated && (title.anim_frames == 0 || title.anim_frames > title.frames) {
2677 return Err("a title's animations last at least one frame and no longer than the title".into());
2678 }
2679 if !(SIZE_RANGE.0..=SIZE_RANGE.1).contains(&title.style.size) {
2680 return Err(format!(
2681 "a title's size is {}..={} permille of the frame height",
2682 SIZE_RANGE.0, SIZE_RANGE.1
2683 )
2684 .into());
2685 }
2686 Ok(())
2687}
2688
2689/// One clip [`Project::clamp_to_walls`] shortened: its lane, its source, and its
2690/// out-point before (`from`) and after (`to`), in source frames.
2691#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2692pub struct WallClamp {
2693 pub lane: Lane,
2694 pub source: usize,
2695 pub from: u32,
2696 pub to: u32,
2697}
2698
2699/// The edit list plus its undo history.
2700#[derive(Clone, Debug)]
2701pub struct Project {
2702 /// Append-only: never popped, never reordered. See the module docs.
2703 sources: Vec<Source>,
2704 /// In display order, which is the order [`Lane::ord`] counts in: the nth
2705 /// lane of a kind here is that kind's `ord` n. Never empty.
2706 lanes: Vec<LaneData>,
2707 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
2708 eq: Vec<EqParams>,
2709 /// The same, for [`Clip::color`].
2710 color: Vec<ColorParams>,
2711 /// The same, for [`Clip::transform`].
2712 transform: Vec<TransformParams>,
2713 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
2714 /// whole lane list, the subtitle palette and the project's own settings,
2715 /// so adding a lane undoes as well and so does picking a resolution. Bounded
2716 /// by [`HISTORY_CAP`]: at the cap the oldest step goes.
2717 history: Vec<Snapshot>,
2718 /// Snapshots `undo` has stepped past; `redo` pops one. Cleared by
2719 /// [`Project::snapshot`], since a fresh edit invalidates whatever branch
2720 /// the undone steps came from. Not saved to `.edith`, matching `history`.
2721 redo: Vec<Snapshot>,
2722 /// Every snapshot pushed since the project was made, evicted ones included:
2723 /// [`Project::snapshot`] bumps it on each push. A caller that measures a
2724 /// batch by the history's length cannot, once the cap holds that length at
2725 /// [`HISTORY_CAP`]; this count keeps rising, so a batch's pushes are the
2726 /// difference of two reads. Not saved to `.edith`, and an undo never rolls
2727 /// it back.
2728 pushes: u64,
2729 /// Which state the project is in, as an id no other state of any project
2730 /// has ([`Project::revision`]). Every edit takes a fresh one and every undo
2731 /// or redo puts back the one its step carries, so a caller that saved at one
2732 /// revision knows whether a later undo has walked back to it.
2733 revision: u64,
2734 /// Set by [`Project::begin_batch`]: while it holds, the first snapshot of the
2735 /// batch is the only one kept, so the batch is one undo step however many edits it makes.
2736 batching: bool,
2737 /// Whether the open batch has pushed its one snapshot yet. An undo or redo clears it,
2738 /// since the state it protects is then not the one the batch started from.
2739 batch_snapped: bool,
2740 /// What the newest step pushed took out of the way, so [`Project::settle`]
2741 /// can put it back should that step turn out to have changed nothing. `None`
2742 /// before any step and after an undo or redo.
2743 pending: Option<PendingStep>,
2744 /// Set by [`Project::hold_history`]: while it holds, a snapshot keeps every step
2745 /// (the history may run past [`HISTORY_CAP`]) so a trial batch that is rolled
2746 /// back takes its own steps off again and drops nothing.
2747 hold_cap: bool,
2748 /// Never rolled back by an undo: an id retired by an undone split must not
2749 /// come back and group two clips that were never together.
2750 next_link: u32,
2751 /// The subtitle tracks this timeline shows, in the order they were added.
2752 /// Saved as a *reference* to the file the cues came out of
2753 /// ([`crate::subtitle`]). In the history snapshots since the widened
2754 /// [`Snapshot`]: a placement names a track by index into this list, so a
2755 /// removal that reindexes the placements can only undo together with the
2756 /// palette it removed the row from.
2757 subtitles: Vec<SubtitleTrack>,
2758 /// The cue overrides: `(track, cue, text)`, the track by its position in
2759 /// `subtitles` and the cue by its position in that track. Saved as `cue`
2760 /// lines ([`crate::edith`]) and in every snapshot, so an undo takes a retype
2761 /// back with the words it changed.
2762 cue_edits: Vec<(usize, usize, String)>,
2763 /// The cues added to a track ([`AddedCue`]), in the order they were added.
2764 /// Each sits in its track's cue list at its own start, and a save writes
2765 /// them as `cueadd` lines. In every snapshot, as the overrides are.
2766 cue_adds: Vec<AddedCue>,
2767 /// The title cards and text overlays, in draw order: sorted by start, and
2768 /// overlaps allowed. In every snapshot, as the subtitle palette is.
2769 titles: Vec<Title>,
2770 chapters: Vec<Chapter>,
2771 /// The comment markers, sorted by frame ([`Marker`]). In every snapshot, as the
2772 /// chapters are.
2773 markers: Vec<Marker>,
2774 /// The project's own settings ([`ProjectSettings`]) -- the canvas, the
2775 /// rate, the proxies switches, the encoder seat, the mix rate, the
2776 /// rendition and the limiter. In every snapshot, so each of them undoes
2777 /// like a lane edit: they are the header of the project's own `.edith`
2778 /// file, not this machine's, and a pick a ctrl+z could not take back
2779 /// would be the one setting with no way out.
2780 settings: ProjectSettings,
2781 /// The sequences ([`sequence`]): the active one is the fields above, the rest are parked here.
2782 seq: Seqs,
2783 /// The library's bins (v51), in creation order. In every snapshot.
2784 bins: Vec<Bin>,
2785 /// The next bin id; never rolled back, so an id is never reused.
2786 bin_next: u32,
2787 /// The next sequence id; never rolled back, so an id is never reused.
2788 seq_next: u32,
2789 /// The expanded copy of the active sequence playback reads ([`Project::render_view`]).
2790 flat: FlatCache,
2791}
2792
2793impl Project {
2794 /// `V1` and `A1`, one clip each covering the whole of `path` and the two
2795 /// grouped -- the state of a freshly opened video, where the timeline is the
2796 /// source. `frame_count` of 0 would break the never-empty invariant, so it
2797 /// is clamped to one frame.
2798 pub fn single(path: impl AsRef<Path>, frame_count: u32) -> Self {
2799 let clip = Clip {
2800 speed_keys: Vec::new(),
2801 reversed: false,
2802 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2803 angle: Default::default(),
2804 fade_in: 0,
2805 fade_out: 0,
2806 transition_out: 0,
2807 transition_kind: Default::default(),
2808 visualizer: 0,
2809 viz_paint: 0,
2810 gain_db: 0.0,
2811 gain_keys: Vec::new(),
2812 pan: 0,
2813 pitch: 0,
2814 transform_keys: Vec::new(),
2815 opacity_keys: Vec::new(),
2816 color_keys: Vec::new(),
2817 effects: Vec::new(),
2818 start: 0,
2819 in_frame: 0,
2820 out_frame: frame_count.max(1),
2821 source: 0,
2822 link: Some(0),
2823 eq: None,
2824 color: None,
2825 transform: None,
2826 fit: FitPolicy::default(),
2827 speed: Speed::NORMAL,
2828 };
2829 Self {
2830 // A file is opened on its first audio stream: nothing has picked
2831 // one yet, and every file with audio at all has that one.
2832 sources: vec![Source::new(path, 0)],
2833 lanes: LaneData::two_lanes(vec![clip.clone()], vec![clip]),
2834 eq: Vec::new(),
2835 color: Vec::new(),
2836 transform: Vec::new(),
2837 history: Vec::new(),
2838 redo: Vec::new(),
2839 pushes: 0,
2840 revision: next_revision(),
2841 batching: false,
2842 batch_snapped: false,
2843 pending: None,
2844 hold_cap: false,
2845 next_link: 1,
2846 subtitles: Vec::new(),
2847 cue_edits: Vec::new(),
2848 cue_adds: Vec::new(),
2849 titles: Vec::new(),
2850 chapters: Vec::new(),
2851 markers: Vec::new(),
2852 settings: ProjectSettings::placeholder(),
2853 seq: Seqs::single(),
2854 bins: Vec::new(),
2855 bin_next: 1,
2856 seq_next: 1,
2857 flat: FlatCache::default(),
2858 }
2859 }
2860
2861 /// A project rebuilt from a saved edit list -- the load half of
2862 /// [`crate::edith`]. The lanes come in display order, each with its kind, and
2863 /// an `ord` is a lane's position among the lanes of that kind, exactly as
2864 /// [`Project::lanes`] hands them back. History is *not* saved, so
2865 /// [`Project::undo`] is `false` until the first edit of the new session.
2866 /// This is the one door untrusted parts come in through, so every invariant
2867 /// every other constructor keeps is checked here, by name and in release:
2868 /// no lanes at all, an empty clip, a clip naming a source (or an equalizer,
2869 /// or a colour) that is not there, a clip whose end overflows, a lane that is
2870 /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
2871 /// below.
2872 ///
2873 /// A project whose lanes are all *empty* is not among them: an emptied
2874 /// timeline is a project like any other -- it plays black and silent, it
2875 /// saves, and it loads back. What a project cannot be is laneless, because
2876 /// [`Project::lanes`] is what a front-end lays out and what every `Lane`
2877 /// handle indexes into.
2878 pub fn from_parts(
2879 sources: Vec<Source>,
2880 lanes: Vec<(LaneKind, Vec<Clip>)>,
2881 eq: Vec<EqParams>,
2882 color: Vec<ColorParams>,
2883 transform: Vec<TransformParams>,
2884 ) -> crate::Result<Self> {
2885 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
2886 return Err(format!("eq {bad} holds a band that is not a finite number").into());
2887 }
2888 if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
2889 return Err(format!("color {bad} holds a value that is not a finite number").into());
2890 }
2891 if let Some(bad) = transform.iter().position(|p| !transform_finite(p)) {
2892 return Err(format!(
2893 "transform {bad} holds a value that is not a finite number in its range"
2894 )
2895 .into());
2896 }
2897 if lanes.is_empty() {
2898 return Err("no lanes at all: that is not a project".into());
2899 }
2900 let lanes: Vec<LaneData> = lanes
2901 .into_iter()
2902 .map(|(kind, clips)| LaneData::new(kind, clips))
2903 .collect();
2904 for (data, lane) in lanes.iter().zip(handles(&lanes)) {
2905 let name = lane.label();
2906 // A subtitle lane carries words and never a picture
2907 // ([`LaneKind::Subtitle`]); a file that puts one there names a
2908 // source on a lane that has nothing to play it with, and every
2909 // media path below would then read a clip off a lane it does not
2910 // know about.
2911 if data.kind == LaneKind::Subtitle && !data.clips.is_empty() {
2912 return Err(format!(
2913 "{name} is a subtitle track and holds {} media clip(s): a picture cannot play on one",
2914 data.clips.len()
2915 )
2916 .into());
2917 }
2918 for c in &data.clips {
2919 // The setters' own rules, which the file loader enforces too: a
2920 // picture has no volume of its own and only a picture is placed
2921 // by keys, and a clip gain outside its range is refused on the way
2922 // back in. A clip that breaks one would save a file that will not
2923 // load.
2924 if data.kind == LaneKind::Video && c.gain_db != 0.0 {
2925 return Err(format!(
2926 "{name} clip at {} has a gain: a picture has no volume of its own",
2927 c.start
2928 )
2929 .into());
2930 }
2931 if data.kind == LaneKind::Audio && !(c.opacity_keys.is_empty() && c.color_keys.is_empty()) {
2932 return Err(format!(
2933 "{name} clip at {} has opacity or colour keys: only a picture is animated by them",
2934 c.start
2935 )
2936 .into());
2937 }
2938 if data.kind == LaneKind::Audio && !c.transform_keys.is_empty() {
2939 return Err(format!(
2940 "{name} clip at {} has placement keys: only a picture is placed by them",
2941 c.start
2942 )
2943 .into());
2944 }
2945 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&c.gain_db) {
2946 return Err(format!(
2947 "{name} clip at {} has a gain of {} dB, outside its range",
2948 c.start, c.gain_db
2949 )
2950 .into());
2951 }
2952 if c.out_frame <= c.in_frame {
2953 return Err(format!(
2954 "{name} clip at {} plays the empty range [{}, {})",
2955 c.start, c.in_frame, c.out_frame
2956 )
2957 .into());
2958 }
2959 if c.source >= sources.len() && !is_sequence_source(c.source) {
2960 return Err(format!(
2961 "{name} clip at {} names source {} of {}",
2962 c.start,
2963 c.source,
2964 sources.len()
2965 )
2966 .into());
2967 }
2968 if c.start.checked_add(c.frames()).is_none() {
2969 return Err(format!(
2970 "{name} clip at {} runs past the last frame there is",
2971 c.start
2972 )
2973 .into());
2974 }
2975 if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
2976 return Err(format!(
2977 "{name} clip at {} names eq {} of {}",
2978 c.start,
2979 c.eq.unwrap_or_default(),
2980 eq.len()
2981 )
2982 .into());
2983 }
2984 if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
2985 return Err(format!(
2986 "{name} clip at {} names color {} of {}",
2987 c.start,
2988 c.color.unwrap_or_default(),
2989 color.len()
2990 )
2991 .into());
2992 }
2993 if c.transform
2994 .is_some_and(|i| usize::from(i) >= transform.len())
2995 {
2996 return Err(format!(
2997 "{name} clip at {} names transform {} of {}",
2998 c.start,
2999 c.transform.unwrap_or_default(),
3000 transform.len()
3001 )
3002 .into());
3003 }
3004 }
3005 if !sorted_disjoint(&data.clips) {
3006 return Err(format!("the {name} lane is out of order or overlaps itself").into());
3007 }
3008 }
3009 links_are_consistent(&lanes)?;
3010 // The counter sits past every id the file names, on either of a lane's
3011 // lists: a v16 caption may carry the highest link there is, and a
3012 // re-issued id would silently group it with the next placement that
3013 // asks for one -- the loader refusing a save the editor just wrote.
3014 let next_link = lanes
3015 .iter()
3016 .flat_map(|l| {
3017 let clips = l.clips.iter().filter_map(|c| c.link);
3018 let subs = l.subs.iter().filter_map(|s| s.link);
3019 clips.chain(subs)
3020 })
3021 .max()
3022 // Saturating so a crafted file cannot make the counter wrap: at the
3023 // ceiling ids stop being fresh, which loses grouping, not memory.
3024 .map_or(0, |m| m.saturating_add(1));
3025 Ok(Self {
3026 sources: sources
3027 .iter()
3028 .map(|s| Source { fav: s.fav, bin: s.bin, ..Source::new(&s.path, s.audio_stream) })
3029 .collect(),
3030 lanes,
3031 eq,
3032 color,
3033 transform,
3034 history: Vec::new(),
3035 redo: Vec::new(),
3036 pushes: 0,
3037 revision: next_revision(),
3038 batching: false,
3039 batch_snapped: false,
3040 pending: None,
3041 hold_cap: false,
3042 next_link,
3043 subtitles: Vec::new(),
3044 cue_edits: Vec::new(),
3045 cue_adds: Vec::new(),
3046 titles: Vec::new(),
3047 chapters: Vec::new(),
3048 markers: Vec::new(),
3049 settings: ProjectSettings::placeholder(),
3050 seq: Seqs::single(),
3051 bins: Vec::new(),
3052 bin_next: 1,
3053 seq_next: 1,
3054 flat: FlatCache::default(),
3055 })
3056 }
3057
3058 /// The first video lane -- what an export renders and what a single-lane
3059 /// caller still means by "the clips".
3060 pub fn clips(&self) -> &[Clip] {
3061 self.lane(Lane::V1)
3062 }
3063
3064 /// The clips of `lane`, or nothing at all for a lane that is not there.
3065 pub fn lane(&self, lane: Lane) -> &[Clip] {
3066 self.index(lane).map_or(&[][..], |i| &self.lanes[i].clips)
3067 }
3068
3069 /// Shortens every clip whose out-point runs past its source's wall: `picture` is
3070 /// the wall of a video lane's clip and `sound` of an audio lane's, per source (the
3071 /// tables a playback session holds each lane to). Each lane is held to its own
3072 /// wall, as the load check holds it. Returns what was shortened, so a save can say
3073 /// so. Sequence sources and walls of zero are left alone.
3074 pub fn clamp_to_walls(&mut self, picture: &[u32], sound: &[u32]) -> Vec<WallClamp> {
3075 let wall = |kind: LaneKind, source: usize| -> Option<u32> {
3076 let table = if kind == LaneKind::Audio { sound } else { picture };
3077 table.get(source).copied().filter(|&w| w > 0)
3078 };
3079 let mut clamps = Vec::new();
3080 for (lane, data) in handles(&self.lanes).into_iter().zip(self.lanes.iter_mut()) {
3081 for c in data.clips.iter_mut().filter(|c| !is_sequence_source(c.source)) {
3082 let Some(cap) = wall(data.kind, c.source) else { continue };
3083 if c.out_frame > cap {
3084 clamps.push(WallClamp { lane, source: c.source, from: c.out_frame, to: cap });
3085 c.out_frame = cap;
3086 }
3087 }
3088 }
3089 clamps
3090 }
3091
3092 /// Every lane's handle, in display order -- what a walk over "all lanes"
3093 /// iterates, and what a front-end lays out top to bottom.
3094 pub fn lanes(&self) -> Vec<Lane> {
3095 handles(&self.lanes)
3096 }
3097
3098 /// How many lanes of `kind` there are: `Lane::new(kind, ord)` names a lane
3099 /// for every `ord` below it, and none at or above it.
3100 pub fn lane_count(&self, kind: LaneKind) -> usize {
3101 self.lanes.iter().filter(|l| l.kind == kind).count()
3102 }
3103
3104 /// Appends an empty lane of `kind` and hands back its handle. One undo
3105 /// step, because the lane list is state a front-end shows: an added lane
3106 /// that could not be taken back would be the one edit with no way out.
3107 /// Nothing plays differently until something is placed on it.
3108 ///
3109 /// An empty lane is a lane like any other -- so is a whole project of them
3110 /// ([`Project::from_parts`]); nothing plays until something is placed.
3111 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3112 self.snapshot();
3113 self.lanes.push(LaneData::new(kind, Vec::new()));
3114 Lane::new(kind, self.lane_count(kind) - 1)
3115 }
3116
3117 /// Drops an *empty* lane -- [`add_lane`](Project::add_lane) taken back, and
3118 /// one undo step like it, which restores the lane where it stood.
3119 ///
3120 /// Refused, changing nothing, while the lane holds anything: the refusal
3121 /// names the clips (file and first frame), because a track removal that
3122 /// deleted takes with it would be the one edit nobody sees coming. Refused
3123 /// too for the last lane of its kind, which is `V1` or `A1`: those two are
3124 /// where an import and a paste land ([`Project::paste`] takes lane 0 of each
3125 /// kind and *skips* a kind that is not there), so a project without one
3126 /// would swallow half of every file dropped on it, silently.
3127 ///
3128 /// The lanes below it move up one `ord`, so a handle a caller was holding
3129 /// (a selection, an open card) names the lane after it from here on -- the
3130 /// one thing a front-end owes this call.
3131 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3132 let Some(i) = self.index(lane) else {
3133 return Err(format!("there is no {} to remove", lane.label()).into());
3134 };
3135 // A subtitle lane is not in that rule: nothing lands on one by itself
3136 // -- a project starts without any and one is added when a caption is --
3137 // so the last of them comes off like any other empty track.
3138 if self.lane_count(lane.kind) == 1 && lane.kind != LaneKind::Subtitle {
3139 return Err(format!(
3140 "{} is the only {} track: every import lands on it",
3141 lane.label(),
3142 match lane.kind {
3143 LaneKind::Video => "video",
3144 LaneKind::Audio => "audio",
3145 // Unreachable while the guard above lets the last subtitle
3146 // lane go, and its own word here so the sentence stays true
3147 // if that rule is ever relaxed.
3148 LaneKind::Subtitle => "subtitle",
3149 }
3150 )
3151 .into());
3152 }
3153 if !self.lanes[i].subs.is_empty() {
3154 // Three names and a count, exactly as the clips below get: the way
3155 // out of the refusal is the drag, so the words say so.
3156 let named: Vec<String> = self.lanes[i]
3157 .subs
3158 .iter()
3159 .take(3)
3160 .map(|s| format!("{} at frame {}", self.track_name(s.track), s.start))
3161 .collect();
3162 let rest = match self.lanes[i].subs.len().saturating_sub(named.len()) {
3163 0 => String::new(),
3164 n => format!(" and {n} more"),
3165 };
3166 return Err(format!(
3167 "{} still holds {}{rest}: delete those captions (or drag them to \
3168 another track) first",
3169 lane.label(),
3170 named.join(", ")
3171 )
3172 .into());
3173 }
3174 let clips = &self.lanes[i].clips;
3175 if !clips.is_empty() {
3176 // Three names and a count: a lane can hold forty clips and a
3177 // refusal nobody reads to the end says nothing at all.
3178 let named: Vec<String> = clips
3179 .iter()
3180 .take(3)
3181 .map(|c| {
3182 let name = self.sources.get(c.source).map_or_else(
3183 || format!("source {}", c.source),
3184 |s| s.path.display().to_string(),
3185 );
3186 format!("{name} at frame {}", c.start)
3187 })
3188 .collect();
3189 let rest = match clips.len().saturating_sub(named.len()) {
3190 0 => String::new(),
3191 n => format!(" and {n} more"),
3192 };
3193 return Err(format!(
3194 "{} still holds {}{rest}: delete those clips (or drag them to \
3195 another track) first",
3196 lane.label(),
3197 named.join(", ")
3198 )
3199 .into());
3200 }
3201 self.snapshot();
3202 self.lanes.remove(i);
3203 Ok(())
3204 }
3205
3206 /// Moves `lane` to display position `to` -- an index into
3207 /// [`Project::lanes`], the slot the lane there gives up -- and hands back
3208 /// the handle it answers to from now on. `None`, changing nothing and
3209 /// snapshotting nothing, for a lane that is not there, a position that is
3210 /// not, and a lane already standing in it.
3211 ///
3212 /// The whole track travels: its clips, its gain, its kind. Nothing is
3213 /// remapped, so no take changes lane and no group is broken -- this is the
3214 /// *order* of the lanes and nothing else, which is why one call is one undo
3215 /// step like an add or a removal.
3216 ///
3217 /// Display order **is** the stack: [`Project::composite_span_at`] shows the
3218 /// last video lane covering a frame, so moving one video lane past another
3219 /// changes which picture wins, in the preview and in an export alike. The
3220 /// audio lanes are summed and their sum does not care about order, so an
3221 /// audio track moved among the video ones is a rearrangement of the screen
3222 /// alone.
3223 ///
3224 /// A label is a *position* ([`Lane::label`] reads `ord`, which is the
3225 /// position among the lanes of that kind), so a lane that crosses one of
3226 /// its own kind swaps names with it -- `V2` dragged above `V1` becomes
3227 /// `V1`, clips and all -- while one that crosses only lanes of the other
3228 /// kind keeps its name. That is the returned handle: unchanged means every
3229 /// handle a caller holds still names the track it named before.
3230 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3231 let i = self.index(lane)?;
3232 if to >= self.lanes.len() || to == i {
3233 return None;
3234 }
3235 self.snapshot();
3236 let data = self.lanes.remove(i);
3237 self.lanes.insert(to, data);
3238 Some(handles(&self.lanes)[to])
3239 }
3240
3241 /// Where `lane` sits in [`Project::lanes`], or `None` for a lane that is
3242 /// not there. The one place a handle becomes a position.
3243 fn index(&self, lane: Lane) -> Option<usize> {
3244 self.lanes
3245 .iter()
3246 .enumerate()
3247 .filter(|(_, l)| l.kind == lane.kind)
3248 .map(|(i, _)| i)
3249 .nth(lane.ord)
3250 }
3251
3252 /// For an export of `range` only: drops the clips that lie wholly outside it and read a file
3253 /// `present` says is not there, so a range that never touches a missing source can be written
3254 /// without opening it. Nothing is dropped when that would shorten the timeline below what the
3255 /// range needs (the length of the file would change). A snapshot's edit, never the project's.
3256 pub fn drop_offline_outside(&mut self, range: (u32, u32), present: impl Fn(&Path) -> bool) {
3257 let gone: Vec<bool> = self.sources.iter().map(|s| !present(&s.path)).collect();
3258 if !gone.iter().any(|g| *g) {
3259 return;
3260 }
3261 let keep_len = self.timeline_frames().min(range.1);
3262 let saved: Vec<Vec<Clip>> = self.lanes.iter().map(|l| l.clips.clone()).collect();
3263 for lane in self.lanes.iter_mut().filter(|l| l.kind != LaneKind::Subtitle) {
3264 lane.clips.retain(|c| {
3265 let outside = c.end() <= range.0 || c.start >= range.1;
3266 !(outside && gone.get(c.source).copied().unwrap_or(false))
3267 });
3268 }
3269 if self.timeline_frames() < keep_len {
3270 for (lane, clips) in self.lanes.iter_mut().zip(saved) {
3271 lane.clips = clips;
3272 }
3273 }
3274 }
3275
3276 fn lane_mut(&mut self, lane: Lane) -> Option<&mut Vec<Clip>> {
3277 let i = self.index(lane)?;
3278 Some(&mut self.lanes[i].clips)
3279 }
3280
3281 /// The files the clips index into, in import order; index 0 is the file the
3282 /// project was opened with.
3283 pub fn sources(&self) -> &[Source] {
3284 &self.sources
3285 }
3286
3287 /// Points source `idx` at `path`, a file the caller has already checked is
3288 /// the same material. No clip changes; a source's index is its identity.
3289 /// One undo step, which puts the old path back ([`Snapshot::sources`]); a
3290 /// relink to the path the source already has is no change and no step.
3291 pub fn relink_source(&mut self, idx: usize, path: &Path) -> crate::Result<()> {
3292 let Some(source) = self.sources.get(idx) else {
3293 return Err(format!("there is no source {idx}").into());
3294 };
3295 let to = canonical(path);
3296 if source.path == to {
3297 return Ok(());
3298 }
3299 self.snapshot();
3300 self.sources[idx].path = to;
3301 Ok(())
3302 }
3303
3304 /// Points several sources at new files in one undo step ([`Self::relink_source`] for each,
3305 /// unchecked: the caller has copies of the same material). Sources already there and indexes
3306 /// that name nothing are left alone; no step when nothing moves. Returns how many moved.
3307 pub fn relink_sources(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3308 let moves: Vec<(usize, PathBuf)> = pairs
3309 .iter()
3310 .filter(|(i, to)| self.sources.get(*i).is_some_and(|s| s.path != canonical(to)))
3311 .map(|(i, to)| (*i, canonical(to)))
3312 .collect();
3313 if moves.is_empty() {
3314 return 0;
3315 }
3316 self.snapshot();
3317 for (i, to) in &moves {
3318 self.sources[*i].path = to.clone();
3319 }
3320 moves.len()
3321 }
3322
3323 /// Takes `other`'s timeline over as one undo step: what this project was
3324 /// before the call is one step back, and it is what a recovery does with an
3325 /// autosave once the saved project is open. The lanes, the subtitle palette,
3326 /// the cue edits and adds, the titles, the chapters, the markers, the settings
3327 /// and the sources all come from `other`. Its clip effect tables (equalizer, colour, transform) are
3328 /// appended to this project's own and its clips re-pointed at them, so the
3329 /// indexes a step in the history holds stay valid; the link counter is raised
3330 /// past `other`'s links, so a new split never reuses one. `false`, with
3331 /// nothing changed, when the appended tables would not fit a clip's `u16`.
3332 pub fn adopt_as_step(&mut self, other: &Project) -> bool {
3333 let fits = |have: usize, add: usize| have + add <= usize::from(u16::MAX);
3334 if !fits(self.eq.len(), other.eq.len())
3335 || !fits(self.color.len(), other.color.len())
3336 || !fits(self.transform.len(), other.transform.len())
3337 {
3338 return false;
3339 }
3340 let (eq_at, color_at, transform_at) = (self.eq.len(), self.color.len(), self.transform.len());
3341 // A `u16` index shifted past the appended table: the fit check above keeps it in range.
3342 let shift = |i: u16, by: usize| (usize::from(i) + by) as u16;
3343 let mut lanes = other.lanes.clone();
3344 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3345 c.eq = c.eq.map(|i| shift(i, eq_at));
3346 c.color = c.color.map(|i| shift(i, color_at));
3347 c.transform = c.transform.map(|i| shift(i, transform_at));
3348 }
3349 self.snapshot();
3350 self.eq.extend(other.eq.iter().cloned());
3351 self.color.extend(other.color.iter().cloned());
3352 self.transform.extend(other.transform.iter().cloned());
3353 let mut parked = other.seq.parked.clone();
3354 for c in parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()).flat_map(|l| &mut l.clips) {
3355 c.eq = c.eq.map(|i| shift(i, eq_at));
3356 c.color = c.color.map(|i| shift(i, color_at));
3357 c.transform = c.transform.map(|i| shift(i, transform_at));
3358 }
3359 self.seq = Seqs { active: other.seq.active, names: other.seq.names.clone(), parked, mcam: other.seq.mcam.clone(), nested: Vec::new() };
3360 self.seq_next = self.seq_next.max(other.seq_next);
3361 self.flat.clear();
3362 self.lanes = lanes;
3363 self.subtitles = other.subtitles.clone();
3364 self.cue_edits = other.cue_edits.clone();
3365 self.cue_adds = other.cue_adds.clone();
3366 self.titles = other.titles.clone();
3367 // The active sequence's chapters and markers are the other timeline's too: left
3368 // out, a recovery drops them and undo cannot bring them back.
3369 self.chapters = other.chapters.clone();
3370 self.markers = other.markers.clone();
3371 self.settings = other.settings.clone();
3372 self.sources = other.sources.clone();
3373 self.bins = other.bins.clone();
3374 self.bin_next = self.bin_next.max(other.bin_next);
3375 self.next_link = self.next_link.max(other.next_link);
3376 true
3377 }
3378
3379 /// The same list in the `(path, stream)` shape the audio engine indexes
3380 /// into -- [`crate::AudioSession::open_multi_streams`] and
3381 /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
3382 /// was placed with is the stream that plays *and* the stream that exports.
3383 pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
3384 self.sources
3385 .iter()
3386 .map(|s| (s.path.clone(), s.audio_stream))
3387 .collect()
3388 }
3389
3390 /// Index for `path` played on `audio_stream`, appending it if it is new.
3391 /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
3392 /// by two paths imports once and two streams of one file are two sources.
3393 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
3394 /// no history: a source entry alone changes nothing playable.
3395 pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
3396 let source = Source::new(path, audio_stream);
3397 match self.sources.iter().position(|s| *s == source) {
3398 Some(idx) => idx,
3399 None => {
3400 self.sources.push(source);
3401 self.sources.len() - 1
3402 }
3403 }
3404 }
3405
3406 /// Append a whole-file clip of `source` to the end of every *media* lane,
3407 /// grouped -- an import lands as one take. Subtitle lanes are skipped: they
3408 /// carry no [`Clip`] ([`LaneKind::Subtitle`]), and a file's own subtitles
3409 /// come in through [`Project::add_subtitles`], which is the palette.
3410 ///
3411 /// One history snapshot, so an import is one undo step, and undoing it
3412 /// leaves the (harmless) source entry behind, because indexes are forever.
3413 /// Refused for an unknown source index.
3414 pub fn append_clip(&mut self, source: usize, frame_count: u32) -> bool {
3415 if source >= self.sources.len() {
3416 return false;
3417 }
3418 self.snapshot();
3419 let start = self.timeline_frames();
3420 let clip = Clip {
3421 speed_keys: Vec::new(),
3422 reversed: false,
3423 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
3424 angle: Default::default(),
3425 fade_in: 0,
3426 fade_out: 0,
3427 transition_out: 0,
3428 transition_kind: Default::default(),
3429 visualizer: 0,
3430 viz_paint: 0,
3431 gain_db: 0.0,
3432 gain_keys: Vec::new(),
3433 pan: 0,
3434 pitch: 0,
3435 transform_keys: Vec::new(),
3436 opacity_keys: Vec::new(),
3437 color_keys: Vec::new(),
3438 effects: Vec::new(),
3439 start,
3440 in_frame: 0,
3441 out_frame: frame_count.max(1),
3442 source,
3443 link: Some(self.new_link()),
3444 eq: None,
3445 color: None,
3446 transform: None,
3447 fit: FitPolicy::default(),
3448 speed: Speed::NORMAL,
3449 };
3450 for data in self
3451 .lanes
3452 .iter_mut()
3453 .filter(|l| l.kind != LaneKind::Subtitle)
3454 {
3455 data.clips.push(clip.clone());
3456 }
3457 true
3458 }
3459
3460 /// Drops a source entry -- the file a library row *is* -- and renumbers
3461 /// every clip that indexed past it, which is why this is more than a
3462 /// `Vec::remove`.
3463 ///
3464 /// Refused, changing nothing, while any clip still plays from it: the
3465 /// refusal names the lanes and how many clips each holds, so a caller can
3466 /// say what has to be deleted first. The *last* entry goes like any other
3467 /// -- a project may name no file at all, which is an empty library over an
3468 /// empty timeline (nothing can play, since a clip would have refused the
3469 /// removal). What a front-end does with that is its own decision: `edith`'s
3470 /// window goes back to the empty state it launches in, and
3471 /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
3472 /// refuses to write a project that names nothing, because no such file
3473 /// could be opened again.
3474 ///
3475 /// Every index past `idx` moves down by one, so a caller holding a *raw*
3476 /// source index of its own -- a clipboard, which is the one thing outside
3477 /// this type that does -- has to fix it up or drop it, or a paste plays a
3478 /// different file. [`PlaybackSession::remove_source`] hands back the index
3479 /// that went for exactly that.
3480 ///
3481 /// corner-cut: this retires the undo stack. `history` holds the lanes, the
3482 /// subtitle palette and the project's own settings -- no source list -- so a
3483 /// snapshot older than the removal can name the very source being removed
3484 /// (delete a file's clips, then remove the file) and restoring it would
3485 /// point a clip at an entry that is gone. The upgrade path is snapshotting
3486 /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
3487 /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
3488 /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
3489 /// exists) currently rules out.
3490 pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
3491 let Some(source) = self.sources.get(idx) else {
3492 return Err(format!("there is no source {idx} to remove").into());
3493 };
3494 let name = source.path.display().to_string();
3495 let used: Vec<String> = handles(&self.lanes)
3496 .into_iter()
3497 .zip(&self.lanes)
3498 .filter_map(|(lane, data)| {
3499 match data.clips.iter().filter(|c| c.source == idx).count() {
3500 0 => None,
3501 1 => Some(format!("{} (1 clip)", lane.label())),
3502 n => Some(format!("{} ({n} clips)", lane.label())),
3503 }
3504 })
3505 .collect();
3506 if !used.is_empty() {
3507 return Err(format!("{name} still plays on {}", used.join(", ")).into());
3508 }
3509 if let Some((id, _)) = self
3510 .seq
3511 .parked
3512 .iter()
3513 .find(|(_, d)| d.lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx)))
3514 {
3515 let who = self.sequence_name(*id).unwrap_or("another sequence").to_string();
3516 return Err(format!("{name} still plays in the sequence \"{who}\"").into());
3517 }
3518 self.sources.remove(idx);
3519 let all = self
3520 .lanes
3521 .iter_mut()
3522 .chain(self.seq.parked.iter_mut().flat_map(|(_, d)| d.lanes.iter_mut()));
3523 for c in all.flat_map(|l| &mut l.clips) {
3524 if c.source > idx && !is_sequence_source(c.source) {
3525 c.source -= 1;
3526 }
3527 }
3528 self.flat.clear();
3529 // The redo steps renumber nothing and name the old indexes: they go with the history.
3530 self.history.clear();
3531 self.redo.clear();
3532 Ok(())
3533 }
3534
3535 /// Drops the **last** source, if nothing names it, and leaves the undo
3536 /// history exactly as it was. The narrow door behind a rollback: a source
3537 /// imported by a batch that then failed is the newest entry and nothing on
3538 /// the timeline plays it, so taking it back out renumbers nothing and
3539 /// invalidates no step.
3540 ///
3541 /// Refused, with the source left in place, when it is not the last entry (a
3542 /// removal below it would renumber every index above, which is what
3543 /// [`remove_source`](Project::remove_source) does and why that one clears
3544 /// history), or when a clip plays it or an undo or redo step does. The steps
3545 /// that held the entry past the new end are cut to the list that is left, so
3546 /// no restore brings it back.
3547 pub fn remove_unused_source(&mut self, idx: usize) -> crate::Result<()> {
3548 if idx >= self.sources.len() {
3549 return Err(format!("there is no source {idx} to remove").into());
3550 }
3551 let name = self.sources[idx].path.display().to_string();
3552 if idx + 1 != self.sources.len() {
3553 return Err(format!(
3554 "{name} is not the last source, so removing it would renumber the sources after it"
3555 )
3556 .into());
3557 }
3558 let named = |lanes: &[LaneData]| {
3559 lanes.iter().any(|l| l.clips.iter().any(|c| c.source == idx))
3560 };
3561 let parked = |seq: &Seqs| seq.parked.iter().any(|(_, d)| named(&d.lanes));
3562 if named(&self.lanes)
3563 || parked(&self.seq)
3564 || self.history.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3565 || self.redo.iter().any(|s| named(&s.lanes) || parked(&s.seq))
3566 {
3567 return Err(format!("{name} is still played by a clip or an undo step").into());
3568 }
3569 self.sources.pop();
3570 // The steps that hold the entry past the new end (none of them names it) are cut to the
3571 // list that is left, so an undo does not bring the removed entry back.
3572 for step in self.history.iter_mut().chain(self.redo.iter_mut()) {
3573 step.sources.truncate(idx);
3574 }
3575 Ok(())
3576 }
3577
3578 /// The sources, equalizer and colour tables, and transform table a save
3579 /// writes, with the clips reindexed onto their pruned copies. Every
3580 /// imported source is kept, in session order, so a source's index in the
3581 /// file is the index it had in the session and stays put across save and
3582 /// open. Equalizer, colour and transform entries nothing names are still
3583 /// pruned: an undone `set_eq`/`set_color` leaves a setting nothing plays
3584 /// behind, and those indexes are re-assigned by first use -- lane by lane,
3585 /// in display order -- so the same project always emits the same bytes.
3586 ///
3587 /// Every lane comes out, in display order and with its kind: that is what a
3588 /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
3589 /// takes back.
3590 ///
3591 /// The equalizer and colour tables are pruned the same way and for the same
3592 /// reason: an undone [`set_eq`](Project::set_eq) or
3593 /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
3594 /// and this is the one moment they can go -- the indexes that survive it are
3595 /// only the ones a clip names.
3596 ///
3597 /// Keeping every source (rather than only the ones a clip names) means an
3598 /// emptied timeline still has the file it is scaffolded from on reopen --
3599 /// the frame rate is written nowhere else -- and a source a clip no longer
3600 /// plays stays a library entry at the index a reload expects. Source 0 is
3601 /// whatever was imported first, which may be a still or a song;
3602 /// `PlaybackSession::open_project` picks its rate and its audio reference by
3603 /// what a source *is*, never by where it sits.
3604 pub fn without_orphan_sources(&self) -> Parts {
3605 // Every source comes out, in session order: an import is not an undo
3606 // step, so a source nothing plays is a deliberate library entry, and
3607 // its index is the one a reload must find it at again.
3608 let sources = self.sources.clone();
3609 let mut moved_eq = vec![None; self.eq.len()];
3610 let mut eq = Vec::new();
3611 let mut moved_color = vec![None; self.color.len()];
3612 let mut color = Vec::new();
3613 let mut moved_transform = vec![None; self.transform.len()];
3614 let mut transform = Vec::new();
3615 let mut lanes = self.lanes.clone();
3616 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
3617 if let Some(old) = c.eq.map(usize::from) {
3618 c.eq = Some(match moved_eq[old] {
3619 Some(new) => new,
3620 None => {
3621 eq.push(self.eq[old].clone());
3622 let new = (eq.len() - 1) as u16;
3623 moved_eq[old] = Some(new);
3624 new
3625 }
3626 });
3627 }
3628 if let Some(old) = c.color.map(usize::from) {
3629 c.color = Some(match moved_color[old] {
3630 Some(new) => new,
3631 None => {
3632 color.push(self.color[old]);
3633 let new = (color.len() - 1) as u16;
3634 moved_color[old] = Some(new);
3635 new
3636 }
3637 });
3638 }
3639 if let Some(old) = c.transform.map(usize::from) {
3640 c.transform = Some(match moved_transform[old] {
3641 Some(new) => new,
3642 None => {
3643 transform.push(self.transform[old]);
3644 let new = (transform.len() - 1) as u16;
3645 moved_transform[old] = Some(new);
3646 new
3647 }
3648 });
3649 }
3650 }
3651 (
3652 sources,
3653 // Every lane, subtitle ones included: they hold no [`Clip`], so what
3654 // comes out for one is an empty list, and its *place* in the display
3655 // order is what a save writes it for. What is on it travels beside
3656 // this, in [`lane_subs`](Project::lane_subs), as the gains do.
3657 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
3658 eq,
3659 color,
3660 transform,
3661 )
3662 }
3663
3664 /// How loud `lane` plays, in dB: `0.0` for one nobody has touched, and for
3665 /// a lane that is not there. Whole-lane and whole-band -- every clip on the
3666 /// track moves by it, which is what makes it a different control from a
3667 /// clip's equalizer (one frequency range of one take) and from the master
3668 /// volume (what this machine monitors at, which no file carries).
3669 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
3670 self.index(lane).map_or(0.0, |i| self.lanes[i].gain_db)
3671 }
3672
3673 /// The first auto-duck on `lane`, if it has one: the one
3674 /// [`lane_duck_list`](Project::lane_duck_list) starts with. `None` for a lane
3675 /// without one and for a lane that is not there. A lane with several ducks
3676 /// has them all in `lane_duck_list`; this names only the first.
3677 pub fn lane_duck(&self, lane: Lane) -> Option<Duck> {
3678 self.lane_duck_list(lane).first().copied()
3679 }
3680
3681 /// Every auto-duck on `lane`, one per key lane, in the order they were set.
3682 /// Empty for a lane without one and for a lane that is not there.
3683 pub fn lane_duck_list(&self, lane: Lane) -> Vec<Duck> {
3684 self.index(lane)
3685 .map_or_else(Vec::new, |i| self.lanes[i].ducks.clone())
3686 }
3687
3688 /// Sets an auto-duck on an audio lane: while the key lane `duck.under` is
3689 /// loud, this lane drops by `depth_db` ([`crate::duck`]). A lane can be
3690 /// ducked under several keys at once: a duck under a key this lane already
3691 /// has replaces that one, and a duck under a new key is added beside the
3692 /// rest. `None` clears every duck on the lane. One undo step, like a volume.
3693 ///
3694 /// `false`, and no history, for a lane that is not an audio lane or is not
3695 /// there, for a key that is not another audio lane of this project (`under`
3696 /// is the key's [`Lane::ord`]), for a number that is not finite, and for a
3697 /// duck already set exactly so. The numbers are clamped as the duck's own
3698 /// ranges clamp them.
3699 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<Duck>) -> bool {
3700 let Some(i) = self.index(lane) else {
3701 return false;
3702 };
3703 if lane.kind != LaneKind::Audio {
3704 return false;
3705 }
3706 let next = match duck {
3707 Some(d) => {
3708 let Some(d) = d.clamped() else {
3709 return false;
3710 };
3711 let key = Lane::new(LaneKind::Audio, d.under);
3712 if key == lane || self.index(key).is_none() {
3713 return false;
3714 }
3715 let mut ducks = self.lanes[i].ducks.clone();
3716 match ducks.iter_mut().find(|x| x.under == d.under) {
3717 Some(slot) if *slot == d => return false,
3718 Some(slot) => *slot = d,
3719 None => ducks.push(d),
3720 }
3721 ducks
3722 }
3723 None => {
3724 if self.lanes[i].ducks.is_empty() {
3725 return false;
3726 }
3727 Vec::new()
3728 }
3729 };
3730 self.snapshot();
3731 self.lanes[i].ducks = next;
3732 true
3733 }
3734
3735 /// Removes the duck `lane` has under the key `under` (the key's
3736 /// [`Lane::ord`]), leaving its other ducks. One undo step. `false`, and no
3737 /// history, for a lane with no duck under that key.
3738 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
3739 let Some(i) = self.index(lane) else {
3740 return false;
3741 };
3742 if !self.lanes[i].ducks.iter().any(|d| d.under == under) {
3743 return false;
3744 }
3745 self.snapshot();
3746 self.lanes[i].ducks.retain(|d| d.under != under);
3747 true
3748 }
3749
3750 /// The voice processors of `lane` ([`crate::voice`]): all off, and the
3751 /// default, for a lane that has none, is not an audio lane or is not there.
3752 pub fn lane_voice(&self, lane: Lane) -> VoiceFx {
3753 self.index(lane)
3754 .map_or_else(VoiceFx::default, |i| self.lanes[i].voice.clone())
3755 }
3756
3757 /// Sets the voice processors of an audio lane. One undo step. The numbers are
3758 /// clamped to their ranges. `false`, and no history, for a lane that is not an
3759 /// audio lane or is not there, for a number that is not finite, for a noise
3760 /// reduction switched on without a profile to subtract, and for a setting the
3761 /// lane already has.
3762 pub fn set_lane_voice(&mut self, lane: Lane, voice: VoiceFx) -> bool {
3763 let Some(i) = self.index(lane) else {
3764 return false;
3765 };
3766 if lane.kind != LaneKind::Audio {
3767 return false;
3768 }
3769 let Some(voice) = voice.clamped() else {
3770 return false;
3771 };
3772 if voice.nr.on && voice.nr.profile.is_empty() {
3773 return false;
3774 }
3775 if self.lanes[i].voice == voice {
3776 return false;
3777 }
3778 self.snapshot();
3779 self.lanes[i].voice = voice;
3780 true
3781 }
3782
3783 /// Sets that lane's volume, clamped to [`MIN_GAIN_DB`]..=[`MAX_GAIN_DB`].
3784 /// One undo step like every other edit -- it is in the lane list, so an
3785 /// undo restores it with the rest. `false`, and no history, for a lane that
3786 /// is not there, for a value that is not finite, and for one already set.
3787 ///
3788 /// `false` too for a subtitle lane, and that one is a *refusal* rather than
3789 /// a value nobody reads: words have no loudness, so a slider that appeared
3790 /// to move one would be a control with no effect. (A video lane's gain is
3791 /// meaningless in the same way but is kept settable: it is the pair `A1`
3792 /// carries for a take, and mixing reads it off the audio lane alone.)
3793 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
3794 let Some(i) = self.index(lane) else {
3795 return false;
3796 };
3797 if !db.is_finite() || lane.kind == LaneKind::Subtitle {
3798 return false;
3799 }
3800 let db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
3801 if self.lanes[i].gain_db == db {
3802 return false;
3803 }
3804 self.snapshot();
3805 self.lanes[i].gain_db = db;
3806 true
3807 }
3808
3809 /// The pan of an audio lane ([`Self::set_lane_pan`]), `0.0` for the middle and for a lane
3810 /// that is not there.
3811 pub fn lane_pan(&self, lane: Lane) -> f32 {
3812 self.index(lane).map_or(0.0, |i| self.lanes[i].pan)
3813 }
3814
3815 /// Give an audio lane this pan, clamped to `-1.0..=1.0`. One undo step; `false` for a lane
3816 /// that is not there or not audio, a value that is not finite, or one already set.
3817 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
3818 let Some(i) = self.index(lane) else {
3819 return false;
3820 };
3821 if !pan.is_finite() || lane.kind != LaneKind::Audio {
3822 return false;
3823 }
3824 let pan = pan.clamp(-1.0, 1.0);
3825 if self.lanes[i].pan == pan {
3826 return false;
3827 }
3828 self.snapshot();
3829 self.lanes[i].pan = pan;
3830 true
3831 }
3832
3833 /// Whether `lane` is hidden: a video lane left out of the picture, or a
3834 /// subtitle lane whose words are left off the screen and the export. `false`
3835 /// for a lane that is not there.
3836 pub fn lane_hidden(&self, lane: Lane) -> bool {
3837 self.index(lane).is_some_and(|i| self.lanes[i].hidden)
3838 }
3839
3840 /// Whether `lane` is muted: an audio lane silenced in the mix
3841 /// ([`audio_gains`](Project::audio_gains) reads it as 0). `false` for a lane
3842 /// that is not there.
3843 pub fn lane_muted(&self, lane: Lane) -> bool {
3844 self.index(lane).is_some_and(|i| self.lanes[i].muted)
3845 }
3846
3847 /// Whether `lane` is locked. The engine does not look at it: an edit to a
3848 /// locked lane is refused by the front-end, which is where the toast that
3849 /// offers Unlock lives.
3850 pub fn lane_locked(&self, lane: Lane) -> bool {
3851 self.index(lane).is_some_and(|i| self.lanes[i].locked)
3852 }
3853
3854 /// The name the user gave `lane`, `None` when it has none (or is not there).
3855 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
3856 self.index(lane).map(|i| self.lanes[i].name.as_str()).filter(|n| !n.is_empty())
3857 }
3858
3859 /// What a header shows for `lane`: its name, else its address (`V1`).
3860 pub fn lane_title(&self, lane: Lane) -> String {
3861 self.lane_name(lane).map_or_else(|| lane.label(), str::to_string)
3862 }
3863
3864 /// Names `lane`; an empty (or all-blank) name clears it. One undo step.
3865 /// `Ok(false)`, and no history, for a lane that is not there or no change.
3866 /// Refused: more than [`MAX_LANE_NAME_CHARS`] characters, control characters.
3867 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
3868 let name = name.trim();
3869 if name.chars().count() > MAX_LANE_NAME_CHARS {
3870 return Err(format!("a lane name is at most {MAX_LANE_NAME_CHARS} characters"));
3871 }
3872 if name.chars().any(char::is_control) {
3873 return Err("a lane name holds no control characters".into());
3874 }
3875 let Some(i) = self.index(lane) else {
3876 return Ok(false);
3877 };
3878 if self.lanes[i].name == name {
3879 return Ok(false);
3880 }
3881 self.snapshot();
3882 self.lanes[i].name = name.to_string();
3883 Ok(true)
3884 }
3885
3886 /// Every lane's name (empty for none), in display order and in step with
3887 /// [`lane_gains`](Project::lane_gains) -- what a save writes.
3888 pub fn lane_names(&self) -> Vec<String> {
3889 self.lanes.iter().map(|l| l.name.clone()).collect()
3890 }
3891
3892 /// The names a *load* puts back, with no undo step (as
3893 /// [`with_voices`](Project::with_voices)).
3894 pub fn with_lane_names(mut self, names: &[String]) -> Self {
3895 for (data, name) in self.lanes.iter_mut().zip(names) {
3896 data.name = name.clone();
3897 }
3898 self
3899 }
3900
3901 /// Hides or shows a lane. One undo step. `false`, and no history, for a lane
3902 /// that is not there, for one already in that state, and for an audio lane:
3903 /// there is no picture or caption on one to leave out (the mute is its
3904 /// switch), so a hide on it would be a control with no effect.
3905 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
3906 self.set_flag(lane, hidden, |k| k != LaneKind::Audio, |l| &mut l.hidden)
3907 }
3908
3909 /// Mutes or unmutes an audio lane. One undo step. `false`, and no history,
3910 /// for a lane that is not there, for one already in that state, and for any
3911 /// lane but an audio one -- the video lane's sound is never mixed.
3912 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
3913 self.set_flag(lane, muted, |k| k == LaneKind::Audio, |l| &mut l.muted)
3914 }
3915
3916 /// Locks or unlocks a lane. One undo step. `false`, and no history, for a
3917 /// lane that is not there and for one already in that state. The engine
3918 /// accepts edits on a locked lane all the same; see
3919 /// [`lane_locked`](Project::lane_locked).
3920 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
3921 self.set_flag(lane, locked, |_| true, |l| &mut l.locked)
3922 }
3923
3924 /// The one door the three switches go through: refuse what the lane kind
3925 /// cannot have, refuse a no-op, otherwise snapshot and set.
3926 fn set_flag(
3927 &mut self,
3928 lane: Lane,
3929 on: bool,
3930 allowed: fn(LaneKind) -> bool,
3931 field: fn(&mut LaneData) -> &mut bool,
3932 ) -> bool {
3933 let Some(i) = self.index(lane) else {
3934 return false;
3935 };
3936 if !allowed(lane.kind) || *field(&mut self.lanes[i]) == on {
3937 return false;
3938 }
3939 self.snapshot();
3940 *field(&mut self.lanes[i]) = on;
3941 true
3942 }
3943
3944 /// Every lane's switches, in display order and in step with
3945 /// [`lane_gains`](Project::lane_gains) -- what a save writes beside them.
3946 pub fn lane_flags(&self) -> Vec<LaneFlags> {
3947 self.lanes
3948 .iter()
3949 .map(|l| LaneFlags {
3950 hidden: l.hidden,
3951 muted: l.muted,
3952 locked: l.locked,
3953 pan: l.pan,
3954 })
3955 .collect()
3956 }
3957
3958 /// The switches a *load* puts back, beside [`with_mix`](Project::with_mix)
3959 /// and for the same reason: no undo step. A short list leaves the rest
3960 /// clear, which is what a file from before the switches means.
3961 pub fn with_lane_flags(mut self, flags: &[LaneFlags]) -> Self {
3962 for (data, f) in self.lanes.iter_mut().zip(flags) {
3963 data.hidden = f.hidden;
3964 data.muted = f.muted;
3965 data.locked = f.locked;
3966 data.pan = f.pan;
3967 }
3968 self
3969 }
3970
3971 /// Every lane's volume in dB, in display order -- what a save writes,
3972 /// beside the lanes [`Project::without_orphan_sources`] hands back.
3973 ///
3974 /// The *same* lanes as that call, subtitle ones included at the `0.0` they
3975 /// are pinned to ([`set_lane_gain_db`](Project::set_lane_gain_db) refuses
3976 /// one): a save zips the two lists, so a lane that is in one and not the
3977 /// other would hand every track below it the volume of the track above.
3978 pub fn lane_gains(&self) -> Vec<f32> {
3979 self.lanes.iter().map(|l| l.gain_db).collect()
3980 }
3981
3982 /// Every lane's ducks, in step with [`lane_gains`](Project::lane_gains) --
3983 /// what a save writes beside them. Empty for every lane but an audio lane
3984 /// with a duck.
3985 pub fn lane_ducks(&self) -> Vec<Vec<Duck>> {
3986 self.lanes.iter().map(|l| l.ducks.clone()).collect()
3987 }
3988
3989 /// Every lane's voice processors, in step with [`lane_gains`](Project::lane_gains)
3990 /// -- what a save writes beside them.
3991 pub fn lane_voices(&self) -> Vec<VoiceFx> {
3992 self.lanes.iter().map(|l| l.voice.clone()).collect()
3993 }
3994
3995 /// What is placed on every lane, in display order and in step with
3996 /// [`without_orphan_sources`](Project::without_orphan_sources) exactly as
3997 /// [`lane_gains`](Project::lane_gains) is -- what a save writes as its `sub`
3998 /// lines. Empty for every video and audio lane, which hold no [`SubClip`].
3999 ///
4000 /// Nothing is renumbered on the way out: a [`SubClip`] names a *palette*
4001 /// row ([`Project::subtitles`]) and the palette is saved whole, so unlike a
4002 /// clip's source there is no orphan to prune and no index to move.
4003 pub fn lane_subs(&self) -> Vec<Vec<SubClip>> {
4004 self.lanes.iter().map(|l| l.subs.clone()).collect()
4005 }
4006
4007 /// The placements a *load* puts back, one list per lane in display order --
4008 /// the door [`with_mix`](Project::with_mix) is, and no undo step for the
4009 /// same reason. Called *after*
4010 /// [`with_subtitles`](Project::with_subtitles), whose palette a placement
4011 /// names.
4012 ///
4013 /// The subtitle half of [`from_parts`](Project::from_parts) and checked
4014 /// like it, by name and in release, because it is the same untrusted file:
4015 /// a placement on a lane that is not a subtitle lane, an empty span or an
4016 /// empty window, a track the palette does not have, a span running past the
4017 /// last frame there is, and a lane that is out of order or overlaps itself
4018 /// ([`place_sub`] refuses every one of those on the live timeline).
4019 ///
4020 /// [`place_sub`]: Project::place_sub
4021 pub fn with_subs(mut self, subs: Vec<Vec<SubClip>>) -> crate::Result<Self> {
4022 let names = handles(&self.lanes);
4023 let palette = self.subtitles.len();
4024 for ((data, lane), list) in self.lanes.iter_mut().zip(names).zip(subs) {
4025 let name = lane.label();
4026 if list.is_empty() {
4027 continue;
4028 }
4029 if data.kind != LaneKind::Subtitle {
4030 return Err(format!(
4031 "{name} is not a subtitle track and holds {} caption(s): words go on a \
4032 subtitle track",
4033 list.len()
4034 )
4035 .into());
4036 }
4037 for s in &list {
4038 if s.frames == 0 || s.out_us <= s.in_us || s.in_us < 0 {
4039 return Err(format!(
4040 "{name} caption at {} is empty: {} frames of [{}, {})",
4041 s.start, s.frames, s.in_us, s.out_us
4042 )
4043 .into());
4044 }
4045 // The width of that window, which the check above cannot see:
4046 // [`edith`](crate::edith) asks the same question at the parse
4047 // and this repeats it, because `with_subs` is the door a
4048 // hand-built `Project` comes through and a caller is not more
4049 // trustworthy than a file.
4050 if s.out_us - s.in_us > MAX_WINDOW_US {
4051 return Err(format!(
4052 "{name} caption at {} is a {}us window, past the {}us a caption can hold",
4053 s.start,
4054 s.out_us - s.in_us,
4055 MAX_WINDOW_US
4056 )
4057 .into());
4058 }
4059 if s.track >= palette {
4060 return Err(format!(
4061 "{name} caption at {} names subtitle track {} of {palette}",
4062 s.start, s.track
4063 )
4064 .into());
4065 }
4066 if s.start.checked_add(s.frames).is_none() {
4067 return Err(format!(
4068 "{name} caption at {} runs past the last frame there is",
4069 s.start
4070 )
4071 .into());
4072 }
4073 }
4074 if !subs_sorted_disjoint(&list) {
4075 return Err(format!("the {name} lane is out of order or overlaps itself").into());
4076 }
4077 data.subs = list;
4078 // The counter also has to clear the ids these captions carry: this
4079 // is the door a load's placements come through, *after*
4080 // [`from_parts`](Project::from_parts) seeded it from the clips, and
4081 // a hand-grouped caption may carry the highest id in the file.
4082 self.next_link = self.next_link.max(
4083 data.subs
4084 .iter()
4085 .filter_map(|s| s.link)
4086 .max()
4087 .map_or(0, |m| m.saturating_add(1)),
4088 );
4089 }
4090 Ok(self)
4091 }
4092
4093 /// The mix settings a *load* puts back: lane volumes in display order (a
4094 /// short list leaves the rest at unity) and the master limiter, both
4095 /// clamped as their setters clamp them.
4096 ///
4097 /// The load's own door, beside [`from_parts`](Project::from_parts): the
4098 /// setters push an undo step, and a project that arrives one undo away from
4099 /// a state it was never in is a project whose first ctrl+z is a surprise.
4100 pub fn with_mix(mut self, gains: &[f32], limiter: Limiter) -> Self {
4101 for (data, &db) in self.lanes.iter_mut().zip(gains) {
4102 if db.is_finite() {
4103 data.gain_db = db.clamp(MIN_GAIN_DB, MAX_GAIN_DB);
4104 }
4105 }
4106 self.settings.limiter = limiter.with_ceiling(limiter.ceiling_db);
4107 self
4108 }
4109
4110 /// The ducks a *load* puts back, in display order and beside
4111 /// [`with_mix`](Project::with_mix), with no undo step for the same reason.
4112 /// A short list leaves the rest without one; a duck the file named is
4113 /// already validated by [`crate::edith`].
4114 pub fn with_ducks(mut self, ducks: &[Vec<Duck>]) -> Self {
4115 for (data, lane_ducks) in self.lanes.iter_mut().zip(ducks) {
4116 data.ducks = lane_ducks.clone();
4117 }
4118 self
4119 }
4120
4121 /// The voice processors a *load* puts back, in display order, with no undo
4122 /// step for the reason [`with_mix`](Project::with_mix) gives. A short list
4123 /// leaves the rest with none.
4124 pub fn with_voices(mut self, voices: &[VoiceFx]) -> Self {
4125 for (data, voice) in self.lanes.iter_mut().zip(voices) {
4126 data.voice = voice.clone();
4127 }
4128 self
4129 }
4130
4131 /// The HDR rendition a *load* puts back -- the same door
4132 /// [`with_mix`](Project::with_mix) is, and no undo step for the same reason.
4133 pub fn with_tone(mut self, preset: crate::tonemap::Preset) -> Self {
4134 self.settings.tone = preset;
4135 self
4136 }
4137
4138 /// The canvas and rate a *load* or a fresh open names -- the project
4139 /// resolution and the rate every clip is counted in. The same door
4140 /// [`with_mix`](Project::with_mix) is, and no undo step for the same
4141 /// reason: a project that arrives one undo away from a state it was never
4142 /// in is a project whose first ctrl+z is a surprise.
4143 pub fn with_canvas(mut self, width: u32, height: u32, frame_rate: f64) -> Self {
4144 self.settings.resolution = (width, height);
4145 self.settings.frame_rate = frame_rate;
4146 self
4147 }
4148
4149 /// The saved switches a *load* puts back: whether the picture is cut on
4150 /// the stand-ins, whether new ones are made on arrival, which encoder an
4151 /// export opens, and the rate the mix was picked to run at. The load half
4152 /// of [`set_proxies`](Project::set_proxies) and its siblings, and no undo
4153 /// step for [`with_mix`](Project::with_mix)'s reason.
4154 pub fn with_switches(
4155 mut self,
4156 proxies: bool,
4157 auto_proxies: bool,
4158 encoder_seat: crate::export::EncoderSeat,
4159 sample_rate: Option<u32>,
4160 ) -> Self {
4161 self.settings.proxies = proxies;
4162 self.settings.auto_proxies = auto_proxies;
4163 self.settings.encoder_seat = encoder_seat;
4164 self.settings.sample_rate = sample_rate;
4165 self
4166 }
4167
4168 /// The word times a *load* puts back, `(track, cue, words)`, after the cue edits and
4169 /// additions have made the cue list they index. No undo step, as [`with_tone`](Project::with_tone).
4170 pub(crate) fn with_cue_words(mut self, rows: &[CueWordRow]) -> Self {
4171 for (track, cue, words) in rows {
4172 if let Some(c) = self.subtitles.get_mut(*track).and_then(|t| t.cues.get_mut(*cue)) {
4173 c.words = words.clone();
4174 }
4175 }
4176 self
4177 }
4178
4179 /// Gives the cues of `track` the word times of `timed`, the cues they were written from:
4180 /// each track cue takes the next timed cue with the same text that starts within a
4181 /// millisecond of it (an SRT keeps milliseconds). A cue none matches keeps none. Not an undo
4182 /// step of its own: it completes the import that made the track.
4183 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
4184 let Some(t) = self.subtitles.get_mut(track) else {
4185 return;
4186 };
4187 let norm = |s: &str| s.split_whitespace().collect::<Vec<_>>().join(" ");
4188 let mut from = 0;
4189 for cue in &mut t.cues {
4190 let hit = timed[from..]
4191 .iter()
4192 .position(|w| (w.start_us - cue.start_us).abs() <= 1000 && norm(&w.text) == norm(&cue.text));
4193 if let Some(k) = hit {
4194 cue.words = timed[from + k].words.clone();
4195 from += k + 1;
4196 }
4197 }
4198 }
4199
4200 /// How burned captions animate in this project ([`crate::captionanim`]).
4201 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
4202 self.settings.caption_style
4203 }
4204
4205 /// Sets it (clamped). `false` for the style already in force; otherwise one undo step.
4206 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
4207 let style = style.clamped();
4208 if self.settings.caption_style == style {
4209 return false;
4210 }
4211 self.snapshot();
4212 self.settings.caption_style = style;
4213 true
4214 }
4215
4216 /// The caption style a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4217 pub(crate) fn with_caption_style(mut self, style: crate::captionanim::CaptionStyle) -> Self {
4218 self.settings.caption_style = style.clamped();
4219 self
4220 }
4221
4222 /// Which HDR-to-SDR rendition this project is watched and exported in. A
4223 /// project setting, not a clip's: one picture, one look
4224 /// ([`crate::tonemap::Preset`]).
4225 pub fn tone(&self) -> crate::tonemap::Preset {
4226 self.settings.tone
4227 }
4228
4229 /// The project's notes: free text, several lines allowed, empty until one is written.
4230 pub fn notes(&self) -> &str {
4231 &self.settings.notes
4232 }
4233
4234 /// Sets the notes. `false` for the text already in force; otherwise one undo step.
4235 pub fn set_notes(&mut self, notes: &str) -> bool {
4236 if self.settings.notes == notes {
4237 return false;
4238 }
4239 self.snapshot();
4240 self.settings.notes = notes.to_string();
4241 true
4242 }
4243
4244 /// The notes a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4245 pub(crate) fn with_notes(mut self, notes: String) -> Self {
4246 self.settings.notes = notes;
4247 self
4248 }
4249
4250 /// How long a still image is placed for, in seconds: [`STILL_DEFAULT_SECS`] until the
4251 /// project picks another length.
4252 pub fn still_secs(&self) -> f64 {
4253 self.settings.still_secs
4254 }
4255
4256 /// Sets it, clamped to [`STILL_MIN_SECS`]..[`STILL_MAX_SECS`]. `false` for the length already
4257 /// in force; otherwise one undo step. Only stills placed after this change take the new length.
4258 pub fn set_still_secs(&mut self, secs: f64) -> bool {
4259 let secs = if secs.is_finite() { secs.clamp(STILL_MIN_SECS, STILL_MAX_SECS) } else { STILL_DEFAULT_SECS };
4260 if self.settings.still_secs == secs {
4261 return false;
4262 }
4263 self.snapshot();
4264 self.settings.still_secs = secs;
4265 true
4266 }
4267
4268 /// The still length a *load* puts back: no undo step, as [`with_tone`](Project::with_tone).
4269 pub(crate) fn with_still_secs(mut self, secs: Option<f64>) -> Self {
4270 self.settings.still_secs = secs.map_or(STILL_DEFAULT_SECS, |s| s.clamp(STILL_MIN_SECS, STILL_MAX_SECS));
4271 self
4272 }
4273
4274 /// Sets it. `false` for the one already in force, which is what keeps a
4275 /// re-pick of the current rendition from costing a reseek. One undo step
4276 /// like every other project-setting pick.
4277 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
4278 if self.settings.tone == preset {
4279 return false;
4280 }
4281 self.snapshot();
4282 self.settings.tone = preset;
4283 true
4284 }
4285
4286 /// The subtitle tracks a *load* puts back, in the order they were saved --
4287 /// the same door [`with_mix`](Project::with_mix) is, and no undo step for
4288 /// the same reason.
4289 pub fn with_subtitles(mut self, tracks: Vec<SubtitleTrack>) -> Self {
4290 self.subtitles = tracks;
4291 self
4292 }
4293
4294 /// The languages a *load* puts back over the palette ([`with_subtitles`](
4295 /// Project::with_subtitles) must come first): `(track, code)` pairs, the
4296 /// track by its position in the palette, as the `sublang` lines name it.
4297 /// No undo step, as with the palette itself. A pair naming no row is
4298 /// ignored; the reader has already refused a line that names one.
4299 pub fn with_sub_langs(mut self, langs: &[(usize, String)]) -> Self {
4300 for (track, code) in langs {
4301 if let Some(t) = self.subtitles.get_mut(*track) {
4302 crate::subtitle::set_language(t, code);
4303 }
4304 }
4305 self
4306 }
4307
4308 /// Names the language of subtitle track `track`: an ISO 639-2 code as
4309 /// [`crate::subtitle::language_code`] gives it, or `und`. One undo step, and
4310 /// `false` (no step) for a track that is not there or already reads that.
4311 /// Kept in the project file (`sublang` lines), and an export writes it as
4312 /// the track's language.
4313 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
4314 match self.subtitles.get(track) {
4315 Some(t) if t.language != code => {}
4316 _ => return false,
4317 }
4318 self.snapshot();
4319 crate::subtitle::set_language(&mut self.subtitles[track], code);
4320 true
4321 }
4322
4323 /// The title cards and text overlays, in draw order: sorted by start, and
4324 /// where two share a start, in the order they were added.
4325 pub fn titles(&self) -> &[Title] {
4326 &self.titles
4327 }
4328
4329 /// Adds a title and returns its index in [`titles`](Project::titles). It is
4330 /// kept sorted by start, so a title lands after the ones that start no
4331 /// later than it. Overlaps are allowed; the later one draws over the earlier.
4332 ///
4333 /// Refused, changing nothing and taking no undo step, when [`check_title`]
4334 /// refuses the title. A title may start past the last clip: the timeline
4335 /// runs on to cover it, over black where no clip plays.
4336 pub fn add_title(&mut self, title: Title) -> crate::Result<usize> {
4337 check_title(&title)?;
4338 self.snapshot();
4339 let idx = self.titles.partition_point(|t| t.start <= title.start);
4340 self.titles.insert(idx, title);
4341 Ok(idx)
4342 }
4343
4344 /// Replaces the title at `idx` with `title`, then re-sorts the list by start
4345 /// -- so the title may move, and a caller that holds its index looks it up
4346 /// again. `false`, changing nothing, for an index that is not there, a title
4347 /// [`check_title`] refuses, or a title the same as the one it replaces.
4348 pub fn set_title(&mut self, idx: usize, title: Title) -> bool {
4349 if idx >= self.titles.len() || check_title(&title).is_err() || self.titles[idx] == title {
4350 return false;
4351 }
4352 self.snapshot();
4353 self.titles[idx] = title;
4354 self.titles.sort_by_key(|t| t.start);
4355 true
4356 }
4357
4358 /// Takes the title at `idx` off the list. `false`, changing nothing, for an
4359 /// index that is not there.
4360 pub fn remove_title(&mut self, idx: usize) -> bool {
4361 if idx >= self.titles.len() {
4362 return false;
4363 }
4364 self.snapshot();
4365 self.titles.remove(idx);
4366 true
4367 }
4368
4369 /// The frame the last title ends on, or 0 with none: what the timeline
4370 /// runs on to, past its media.
4371 fn title_end(&self) -> u32 {
4372 self.titles.iter().map(Title::end).max().unwrap_or(0)
4373 }
4374
4375 /// The chapter markers, sorted by frame, at most one per frame.
4376 pub fn chapters(&self) -> &[Chapter] {
4377 &self.chapters
4378 }
4379
4380 /// Adds a chapter and returns its index in [`chapters`](Project::chapters).
4381 /// Refused, changing nothing and taking no undo step, when [`check_chapter`]
4382 /// refuses it or another chapter already sits on its frame.
4383 pub fn add_chapter(&mut self, chapter: Chapter) -> crate::Result<usize> {
4384 check_chapter(&chapter)?;
4385 if let Some(other) = self.chapters.iter().find(|c| c.frame == chapter.frame) {
4386 return Err(format!("chapter {:?} already starts at frame {}", other.title, other.frame).into());
4387 }
4388 self.snapshot();
4389 let idx = self.chapters.partition_point(|c| c.frame < chapter.frame);
4390 self.chapters.insert(idx, chapter);
4391 Ok(idx)
4392 }
4393
4394 /// Takes the chapter at `idx` off the list. `false`, changing nothing, for an
4395 /// index that is not there.
4396 pub fn remove_chapter(&mut self, idx: usize) -> bool {
4397 if idx >= self.chapters.len() {
4398 return false;
4399 }
4400 self.snapshot();
4401 self.chapters.remove(idx);
4402 true
4403 }
4404
4405 /// Renames the chapter at `idx`. `false`, changing nothing, for an index that
4406 /// is not there, a name [`check_chapter`] refuses, or the name it already has.
4407 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
4408 let Some(current) = self.chapters.get(idx) else {
4409 return false;
4410 };
4411 let renamed = Chapter { frame: current.frame, title: title.to_string() };
4412 if current.title == title || check_chapter(&renamed).is_err() {
4413 return false;
4414 }
4415 self.snapshot();
4416 self.chapters[idx] = renamed;
4417 true
4418 }
4419
4420 /// Moves the chapter at `idx` to `frame`, and returns its new index. Refused,
4421 /// changing nothing, for an index that is not there or a frame another chapter
4422 /// already holds; a move to the frame it is on is a no-op that takes no step.
4423 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
4424 let Some(current) = self.chapters.get(idx) else {
4425 return Err("no chapter there to move".into());
4426 };
4427 if current.frame == frame {
4428 return Ok(idx);
4429 }
4430 if let Some(other) = self.chapters.iter().find(|c| c.frame == frame) {
4431 return Err(format!("chapter {:?} already starts at frame {frame}", other.title).into());
4432 }
4433 self.snapshot();
4434 let mut chapter = self.chapters.remove(idx);
4435 chapter.frame = frame;
4436 let at = self.chapters.partition_point(|c| c.frame < frame);
4437 self.chapters.insert(at, chapter);
4438 Ok(at)
4439 }
4440
4441 /// Maps every chapter's frame through `map` in one undo step, for an edit that
4442 /// moves time: a cut, a ripple, a rate change. Two chapters that land on one
4443 /// frame keep the first in the list and drop the other, which is why the
4444 /// count of chapters dropped is returned. `0`, changing nothing and taking no
4445 /// step, when no frame moves.
4446 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
4447 let before = self.chapters.len();
4448 let mut mapped: Vec<Chapter> = self
4449 .chapters
4450 .iter()
4451 .map(|c| Chapter { frame: map(c.frame), title: c.title.clone() })
4452 .collect();
4453 if mapped == self.chapters {
4454 return 0;
4455 }
4456 self.snapshot();
4457 // Stable sort keeps list order among chapters on one frame, so the first
4458 // one written keeps its frame.
4459 mapped.sort_by_key(|c| c.frame);
4460 mapped.dedup_by_key(|c| c.frame);
4461 let dropped = before - mapped.len();
4462 self.chapters = mapped;
4463 dropped
4464 }
4465
4466 /// Sets the whole chapter list at once, for a loader: sorted by frame, a
4467 /// second chapter on a frame dropped. Not an edit, so no undo step.
4468 pub(crate) fn with_chapters(mut self, mut chapters: Vec<Chapter>) -> Self {
4469 chapters.sort_by_key(|c| c.frame);
4470 chapters.dedup_by_key(|c| c.frame);
4471 self.chapters = chapters;
4472 self
4473 }
4474
4475 /// The comment markers, sorted by frame (several may share one).
4476 pub fn markers(&self) -> &[Marker] {
4477 &self.markers
4478 }
4479
4480 /// Adds a marker and returns its index in [`markers`](Project::markers); after any
4481 /// marker already on its frame. Refused, changing nothing and taking no undo step,
4482 /// when [`check_marker`] refuses it.
4483 pub fn add_marker(&mut self, marker: Marker) -> crate::Result<usize> {
4484 check_marker(&marker)?;
4485 self.snapshot();
4486 let idx = self.markers.partition_point(|m| m.frame <= marker.frame);
4487 self.markers.insert(idx, marker);
4488 Ok(idx)
4489 }
4490
4491 /// Takes the marker at `idx` off. `false`, changing nothing, for an index that is not there.
4492 pub fn remove_marker(&mut self, idx: usize) -> bool {
4493 if idx >= self.markers.len() {
4494 return false;
4495 }
4496 self.snapshot();
4497 self.markers.remove(idx);
4498 true
4499 }
4500
4501 /// Replaces the marker at `idx` and returns its new index (it re-sorts when its frame
4502 /// moves). Refused, changing nothing, for an index that is not there, a marker
4503 /// [`check_marker`] refuses, or one equal to what is there.
4504 pub fn set_marker(&mut self, idx: usize, marker: Marker) -> crate::Result<usize> {
4505 let Some(current) = self.markers.get(idx) else {
4506 return Err("no marker there to change".into());
4507 };
4508 check_marker(&marker)?;
4509 if *current == marker {
4510 return Err("the marker is already so".into());
4511 }
4512 self.snapshot();
4513 if self.markers[idx].frame == marker.frame {
4514 self.markers[idx] = marker;
4515 return Ok(idx);
4516 }
4517 self.markers.remove(idx);
4518 let at = self.markers.partition_point(|m| m.frame <= marker.frame);
4519 self.markers.insert(at, marker);
4520 Ok(at)
4521 }
4522
4523 /// Maps every marker's start and end through `map` in one undo step, for an edit that
4524 /// moves time, as [`remap_chapters`](Project::remap_chapters) does. A range keeps at
4525 /// least a point of itself; markers never merge, so none is lost. `false`, changing
4526 /// nothing and taking no step, when nothing moves.
4527 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
4528 let mut mapped: Vec<Marker> = self
4529 .markers
4530 .iter()
4531 .map(|m| {
4532 let frame = map(m.frame);
4533 let length = if m.length == 0 { 0 } else { map(m.end()).saturating_sub(frame) };
4534 Marker { frame, length, ..m.clone() }
4535 })
4536 .collect();
4537 if mapped == self.markers {
4538 return false;
4539 }
4540 self.snapshot();
4541 mapped.sort_by_key(|m| m.frame);
4542 self.markers = mapped;
4543 true
4544 }
4545
4546 /// Sets the whole marker list at once, for a loader: sorted by frame. Not an edit, so no undo step.
4547 pub(crate) fn with_markers(mut self, mut markers: Vec<Marker>) -> Self {
4548 markers.sort_by_key(|m| m.frame);
4549 self.markers = markers;
4550 self
4551 }
4552
4553 /// Sets the whole title list at once, for a loader: the file's own order is
4554 /// kept, sorted by start as [`add_title`](Project::add_title) keeps it. Not an
4555 /// edit, so no undo step.
4556 pub(crate) fn with_titles(mut self, mut titles: Vec<Title>) -> Self {
4557 titles.sort_by_key(|t| t.start);
4558 self.titles = titles;
4559 self
4560 }
4561
4562 /// What this timeline shows over the picture, in the order they were added:
4563 /// what a front-end lists and what a save writes.
4564 pub fn subtitles(&self) -> &[SubtitleTrack] {
4565 &self.subtitles
4566 }
4567
4568 /// Adds a track, unless the very same one -- same file, same track number
4569 /// inside it -- is already on the list. `false` for that repeat: importing
4570 /// the same `.srt` twice is one subtitle track, not two identical ones.
4571 /// Adds every track of an import that is not already on the list, as one undo
4572 /// step: a failed batch that imported a track rolls the import back with it.
4573 /// Returns how many were added (none, and no step, when every one is a repeat).
4574 pub fn add_subtitles_all(&mut self, tracks: &[SubtitleTrack]) -> usize {
4575 let fresh: Vec<&SubtitleTrack> = tracks
4576 .iter()
4577 .filter(|t| !self.subtitles.iter().any(|o| o.path == t.path && o.track == t.track))
4578 .collect();
4579 if fresh.is_empty() {
4580 return 0;
4581 }
4582 self.snapshot();
4583 let n = fresh.len();
4584 self.subtitles.extend(fresh.into_iter().cloned());
4585 n
4586 }
4587
4588 pub fn add_subtitles(&mut self, track: &SubtitleTrack) -> bool {
4589 if self
4590 .subtitles
4591 .iter()
4592 .any(|t| t.path == track.path && t.track == track.track)
4593 {
4594 return false;
4595 }
4596 self.subtitles.push(track.clone());
4597 true
4598 }
4599
4600 /// Takes the track at `idx` off the list -- what a row's own remove goes
4601 /// through, so whatever an import added can be taken back out. Refused by
4602 /// name for a row this project does not have, rather than a silent no-op:
4603 /// a front-end holding a stale index has picked the wrong row and needs to
4604 /// hear it.
4605 ///
4606 /// Every index past `idx` moves down by one, as [`remove_source`](
4607 /// Project::remove_source)'s do: a caller holding a picked row (an export's
4608 /// [`crate::export::ExportSettings::subtitles`]) has to fix it up or drop
4609 /// it, or it names a different track afterwards. The placements on the
4610 /// lanes are *not* a caller's to fix: a [`SubClip`] names its track by
4611 /// index into this very list, so every one past `idx` is walked down with
4612 /// it here -- the reindex [`remove_source`](Project::remove_source) does
4613 /// for its clips, for its reason.
4614 ///
4615 /// Refused, changing nothing, while anything placed on a subtitle lane
4616 /// plays *this* row: the placement would have to be deleted or retargeted,
4617 /// and either one is an edit nobody asked for. The refusal names the lane
4618 /// and the frame it is at, up to three of them --
4619 /// [`remove_source`](Project::remove_source) refuses the same way for the
4620 /// same silent corruption.
4621 ///
4622 /// One undo step, and the reindex with it: every placement names a track
4623 /// by index into the palette ([`crate::subtitle`]), so a removal that
4624 /// renumbers them can only come back together with the palette it took
4625 /// the row from -- which is what the history entry holds, beside the
4626 /// lanes it also carries ([`Snapshot`]). The inverse, for a caller that
4627 /// wants the file's tracks back, is [`crate::PlaybackSession::import_subtitles`]
4628 /// -- the panel's own door, which reads the subtitles of a file and
4629 /// nothing else.
4630 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
4631 if idx >= self.subtitles.len() {
4632 return Err(format!("there is no subtitle track {idx} to remove").into());
4633 }
4634 let placed: Vec<String> = handles(&self.lanes)
4635 .into_iter()
4636 .zip(&self.lanes)
4637 .flat_map(|(lane, data)| {
4638 data.subs
4639 .iter()
4640 .filter(move |s| s.track == idx)
4641 .map(move |s| format!("{} at frame {}", lane.label(), s.start))
4642 })
4643 .take(3)
4644 .collect();
4645 if !placed.is_empty() {
4646 return Err(format!(
4647 "{} is on the timeline ({}): delete those clips first",
4648 self.track_name(idx),
4649 placed.join(", ")
4650 )
4651 .into());
4652 }
4653 self.snapshot();
4654 self.subtitles.remove(idx);
4655 // The overrides follow their tracks down, as the placements do, and the
4656 // removed row's own go with it: a row added again later is a new read of
4657 // the file, and its words are the file's.
4658 self.cue_edits.retain(|(t, _, _)| *t != idx);
4659 for (t, _, _) in &mut self.cue_edits {
4660 if *t > idx {
4661 *t -= 1;
4662 }
4663 }
4664 self.cue_adds.retain(|a| a.track != idx);
4665 for a in &mut self.cue_adds {
4666 if a.track > idx {
4667 a.track -= 1;
4668 }
4669 }
4670 for s in self.lanes.iter_mut().flat_map(|l| &mut l.subs) {
4671 if s.track > idx {
4672 s.track -= 1;
4673 }
4674 }
4675 Ok(())
4676 }
4677
4678 /// What a refusal calls a palette row: the name the panel shows, and the
4679 /// index alone for a row that is not there.
4680 fn track_name(&self, track: usize) -> String {
4681 self.subtitles
4682 .get(track)
4683 .map_or_else(|| format!("subtitle track {track}"), |t| t.label.clone())
4684 }
4685
4686 /// The subtitle lanes in display order -- what a front-end lays out and
4687 /// what [`sub_lane_cues`](Project::sub_lane_cues) is asked of, the twin of
4688 /// [`audio_lanes`](Project::audio_lanes).
4689 pub fn subtitle_lanes(&self) -> Vec<Lane> {
4690 self.lanes()
4691 .into_iter()
4692 .filter(|l| l.kind == LaneKind::Subtitle)
4693 .collect()
4694 }
4695
4696 /// What is placed on `lane`, in timeline order -- [`Project::lane`]'s twin
4697 /// for a subtitle track, and empty for every other lane and for one that is
4698 /// not there.
4699 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
4700 self.index(lane).map_or(&[][..], |i| &self.lanes[i].subs)
4701 }
4702
4703 /// Put `sub` on `lane` at timeline frame `at` -- [`place`](Project::place)'s
4704 /// twin, with one deliberate difference: it **refuses** an overlap instead
4705 /// of overwriting what it lands on.
4706 ///
4707 /// `at` is where it lands and [`sub.start`](SubClip::start) is ignored,
4708 /// exactly as [`place`](Project::place) ignores a [`Clip`]'s: what a drag
4709 /// carries is a *window of a track* and where the hand let go, and the
4710 /// second of those is the argument. So a caller builds the placement once
4711 /// (from the palette row it dragged) and drops it at as many frames as it
4712 /// likes without rewriting the field each time.
4713 ///
4714 /// A picture placed over a picture hides it and the hidden one is still
4715 /// there to drag back out; two captions in one frame are two lines nobody
4716 /// asked to stack, and the words that lost are gone from the screen with
4717 /// nothing to show for it. So the refusal names the placement in the way,
4718 /// and the caller picks another frame or another lane -- which is what a
4719 /// second subtitle lane is for.
4720 ///
4721 /// One undo step on success, and none on any refusal: an empty window or an
4722 /// empty span, a track the palette does not have
4723 /// ([`Project::subtitles`]), a lane that is not there, a lane that is not a
4724 /// subtitle lane, a span that would run past the last frame there is, and
4725 /// the overlap above.
4726 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
4727 if lane.kind != LaneKind::Subtitle {
4728 return Err(format!(
4729 "{} is not a subtitle track: words go on a subtitle track, pictures and sound on \
4730 the others",
4731 lane.label()
4732 )
4733 .into());
4734 }
4735 let Some(i) = self.index(lane) else {
4736 return Err(format!("there is no {} to place on", lane.label()).into());
4737 };
4738 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4739 return Err(format!(
4740 "that placement is empty: {} frames of [{}, {})",
4741 sub.frames, sub.in_us, sub.out_us
4742 )
4743 .into());
4744 }
4745 // The width of that window, which the check above cannot see: the same
4746 // bound the two file doors hold a placement to
4747 // ([`edith`](crate::edith)'s parse and [`with_subs`]), asked here
4748 // because this is the door a *dragged* caption comes through and the
4749 // hand that dragged it builds the `SubClip` itself.
4750 if sub.out_us - sub.in_us > MAX_WINDOW_US {
4751 return Err(format!(
4752 "that placement is a {}us window, past the {}us a caption can hold",
4753 sub.out_us - sub.in_us,
4754 MAX_WINDOW_US
4755 )
4756 .into());
4757 }
4758 if sub.track >= self.subtitles.len() {
4759 return Err(format!(
4760 "it names subtitle track {} of {}",
4761 sub.track,
4762 self.subtitles.len()
4763 )
4764 .into());
4765 }
4766 // The placement belongs to no group, for [`place`]'s reason: a caption
4767 // dragged out of the palette arrives alone, and grouping it with what
4768 // is under it is a hand's decision ([`Project::group_all`]).
4769 let sub = SubClip {
4770 start: at,
4771 link: None,
4772 ..sub
4773 };
4774 if at.checked_add(sub.frames).is_none() {
4775 return Err(
4776 format!("a placement at frame {at} runs past the last frame there is").into(),
4777 );
4778 }
4779 if let Some(other) = self.lanes[i]
4780 .subs
4781 .iter()
4782 .find(|o| o.end() > sub.start && o.start < sub.end())
4783 {
4784 return Err(format!(
4785 "the {} subtitle at frame {} already covers [{}, {}): move it, or place this one \
4786 on another subtitle track",
4787 lane.label(),
4788 other.start,
4789 other.start,
4790 other.end()
4791 )
4792 .into());
4793 }
4794 self.snapshot();
4795 let subs = &mut self.lanes[i].subs;
4796 let idx = subs.partition_point(|o| o.start < sub.start);
4797 subs.insert(idx, sub);
4798 debug_assert!(subs_sorted_disjoint(subs));
4799 Ok(())
4800 }
4801
4802 /// Move the subtitle at `idx` of `from` onto `to` with its head at `start`
4803 /// -- [`move_clip`](Project::move_clip)'s twin. A caption in no group is
4804 /// refused an overlap where that one clamps to it, for
4805 /// [`place_sub`](Project::place_sub)'s reason: there is no group to hold it
4806 /// still and no picture under it that a landing would hide, so "as far as
4807 /// it goes" would silently be a frame nobody named.
4808 ///
4809 /// A caption *in* a group drags the group: one delta for every member --
4810 /// its clips and its other captions -- clamped to the room each of them
4811 /// has, exactly as a clip's drag always has. That is the point of putting
4812 /// a caption in a group: the words go where the picture goes.
4813 ///
4814 /// The window travels untouched: a caption dragged later says the same
4815 /// words later, exactly as a clip dragged later plays the same pictures
4816 /// later.
4817 ///
4818 /// One undo step on success; nothing changed and no step on a refusal --
4819 /// an index that is not there, a lane that is not a subtitle lane or is not
4820 /// there, and (for a caption in no group) an overlap. A drop that changes
4821 /// neither lane nor frame is `Ok` and no step: a hand that picked a caption
4822 /// up and put it back has done nothing wrong, and a front-end showing every
4823 /// `Err` would say so.
4824 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
4825 let Some(sub) = self.sub_lane(from).get(idx).copied() else {
4826 return Err(format!("there is no subtitle {idx} on {}", from.label()).into());
4827 };
4828 if to.kind != LaneKind::Subtitle {
4829 return Err(format!(
4830 "{} is not a subtitle track: a caption cannot play on it",
4831 to.label()
4832 )
4833 .into());
4834 }
4835 let (Some(here), Some(dest)) = (self.index(from), self.index(to)) else {
4836 return Err(format!("there is no {} to move onto", to.label()).into());
4837 };
4838 if (here, start) == (dest, sub.start) {
4839 // A pick-up-put-back: the drag ended where it began, which is not a
4840 // mistake to name -- `Ok`, and no undo step, because nothing
4841 // changed. A refusal here would toast a hand that did nothing.
4842 return Ok(());
4843 }
4844 if start.checked_add(sub.frames).is_none() {
4845 return Err(
4846 format!("a placement at frame {start} runs past the last frame there is").into(),
4847 );
4848 }
4849 // A grouped caption carries its group, clamped to the room the whole
4850 // group has rather than refused ([`Project::move_room]) -- one drag, one
4851 // delta, one undo step.
4852 let members = self.group_of(from, idx).expect("the subtitle was found");
4853 if !members.alone() {
4854 if members
4855 .subs
4856 .iter()
4857 .any(|&(l, i)| l == dest && (l, i) != (here, idx))
4858 {
4859 return Err(format!(
4860 "a group is one caption per track: {} already carries this group",
4861 to.label()
4862 )
4863 .into());
4864 }
4865 let want = i64::from(start) - i64::from(sub.start);
4866 let Some((lo, hi)) = self.move_room(&members, Some((here, idx, dest, start)), None) else {
4867 return Err(format!(
4868 "another placement already covers those frames on {}",
4869 to.label()
4870 )
4871 .into());
4872 };
4873 let delta = want.clamp(lo, hi);
4874 self.snapshot();
4875 for &(l, i) in &members.clips {
4876 let c = &mut self.lanes[l].clips[i];
4877 c.start = (i64::from(c.start) + delta) as u32;
4878 }
4879 for &(l, i) in &members.subs {
4880 let s = &mut self.lanes[l].subs[i];
4881 s.start = (i64::from(s.start) + delta) as u32;
4882 }
4883 let moved = self.lanes[here].subs.remove(idx);
4884 let subs = &mut self.lanes[dest].subs;
4885 let at = subs.partition_point(|o| o.start < moved.start);
4886 subs.insert(at, moved);
4887 debug_assert!(subs_sorted_disjoint(subs));
4888 debug_assert!(
4889 members
4890 .clips
4891 .iter()
4892 .all(|&(l, _)| sorted_disjoint(&self.lanes[l].clips))
4893 );
4894 return Ok(());
4895 }
4896 let moved = SubClip { start, ..sub };
4897 if let Some(other) = self.lanes[dest]
4898 .subs
4899 .iter()
4900 .enumerate()
4901 .find(|&(j, o)| {
4902 !(dest == here && j == idx) && o.end() > moved.start && o.start < moved.end()
4903 })
4904 .map(|(_, o)| *o)
4905 {
4906 return Err(format!(
4907 "the {} subtitle at frame {} already covers [{}, {})",
4908 to.label(),
4909 other.start,
4910 other.start,
4911 other.end()
4912 )
4913 .into());
4914 }
4915 self.snapshot();
4916 self.lanes[here].subs.remove(idx);
4917 let subs = &mut self.lanes[dest].subs;
4918 let at = subs.partition_point(|o| o.start < moved.start);
4919 subs.insert(at, moved);
4920 debug_assert!(subs_sorted_disjoint(subs));
4921 debug_assert!(subs_sorted_disjoint(&self.lanes[here].subs));
4922 Ok(())
4923 }
4924
4925 /// Move one `edge` of the subtitle at `idx` of `lane` to timeline frame
4926 /// `to` -- [`trim`](Project::trim)'s twin, and clamped like it: a hand
4927 /// pulling an edge past what is legal means "as far as it goes".
4928 ///
4929 /// The window follows the edge, in the seconds the frames are worth at
4930 /// `fps`: a head pulled in starts the caption later *in its track* (the
4931 /// cues that were skipped stay skipped, exactly as a trimmed clip's frames
4932 /// stay behind), and a tail pulled out shows more of it. `fps` is the one
4933 /// thing a [`Project`] does not know -- it is the caller's timeline rate,
4934 /// the same one [`crate::export::timeline_cues`] is asked with -- and it is
4935 /// needed here and nowhere else in this file, because a trim is the only
4936 /// edit that changes a *duration*.
4937 ///
4938 /// The walls: one frame always survives, an edge never crosses the
4939 /// neighbouring subtitle on its own lane, a head never walks back past the
4940 /// track's own start (`in_us` of 0), and a tail never runs past the last
4941 /// cue the track has -- which is the source length a media trim needs a
4942 /// caller's table for, and which this one can simply read.
4943 ///
4944 /// `Err`, with nothing changed and no undo step, for an index that is not
4945 /// there and an unusable `fps`. An edge that ends up where it already was
4946 /// -- the hand did not move it, or the clamp stopped it at a wall it stood
4947 /// against -- is `Ok` and no step, for [`move_sub`](Project::move_sub)'s
4948 /// reason: a drag that stops at a wall is not a mistake to report.
4949 pub fn trim_sub(
4950 &mut self,
4951 lane: Lane,
4952 idx: usize,
4953 edge: Edge,
4954 to: u32,
4955 fps: f64,
4956 ) -> crate::Result<()> {
4957 if !(fps.is_finite() && fps > 0.0) {
4958 return Err(format!("{fps} is not a frame rate to trim against").into());
4959 }
4960 let Some((lo, hi)) = self.trim_sub_room(lane, idx, edge, fps) else {
4961 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
4962 };
4963 let Some(sub) = self.sub_lane(lane).get(idx).copied() else {
4964 return Err(format!("there is no subtitle {idx} on {}", lane.label()).into());
4965 };
4966 let to = to.clamp(lo, hi);
4967 let at = match edge {
4968 Edge::Start => sub.start,
4969 Edge::End => sub.end(),
4970 };
4971 if to == at {
4972 // The edge is where it was asked to go -- either the hand did not
4973 // move it, or the clamp above stopped it at a wall it was already
4974 // standing against. Both are a drag that changed nothing: `Ok`, no
4975 // undo step, and no toast for a box that simply stopped moving.
4976 return Ok(());
4977 }
4978 self.snapshot();
4979 let members = self.group_of(lane, idx).expect("the subtitle was found");
4980 let i = self.index(lane).expect("the subtitle was found on it");
4981 let s = &mut self.lanes[i].subs[idx];
4982 match edge {
4983 // The words that stay are the words that were there, so the window
4984 // moves with the head -- a trim, not a slip.
4985 Edge::Start => {
4986 // The head moves and the words that stay are the words that
4987 // were there, so `in_us` follows it -- a trim, not a slip.
4988 // Falling `in_us` makes the window *wider* (the ceiling bounds
4989 // a difference), which is the half of this nothing here can
4990 // see: `set_window` is what puts the width back inside.
4991 set_window(
4992 s,
4993 s.in_us
4994 .saturating_add(us_of(i64::from(to) - i64::from(s.start), fps)),
4995 s.out_us,
4996 );
4997 s.frames = s.end() - to;
4998 s.start = to;
4999 }
5000 Edge::End => {
5001 // ...and the tail, for [`set_window`]'s reason: the End room
5002 // is walled at the ceiling, but `set_window` is what holds it
5003 // for every other composer too, including this one when a
5004 // caller hands `trim_sub` a `to` past its own room.
5005 set_window(
5006 s,
5007 s.in_us,
5008 s.out_us
5009 .saturating_add(us_of(i64::from(to) - i64::from(s.end()), fps)),
5010 );
5011 s.frames = to - s.start;
5012 }
5013 }
5014 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
5015 debug_assert!(subs_sorted_disjoint(&self.lanes[i].subs));
5016 // A caption in a group drags its group's edge with it, exactly as a
5017 // clip's trim does: one delta, each member clamped to its own room.
5018 // No source table to grow by, which only tightens how far a member may
5019 // follow -- never whether it may.
5020 self.follow_group(
5021 &members,
5022 &(i, idx),
5023 edge,
5024 i64::from(to) - i64::from(at),
5025 SourceWalls::same(&[]),
5026 );
5027 Ok(())
5028 }
5029
5030 /// How far that edge may travel, `(first, last)` timeline frame inclusive
5031 /// -- [`trim_room`](Project::trim_room)'s twin, and what a front-end
5032 /// drawing the box during a drag asks. `None` for an index that is not
5033 /// there.
5034 pub fn trim_sub_room(
5035 &self,
5036 lane: Lane,
5037 idx: usize,
5038 edge: Edge,
5039 fps: f64,
5040 ) -> Option<(u32, u32)> {
5041 let subs = self.sub_lane(lane);
5042 let s = *subs.get(idx)?;
5043 // How many timeline frames a stretch of the track is worth, which is
5044 // what turns its two walls -- its own start, and its last cue -- into
5045 // frames. A rate that is not a rate leaves the window where it is.
5046 let frames_of = |us: i64| match fps.is_finite() && fps > 0.0 {
5047 true => ((us as f64) * fps / 1e6)
5048 .round()
5049 .max(0.0)
5050 .min(f64::from(u32::MAX)) as u32,
5051 false => 0,
5052 };
5053 Some(match edge {
5054 Edge::Start => (
5055 s.start
5056 .saturating_sub(frames_of(s.in_us))
5057 .max(idx.checked_sub(1).map_or(0, |p| subs[p].end())),
5058 s.end() - 1,
5059 ),
5060 Edge::End => {
5061 // Out to the end of the track it reads, and never over the
5062 // subtitle behind it. A track the palette no longer has (or one
5063 // with no cues at all) may not grow, exactly as a source with no
5064 // entry in a media trim's table may not.
5065 let track_end = self
5066 .subtitles
5067 .get(s.track)
5068 .and_then(|t| t.cues.iter().map(|c| c.end_us).max())
5069 .unwrap_or(s.out_us);
5070 // ...and never past [`grow_window`]'s ceiling, which is the
5071 // wall that matters here: a front-end asks this to draw the
5072 // drag, then trims to whatever it is told. An engine that
5073 // offers room its own trim would refuse is a drag that snaps
5074 // back at the end of the gesture -- so the room stops where
5075 // the window stops, and the two agree by construction.
5076 let wall_us = track_end.min(s.in_us.saturating_add(MAX_WINDOW_US));
5077 (
5078 s.start + 1,
5079 s.start
5080 .saturating_add(frames_of((wall_us - s.in_us).max(1)))
5081 .min(subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
5082 )
5083 }
5084 })
5085 }
5086
5087 /// Take the subtitle at `idx` off `lane`, leaving a gap and moving nothing
5088 /// else -- [`lift`](Project::lift)'s twin, and one undo step like it.
5089 /// `false` for an index that is not there (which a lane that is not a
5090 /// subtitle lane always is).
5091 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
5092 let Some(i) = self.index(lane).filter(|_| idx < self.sub_lane(lane).len()) else {
5093 return false;
5094 };
5095 self.snapshot();
5096 self.lanes[i].subs.remove(idx);
5097 true
5098 }
5099
5100 /// Retypes one cue's words: cue `cue` of subtitle track `track`. The words
5101 /// belong to the **track**, not to one placement, so every placement of that
5102 /// track shows the new text -- a subtitle file's line is one line however
5103 /// many times the film plays it, and that is why this is a palette edit and
5104 /// not a placement one.
5105 ///
5106 /// `false`, changing nothing and taking no undo step, for a row or a cue
5107 /// that is not there, for a picture cue (a display set has no words), and
5108 /// for text the cue already has. Empty text is not a blank cue: it deletes
5109 /// the cue ([`delete_cue`](Project::delete_cue)), which is the one way a cue
5110 /// leaves a track. The edit is kept in [`cue_edits`](Project::cue_edits),
5111 /// which a save writes and a reopen puts back over the file's own words
5112 /// ([`with_cue_edits`](Project::with_cue_edits)).
5113 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
5114 if text.is_empty() {
5115 return self.delete_cue(track, cue);
5116 }
5117 let Some(c) = self.subtitles.get(track).and_then(|t| t.cues.get(cue)) else {
5118 return false;
5119 };
5120 if c.image.is_some() || c.text == text {
5121 return false;
5122 }
5123 let added = self.added_index(track, cue);
5124 let orig = if added.is_none() { self.original_cue_index(track, cue) } else { 0 };
5125 self.snapshot();
5126 self.subtitles[track].cues[cue].text = text.to_string();
5127 match added {
5128 Some(i) => self.cue_adds[i].text = text.to_string(),
5129 None => self.record_cue_edit(track, orig, text),
5130 }
5131 true
5132 }
5133
5134 /// Removes one cue from subtitle track `track`, as [`set_cue_text`](Project::set_cue_text)
5135 /// names it. The track is the palette every placement of it shows, so the
5136 /// cue is gone from each of them; no placement moves, since a cue's place is
5137 /// its own time in the file, and the cues after it keep theirs. One undo step.
5138 ///
5139 /// `false` for a track or cue that is not there. A picture cue can go too.
5140 /// The removal is kept in [`cue_edits`](Project::cue_edits) as an empty text
5141 /// on the cue's file index, so a reopen takes the same cue out again.
5142 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
5143 if self.subtitles.get(track).is_none_or(|t| cue >= t.cues.len()) {
5144 return false;
5145 }
5146 self.snapshot();
5147 self.drop_cue(track, cue);
5148 true
5149 }
5150
5151 /// Adds a cue to subtitle track `track`, on the track's own clock: `start_us`
5152 /// to `end_us` in microseconds, with `text` (`\n` between lines). It is kept
5153 /// in the track's cue list at its start, shows in every placement of the
5154 /// track, and is written by a save as a [`AddedCue`]. Returns its index in
5155 /// the track.
5156 ///
5157 /// Refused, changing nothing and taking no undo step, for a track that is
5158 /// not there, empty text, an end that is not after the start, a picture
5159 /// track, and a cue that overlaps one already there -- unless `overwrite`,
5160 /// which removes every overlapped cue first. Both the add and those removals
5161 /// are one undo step.
5162 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
5163 let Some(t) = self.subtitles.get(track) else {
5164 return Err(format!("there is no subtitle track {track}").into());
5165 };
5166 if text.is_empty() {
5167 return Err("a cue needs words: empty text adds no cue".into());
5168 }
5169 if end_us <= start_us {
5170 return Err(format!("a cue must end after it starts ({start_us} µs to {end_us} µs)").into());
5171 }
5172 if t.cues.iter().any(|c| c.image.is_some()) {
5173 return Err(format!("track {track} is pictures, not text: a text cue cannot be added to it").into());
5174 }
5175 let clash: Vec<usize> = t
5176 .cues
5177 .iter()
5178 .enumerate()
5179 .filter(|(_, c)| c.start_us < end_us && start_us < c.end_us)
5180 .map(|(i, _)| i)
5181 .collect();
5182 if let (false, Some(&first)) = (overwrite, clash.first()) {
5183 return Err(format!("track {track} cue {first} overlaps the new cue: pass overwrite to replace it").into());
5184 }
5185 self.snapshot();
5186 // Highest first, so each position still names the cue it named.
5187 for &i in clash.iter().rev() {
5188 self.drop_cue(track, i);
5189 }
5190 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5191 self.subtitles[track].cues.insert(
5192 at,
5193 crate::subtitle::Cue { start_us, end_us, text: text.to_string(), image: None, words: Vec::new(), karaoke: Vec::new() },
5194 );
5195 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5196 Ok(at)
5197 }
5198
5199 /// Divides every text cue of track `track` that straddles `t_us` (on the
5200 /// track's own clock) into two cues at `t_us`, one undo step. Each cue's
5201 /// words are shared out at the word boundary nearest the proportional point
5202 /// ([`split_words`]), so a window edge that falls inside a sentence leaves
5203 /// each side only the words it covers, and a piece with no words is dropped.
5204 ///
5205 /// `false`, changing nothing and taking no undo step, when no cue straddles
5206 /// `t_us`. A picture cue is never split.
5207 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
5208 let straddles = self
5209 .subtitles
5210 .get(track)
5211 .is_some_and(|t| {
5212 t.cues
5213 .iter()
5214 .any(|c| c.image.is_none() && c.start_us < t_us && t_us < c.end_us && split_words(c, t_us).is_some())
5215 });
5216 if !straddles {
5217 return false;
5218 }
5219 self.snapshot();
5220 self.split_cue_raw(track, t_us, false);
5221 true
5222 }
5223
5224 /// The room cue `cue` of track `track` has to move or trim in, on the track's
5225 /// own clock: from the end of the cue before it (or 0) to the start of the cue
5226 /// after it (or the end of time). `None` for a cue that is not there.
5227 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
5228 let t = self.subtitles.get(track)?;
5229 let c = t.cues.get(cue)?;
5230 let lo = cue.checked_sub(1).map_or(0, |p| t.cues[p].end_us.min(c.start_us));
5231 let hi = t.cues.get(cue + 1).map_or(i64::MAX, |n| n.start_us.max(c.end_us));
5232 Some((lo, hi))
5233 }
5234
5235 /// Where timeline time `tl_us` falls on the track's own clock, through the
5236 /// placement on `lane` that shows cue `cue` of `track` (extrapolated when it is
5237 /// outside the cue's shown part). `None` when no placement on `lane` shows it.
5238 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64, fps: f64) -> Option<i64> {
5239 let s = self.sub_lane_cue_spans(lane, fps).into_iter().find(|s| s.track == track && s.cue == cue)?;
5240 let (shown, window) = ((s.end_us - s.start_us).max(1) as f64, (s.window.1 - s.window.0) as f64);
5241 Some(s.window.0 + ((tl_us - s.start_us) as f64 * window / shown).round() as i64)
5242 }
5243
5244 /// Gives cue `cue` of `track` new times and words, kept the way a cue add keeps
5245 /// them: an added cue's entry is updated, a file cue is removed as
5246 /// [`drop_cue`](Project::drop_cue) does and re-added with its new times. The cue
5247 /// keeps its place in the track. No undo step of its own.
5248 fn rewrite_cue_raw(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64, text: &str) {
5249 match self.added_index(track, cue) {
5250 Some(i) => {
5251 let a = &mut self.cue_adds[i];
5252 (a.start_us, a.end_us, a.text) = (start_us, end_us, text.to_string());
5253 }
5254 None => {
5255 let orig = self.original_cue_index(track, cue);
5256 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5257 self.cue_edits.push((track, orig, String::new()));
5258 self.cue_adds.push(AddedCue { track, start_us, end_us, text: text.to_string() });
5259 }
5260 }
5261 let c = &mut self.subtitles[track].cues[cue];
5262 (c.start_us, c.end_us, c.text) = (start_us, end_us, text.to_string());
5263 }
5264
5265 /// Moves or trims one cue: new `start_us` and `end_us` on the track's own clock,
5266 /// kept inside its neighbours ([`cue_room`](Project::cue_room)) and at least
5267 /// [`MIN_CUE_US`] long. One undo step. `Ok(false)`, with none, when the times are
5268 /// the cue's own; `Err` for a cue that is not there, a picture cue, or times
5269 /// that break those rules.
5270 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
5271 let Some((lo, hi)) = self.cue_room(track, cue) else {
5272 return Err(format!("track {track} has no cue {cue}").into());
5273 };
5274 let c = &self.subtitles[track].cues[cue];
5275 if c.image.is_some() {
5276 return Err("a picture cue has no times to set".into());
5277 }
5278 if (c.start_us, c.end_us) == (start_us, end_us) {
5279 return Ok(false);
5280 }
5281 if end_us - start_us < MIN_CUE_US {
5282 return Err(format!("a cue is at least {} ms long", MIN_CUE_US / 1000).into());
5283 }
5284 if start_us < lo || end_us > hi {
5285 return Err("the cue would run into its neighbour".into());
5286 }
5287 let text = c.text.clone();
5288 self.snapshot();
5289 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5290 Ok(true)
5291 }
5292
5293 /// Joins cue `cue` of `track` with the one after it: one cue from the first's
5294 /// start to the second's end, the words one after the other (a space between),
5295 /// whatever lay between them now inside it. One undo step. `Err`, changing
5296 /// nothing, for a cue with none after it or a picture cue.
5297 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
5298 let Some(t) = self.subtitles.get(track) else {
5299 return Err(format!("there is no subtitle track {track}").into());
5300 };
5301 let (Some(a), Some(b)) = (t.cues.get(cue), t.cues.get(cue + 1)) else {
5302 return Err("there is no cue after it to merge with".into());
5303 };
5304 if a.image.is_some() || b.image.is_some() {
5305 return Err("a picture cue cannot be merged".into());
5306 }
5307 let text = format!("{} {}", a.text.trim_end(), b.text.trim_start());
5308 let (start_us, end_us) = (a.start_us, b.end_us.max(a.end_us));
5309 let (words, karaoke) = (b.words.clone(), b.karaoke.clone());
5310 self.snapshot();
5311 self.drop_cue(track, cue + 1);
5312 self.rewrite_cue_raw(track, cue, start_us, end_us, &text);
5313 let c = &mut self.subtitles[track].cues[cue];
5314 c.words.extend(words);
5315 c.karaoke.extend(karaoke);
5316 Ok(())
5317 }
5318
5319 /// Splits the cues of every subtitle lane in `on` at the window edges a cut
5320 /// at each of `frames` would make: a placement that strictly straddles a
5321 /// frame gets its window's point there ([`SubClip::window_at`]), and each
5322 /// cue crossing that point is divided. No undo step of its own; the caller
5323 /// has taken its snapshot. Called before the lanes move, so the windows are
5324 /// the ones the cut will split.
5325 ///
5326 /// `both_sides` keeps a one-word cue on both sides of a point
5327 /// ([`cut_pieces`]), for a cut: which side the cut leaves in a window is
5328 /// only known after the ripple, so the caller drops the other one with
5329 /// [`drop_unplaced`](Project::drop_unplaced). A split (`false`) keeps the
5330 /// word on one side only. Returns the pieces made, `(track, start_us, end_us)`.
5331 fn split_cues_across(&mut self, on: &[usize], frames: &[u32], both_sides: bool) -> Vec<(usize, i64, i64)> {
5332 let mut points: Vec<(usize, i64)> = Vec::new();
5333 // A placement that both edges of a cut fall inside: its track and the two window points.
5334 let mut spans: Vec<(usize, i64, i64)> = Vec::new();
5335 for &i in on {
5336 for s in &self.lanes[i].subs {
5337 let inside: Vec<i64> = frames
5338 .iter()
5339 .filter(|&&f| s.start < f && f < s.end())
5340 .map(|&f| s.window_at(f))
5341 .collect();
5342 points.extend(inside.iter().map(|&t| (s.track, t)));
5343 if let [a, b] = inside[..] {
5344 spans.push((s.track, a, b));
5345 }
5346 }
5347 }
5348 let mut pieces = Vec::new();
5349 for (track, a, b) in spans {
5350 pieces.extend(self.keep_one_word_outside(track, a, b));
5351 }
5352 for (track, t) in points {
5353 pieces.extend(self.split_cue_raw(track, t, both_sides));
5354 }
5355 pieces
5356 }
5357
5358 /// A cut from `a` to `b` through the middle of a one-word cue: the word is
5359 /// kept on whichever side the cut leaves longer (ties: the side before), and
5360 /// the removed middle and the other side are dropped, as [`split_words`]
5361 /// does for a single edge. A cue with more words is left for
5362 /// [`split_cue_raw`](Project::split_cue_raw) to divide at each edge.
5363 fn keep_one_word_outside(&mut self, track: usize, a: i64, b: i64) -> Vec<(usize, i64, i64)> {
5364 let Some(t) = self.subtitles.get(track) else {
5365 return Vec::new();
5366 };
5367 let crossing: Vec<usize> = t
5368 .cues
5369 .iter()
5370 .enumerate()
5371 .filter(|(_, c)| {
5372 c.image.is_none() && c.start_us < a && b < c.end_us && c.text.split_whitespace().count() == 1
5373 })
5374 .map(|(i, _)| i)
5375 .collect();
5376 let mut pieces = Vec::new();
5377 for &i in crossing.iter().rev() {
5378 let cue = self.subtitles[track].cues[i].clone();
5379 let text = cue.text.trim().to_string();
5380 let (start_us, end_us) = if a - cue.start_us >= cue.end_us - b {
5381 (cue.start_us, a)
5382 } else {
5383 (b, cue.end_us)
5384 };
5385 self.drop_cue(track, i);
5386 self.add_piece(track, start_us, end_us, text);
5387 pieces.push((track, start_us, end_us));
5388 }
5389 pieces
5390 }
5391
5392 /// Puts one piece of a divided cue into `track` at its start time, and keeps
5393 /// it the way a cue add keeps it (an [`AddedCue`]), so a save and a reopen
5394 /// give back the same cues.
5395 fn add_piece(&mut self, track: usize, start_us: i64, end_us: i64, text: String) {
5396 let at = self.subtitles[track].cues.partition_point(|c| c.start_us <= start_us);
5397 self.subtitles[track]
5398 .cues
5399 .insert(at, crate::subtitle::Cue { start_us, end_us, text: text.clone(), image: None, words: Vec::new(), karaoke: Vec::new() });
5400 self.cue_adds.push(AddedCue { track, start_us, end_us, text });
5401 }
5402
5403 /// [`split_cues_at`](Project::split_cues_at) with no snapshot and no check:
5404 /// each cue of `track` straddling `t_us` is replaced by its pieces, cut by
5405 /// [`cut_pieces`] with `both_sides`. The pieces are kept the way a cue add
5406 /// keeps them -- the file's cue is removed as [`drop_cue`](Project::drop_cue)
5407 /// does and each piece is an [`AddedCue`] -- so a save and a reopen give back
5408 /// the same cues. Returns the pieces made, `(track, start_us, end_us)`.
5409 fn split_cue_raw(&mut self, track: usize, t_us: i64, both_sides: bool) -> Vec<(usize, i64, i64)> {
5410 let Some(t) = self.subtitles.get(track) else {
5411 return Vec::new();
5412 };
5413 let crossing: Vec<usize> = t
5414 .cues
5415 .iter()
5416 .enumerate()
5417 .filter(|(_, c)| c.image.is_none() && c.start_us < t_us && t_us < c.end_us)
5418 .map(|(i, _)| i)
5419 .collect();
5420 let mut made = Vec::new();
5421 // Highest first, so each index still names the cue it named.
5422 for &i in crossing.iter().rev() {
5423 let cue = self.subtitles[track].cues[i].clone();
5424 let Some(pieces) = cut_pieces(&cue, t_us, both_sides) else {
5425 continue;
5426 };
5427 self.drop_cue(track, i);
5428 for (start_us, end_us, text) in pieces {
5429 self.add_piece(track, start_us, end_us, text);
5430 made.push((track, start_us, end_us));
5431 }
5432 }
5433 made
5434 }
5435
5436 /// The tracks a cut over the lanes `on` can change the windows of: the
5437 /// tracks their placements show, each once.
5438 fn caption_tracks_on(&self, on: &[usize]) -> Vec<usize> {
5439 let mut tracks: Vec<usize> = on.iter().flat_map(|&i| self.lanes[i].subs.iter().map(|s| s.track)).collect();
5440 tracks.sort_unstable();
5441 tracks.dedup();
5442 tracks
5443 }
5444
5445 /// Every placement window of every lane, as `(track, in_us, out_us)`.
5446 fn windows(&self) -> Vec<(usize, i64, i64)> {
5447 self.lanes
5448 .iter()
5449 .flat_map(|l| l.subs.iter())
5450 .map(|s| (s.track, s.in_us, s.out_us))
5451 .collect()
5452 }
5453
5454 /// The cues of `tracks` that some placement window covers now (overlaps
5455 /// it), as `(track, start_us, end_us)`.
5456 fn placed_cues(&self, tracks: &[usize]) -> Vec<(usize, i64, i64)> {
5457 let windows = self.windows();
5458 let mut out = Vec::new();
5459 for &t in tracks {
5460 let Some(track) = self.subtitles.get(t) else {
5461 continue;
5462 };
5463 for c in &track.cues {
5464 if windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us) {
5465 out.push((t, c.start_us, c.end_us));
5466 }
5467 }
5468 }
5469 out
5470 }
5471
5472 /// After a cut, drops the track cues it left outside every placement window
5473 /// of their track. A cue is dropped only if it is one the cut touched:
5474 /// `placed` is the cues a window covered before the cut, and `pieces` the
5475 /// ones the cut made ([`split_cues_across`](Project::split_cues_across)). A
5476 /// cue no placement ever covered (a caption placed over a part of its track,
5477 /// say) is not the cut's to remove, so it stays for a later placement.
5478 ///
5479 /// The cut leaves the words it removed, or the side of a divided cue it
5480 /// cut away, outside every window -- those are the orphans this drops. The
5481 /// piece a window still covers stays, with its words.
5482 fn drop_unplaced(&mut self, tracks: &[usize], placed: &[(usize, i64, i64)], pieces: &[(usize, i64, i64)]) {
5483 let windows = self.windows();
5484 for &t in tracks {
5485 let Some(mut i) = self.subtitles.get(t).map(|tr| tr.cues.len()) else {
5486 continue;
5487 };
5488 // Last first, so dropping one leaves the indices before it true.
5489 while i > 0 {
5490 i -= 1;
5491 let Some(c) = self.subtitles.get(t).and_then(|tr| tr.cues.get(i)) else {
5492 continue;
5493 };
5494 let key = (t, c.start_us, c.end_us);
5495 let touched = placed.contains(&key) || pieces.contains(&key);
5496 let covered = windows.iter().any(|&(w, a, b)| w == t && c.start_us < b && a < c.end_us);
5497 if touched && !covered {
5498 self.drop_cue(t, i);
5499 }
5500 }
5501 }
5502 }
5503
5504 /// Takes cue `cue` out of track `track` with no undo step of its own. An
5505 /// added cue leaves the added list; a file cue's removal is kept as an
5506 /// empty override on its file index.
5507 fn drop_cue(&mut self, track: usize, cue: usize) {
5508 match self.added_index(track, cue) {
5509 Some(i) => {
5510 self.cue_adds.remove(i);
5511 }
5512 None => {
5513 let orig = self.original_cue_index(track, cue);
5514 self.cue_edits.retain(|(t, c, _)| !(*t == track && *c == orig));
5515 self.cue_edits.push((track, orig, String::new()));
5516 }
5517 }
5518 self.subtitles[track].cues.remove(cue);
5519 }
5520
5521 /// Which entry of [`cue_adds`](Project::cue_adds) cue `cue` of track `track`
5522 /// is, if it was added rather than read from the file. An added cue is found
5523 /// by its times: no file cue overlaps one, since adding it refused that.
5524 fn added_index(&self, track: usize, cue: usize) -> Option<usize> {
5525 let c = self.subtitles.get(track)?.cues.get(cue)?;
5526 self.cue_adds
5527 .iter()
5528 .position(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us)
5529 }
5530
5531 /// The file's index of cue `cue` of track `track`, which is not an added
5532 /// one. The cue overrides name cues by where the file has them, so a cue
5533 /// after a removed one keeps its index there while its position in the
5534 /// track moves down: this counts the file's cues before `cue` in the track
5535 /// (added ones have no file index), then walks the file past the removed
5536 /// ones to that survivor.
5537 fn original_cue_index(&self, track: usize, cue: usize) -> usize {
5538 let removed: Vec<usize> = self
5539 .cue_edits
5540 .iter()
5541 .filter(|(t, _, text)| *t == track && text.is_empty())
5542 .map(|(_, c, _)| *c)
5543 .collect();
5544 let before = self.subtitles[track]
5545 .cues
5546 .iter()
5547 .take(cue)
5548 .filter(|c| !self.cue_adds.iter().any(|a| a.track == track && a.start_us == c.start_us && a.end_us == c.end_us))
5549 .count();
5550 let (mut orig, mut seen) = (0usize, 0usize);
5551 loop {
5552 if !removed.contains(&orig) {
5553 if seen == before {
5554 return orig;
5555 }
5556 seen += 1;
5557 }
5558 orig += 1;
5559 }
5560 }
5561
5562 /// Keeps one override in the save list, replacing an earlier one for the
5563 /// same cue so a cue is written once however often it was retyped. `cue` is
5564 /// the file's index ([`original_cue_index`](Project::original_cue_index)).
5565 fn record_cue_edit(&mut self, track: usize, cue: usize, text: &str) {
5566 match self
5567 .cue_edits
5568 .iter_mut()
5569 .find(|(t, c, _)| *t == track && *c == cue)
5570 {
5571 Some(edit) => edit.2 = text.to_string(),
5572 None => self.cue_edits.push((track, cue, text.to_string())),
5573 }
5574 }
5575
5576 /// The cue overrides a save writes, `(track, cue, text)` each, the cue by
5577 /// its index in the file it came from; empty text is a cue removed -- see
5578 /// [`set_cue_text`](Project::set_cue_text) and [`delete_cue`](Project::delete_cue).
5579 pub fn cue_edits(&self) -> &[(usize, usize, String)] {
5580 &self.cue_edits
5581 }
5582
5583 /// The cues added to tracks ([`AddedCue`]), in the order they were added: what
5584 /// a save writes after [`cue_edits`](Project::cue_edits).
5585 pub fn cue_adds(&self) -> &[AddedCue] {
5586 &self.cue_adds
5587 }
5588
5589 /// Puts saved added cues back into their tracks, after the file's cues and
5590 /// the overrides ([`with_cue_edits`](Project::with_cue_edits)), each at its
5591 /// start. An added cue naming a track the file no longer has is kept, so a
5592 /// re-save does not lose it, and is not shown.
5593 pub fn with_cue_adds(mut self, adds: &[AddedCue]) -> Self {
5594 for a in adds {
5595 if let Some(t) = self.subtitles.get_mut(a.track) {
5596 let at = t.cues.partition_point(|c| c.start_us <= a.start_us);
5597 t.cues.insert(
5598 at,
5599 crate::subtitle::Cue { start_us: a.start_us, end_us: a.end_us, text: a.text.clone(), image: None, words: Vec::new(), karaoke: Vec::new() },
5600 );
5601 }
5602 self.cue_adds.push(a.clone());
5603 }
5604 self
5605 }
5606
5607 /// Puts saved cue overrides back over the tracks a load read -- the door a
5608 /// load uses, like [`with_subtitles`](Project::with_subtitles), and no undo
5609 /// step for the same reason. Retyped words go on first, then the removed
5610 /// cues come out, last index first, so each still names the file's cue. An
5611 /// override naming a track or cue the file no longer has is kept, so a
5612 /// re-save does not lose it, and changes nothing.
5613 pub fn with_cue_edits(mut self, edits: &[(usize, usize, String)]) -> Self {
5614 let mut removed: Vec<(usize, usize)> = Vec::new();
5615 for (track, cue, text) in edits {
5616 if text.is_empty() {
5617 removed.push((*track, *cue));
5618 } else if let Some(c) = self
5619 .subtitles
5620 .get_mut(*track)
5621 .and_then(|t| t.cues.get_mut(*cue))
5622 .filter(|c| c.image.is_none())
5623 {
5624 c.text = text.clone();
5625 }
5626 self.record_cue_edit(*track, *cue, text);
5627 }
5628 removed.sort_unstable_by(|a, b| b.cmp(a));
5629 removed.dedup();
5630 for (track, cue) in removed {
5631 if let Some(t) = self.subtitles.get_mut(track).filter(|t| cue < t.cues.len()) {
5632 t.cues.remove(cue);
5633 }
5634 }
5635 self
5636 }
5637
5638 /// What `lane` shows, as cues on the **timeline's** clock: every placement's
5639 /// window of its track, clipped to that window and shifted to where the
5640 /// placement sits. The map [`crate::export::timeline_cues`] is for a track
5641 /// carried through the picture's spans -- this is its twin for a track that
5642 /// is placed on a lane of its own, and it is what a preview draws and what
5643 /// an export of the lane would write.
5644 ///
5645 /// Cut, not stretched: a cue half inside the window keeps the half that is
5646 /// inside, and a cue wholly outside it is gone -- the same rule the media
5647 /// spans follow. `fps` is the timeline's rate, needed here because a
5648 /// placement's *position* is in frames while its words are in microseconds.
5649 ///
5650 /// Pure and cheap enough to ask per repaint (a walk of the placements and
5651 /// of their cues, no file opened), which is how a front-end asks it.
5652 pub fn sub_lane_cues(&self, lane: Lane, fps: f64) -> Vec<SubtitleCue> {
5653 self.sub_lane_cue_spans(lane, fps)
5654 .into_iter()
5655 .filter_map(|s| {
5656 let cue = self.subtitles.get(s.track)?.cues.get(s.cue)?;
5657 Some(SubtitleCue {
5658 start_us: s.start_us,
5659 end_us: s.end_us,
5660 text: cue.text.clone(),
5661 image: cue.image.clone(),
5662 words: crate::subtitle::map_words(&cue.words, s.window, (s.start_us, s.end_us)),
5663 karaoke: crate::subtitle::map_karaoke(&cue.karaoke, s.window, (s.start_us, s.end_us)),
5664 })
5665 })
5666 .collect()
5667 }
5668
5669 /// [`sub_lane_cues`](Project::sub_lane_cues) with the cue each entry is: the
5670 /// same entries in the same order, as `(start_us, end_us, track, cue)`, so a
5671 /// front-end can hit-test a drawn cue and name the words it would edit
5672 /// ([`set_cue_text`](Project::set_cue_text)). Built by the same walk, so the
5673 /// two cannot disagree about which cue is where.
5674 pub fn sub_lane_cue_refs(&self, lane: Lane, fps: f64) -> Vec<(i64, i64, usize, usize)> {
5675 self.sub_lane_cue_spans(lane, fps)
5676 .into_iter()
5677 .map(|s| (s.start_us, s.end_us, s.track, s.cue))
5678 .collect()
5679 }
5680
5681 /// [`sub_lane_cue_refs`](Project::sub_lane_cue_refs) with the stretch of the cue's own clock
5682 /// each entry shows, which is what its words are moved by ([`crate::subtitle::map_words`]).
5683 pub fn sub_lane_cue_spans(&self, lane: Lane, fps: f64) -> Vec<CueSpan> {
5684 // A hidden lane has no cues at all: the screen draws none and the
5685 // export writes no track for it (its empty cue list is what drops it).
5686 if !(fps.is_finite() && fps > 0.0) || self.lane_hidden(lane) {
5687 return Vec::new();
5688 }
5689 let mut out = Vec::new();
5690 for s in self.sub_lane(lane) {
5691 let Some(track) = self.subtitles.get(s.track) else {
5692 // A placement whose track was taken off the palette
5693 // ([`Project::remove_subtitles`]) shows nothing rather than
5694 // showing another track's words.
5695 continue;
5696 };
5697 // Where the placement's own first microsecond lands on the
5698 // timeline, and how many microseconds of timeline one microsecond
5699 // of the window is worth: the placement's own proportion, which a
5700 // group's re-rate changes (the frames compress, the window does
5701 // not -- [`write_speed`]'s law). At unity the ratio is 1.0 and
5702 // every cue lands where it always did; at 2x the words cross the
5703 // screen in half the time, cue for cue.
5704 let per = f64::from(s.frames) / fps * 1e6 / (s.window_us().max(1) as f64);
5705 let onto = |t: i64| {
5706 (f64::from(s.start) / fps * 1e6 + (t - s.in_us) as f64 * per).round() as i64
5707 };
5708 for (i, cue) in track.cues.iter().enumerate() {
5709 let (a, b) = (cue.start_us.max(s.in_us), cue.end_us.min(s.out_us));
5710 if b <= a {
5711 continue; // wholly outside the window this placement keeps
5712 }
5713 let (from, to) = (onto(a), onto(b));
5714 // Frames the cue keeps on the timeline (the +1 is the microsecond
5715 // rounding gives back).
5716 let kept = ((to - from) as f64 + 1.0) * fps / 1e6;
5717 // Shorter than one timeline frame: a timeline cannot show it. A
5718 // cue a window edge shortened (a cut met it, or a trim) is also
5719 // a sliver under [`CUT_SLIVER_FRAMES`]: the words a cut leaves
5720 // at the very edge of a cue flash past too quickly to read, so
5721 // they are not a cue. A cue short in the file itself keeps the
5722 // one-frame floor, as it always had.
5723 let clipped = a != cue.start_us || b != cue.end_us;
5724 if kept < 1.0 || (clipped && kept < CUT_SLIVER_FRAMES) {
5725 continue;
5726 }
5727 out.push(CueSpan { start_us: from, end_us: to, track: s.track, cue: i, window: (a, b) });
5728 }
5729 }
5730 // The placements come in timeline order, but two lanes' worth (or a
5731 // track whose cues a window reordered) do not.
5732 out.sort_by_key(|c| c.start_us);
5733 out
5734 }
5735
5736 /// What each of [`audio_segments_from`](Project::audio_segments_from)'s
5737 /// lanes is multiplied by on its way into the mix: the same lanes in the
5738 /// same order, as *amplitudes*, so the mixer never sees a decibel. `1.0`
5739 /// for a lane nobody has turned, which is a multiply f32 leaves alone --
5740 /// the bit-exact path.
5741 ///
5742 /// A muted lane is `0.0`: silence in the same sum, so the mix, the single
5743 /// stream test ([`AudioSession::is_mixed`]) and the export all see the one
5744 /// answer. Its clips and its volume are left as they are.
5745 pub fn audio_gains(&self) -> Vec<f32> {
5746 self.audio_lanes()
5747 .into_iter()
5748 .map(|lane| match self.lane_muted(lane) {
5749 true => 0.0,
5750 false => db_to_linear(self.lane_gain_db(lane)),
5751 })
5752 .collect()
5753 }
5754
5755 /// The ducks, in the same order and as long as
5756 /// [`audio_gains`](Project::audio_gains): what the mixer reads beside the
5757 /// gains. A duck names its key by the key's [`Lane::ord`], which is stable
5758 /// while lanes are emptied and refilled; here it is rewritten to the key's
5759 /// position in the mix, and dropped when that key is not in the mix at all
5760 /// (an empty audio lane is not one), which leaves the lane unducked rather
5761 /// than ducked under silence it could not hear.
5762 pub fn audio_ducks(&self) -> Vec<Vec<Duck>> {
5763 let mixed = self.audio_lanes();
5764 mixed
5765 .iter()
5766 .map(|&lane| {
5767 self.lane_duck_list(lane)
5768 .into_iter()
5769 .filter_map(|duck| {
5770 let key = Lane::new(LaneKind::Audio, duck.under);
5771 let at = mixed.iter().position(|&l| l == key)?;
5772 Some(Duck { under: at, ..duck })
5773 })
5774 .collect()
5775 })
5776 .collect()
5777 }
5778
5779 /// The voice processors, in the same order and as long as
5780 /// [`audio_gains`](Project::audio_gains): what the mix opens each lane
5781 /// through. All off for a project nobody has cleaned, which is the path
5782 /// that decodes the same samples it always did.
5783 pub fn audio_voices(&self) -> Vec<VoiceFx> {
5784 self.audio_lanes()
5785 .into_iter()
5786 .map(|lane| self.lane_voice(lane))
5787 .collect()
5788 }
5789
5790 /// The master limiter the mix is summed through. A project setting, not a
5791 /// clip's and not a lane's: there is one mix.
5792 pub fn limiter(&self) -> Limiter {
5793 self.settings.limiter
5794 }
5795
5796 /// Sets it, with the ceiling clamped to what [`Limiter`] allows. `false`
5797 /// for a setting already in force. One undo step like every other
5798 /// project-setting pick.
5799 pub fn set_limiter(&mut self, limiter: Limiter) -> bool {
5800 let limiter = limiter.with_ceiling(limiter.ceiling_db);
5801 if self.settings.limiter == limiter {
5802 return false;
5803 }
5804 self.snapshot();
5805 self.settings.limiter = limiter;
5806 true
5807 }
5808
5809 /// What the clip at `idx` of `lane` plays through, or `None` for one that
5810 /// plays flat (and for an index that is not there) -- what a feeder and an
5811 /// export ask before they build an [`crate::eq::EqState`].
5812 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
5813 self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
5814 }
5815
5816 /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
5817 /// take them off. One undo step, like every other edit. `false` -- and no
5818 /// history -- for an index that is not there and for params holding a value
5819 /// that is not finite, which is the one thing the file format could not
5820 /// write and read back.
5821 ///
5822 /// Settings equal to ones already in the table share their entry, so a
5823 /// project that puts the same curve on twenty clips writes it once.
5824 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
5825 if idx >= self.lane(lane).len() {
5826 return false;
5827 }
5828 let slot = match params {
5829 None => None,
5830 Some(params) => {
5831 if !finite(&params) {
5832 return false;
5833 }
5834 Some(match self.eq.iter().position(|p| *p == params) {
5835 Some(at) => at as u16,
5836 // corner-cut: the table is append-only within a session (see
5837 // the module docs) and `Clip::eq` is a u16, so the 65535th
5838 // *distinct* setting of one session is refused rather than
5839 // silently aliased. Upgrade path if a UI ever drags a slider
5840 // that far: widen `Clip::eq` to u32 (Clip has the room) or
5841 // snapshot the table into the history and compact it here.
5842 None if self.eq.len() >= usize::from(u16::MAX) => return false,
5843 None => {
5844 self.eq.push(params);
5845 (self.eq.len() - 1) as u16
5846 }
5847 })
5848 }
5849 };
5850 self.snapshot();
5851 self.lane_mut(lane).expect("checked above")[idx].eq = slot;
5852 true
5853 }
5854
5855 /// The clip's own gain in dB ([`Clip::gain_db`]) at `idx` of `lane`, or
5856 /// `None` for an index that is not there. `0.0` is unity.
5857 pub fn clip_gain(&self, lane: Lane, idx: usize) -> Option<f32> {
5858 self.lane(lane).get(idx).map(|c| c.gain_db)
5859 }
5860
5861 /// Give the clip at `idx` of `lane` this gain in dB, clamped to
5862 /// [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step, like every
5863 /// other edit. `false` -- and no history -- for an index that is not there,
5864 /// a value that is not finite, a video lane (a picture has no volume of its
5865 /// own to set: the gain is on the audio clip the take was split into, not
5866 /// relayed to it), or a value already set exactly so.
5867 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
5868 if lane.kind != LaneKind::Audio || !db.is_finite() {
5869 return false;
5870 }
5871 let Some(current) = self.lane(lane).get(idx).map(|c| c.gain_db) else {
5872 return false;
5873 };
5874 let db = db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
5875 if current == db {
5876 return false;
5877 }
5878 self.snapshot();
5879 self.lane_mut(lane).expect("checked above")[idx].gain_db = db;
5880 true
5881 }
5882
5883 /// The clip's pan ([`Clip::pan`]) at `idx` of `lane`, or `None` for an index that is not there.
5884 pub fn clip_pan(&self, lane: Lane, idx: usize) -> Option<f32> {
5885 self.lane(lane).get(idx).map(Clip::pan_value)
5886 }
5887
5888 /// Give the clip at `idx` of `lane` this pan, clamped to `-1.0..=1.0`. One undo step.
5889 /// `false` -- and no history -- for an index that is not there, a value that is not
5890 /// finite, a non-audio lane, or a value already set.
5891 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
5892 if lane.kind != LaneKind::Audio || !pan.is_finite() {
5893 return false;
5894 }
5895 let Some(current) = self.lane(lane).get(idx).map(|c| c.pan) else {
5896 return false;
5897 };
5898 let pan = (pan.clamp(-1.0, 1.0) * 100.0).round() as i8;
5899 if current == pan {
5900 return false;
5901 }
5902 self.snapshot();
5903 self.lane_mut(lane).expect("checked above")[idx].pan = pan;
5904 true
5905 }
5906
5907 /// Give the clip at `idx` of `lane` this pitch in semitones, clamped to `-12..=12`.
5908 /// One undo step. `false` -- and no history -- for an index that is not there, a
5909 /// non-audio lane, or a value already set.
5910 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
5911 if lane.kind != LaneKind::Audio {
5912 return false;
5913 }
5914 let Some(current) = self.lane(lane).get(idx).map(|c| c.pitch) else {
5915 return false;
5916 };
5917 let semitones = semitones.clamp(i32::from(MIN_CLIP_PITCH), i32::from(MAX_CLIP_PITCH)) as i8;
5918 if current == semitones {
5919 return false;
5920 }
5921 self.snapshot();
5922 self.lane_mut(lane).expect("checked above")[idx].pitch = semitones;
5923 true
5924 }
5925
5926 /// The pitch in semitones of the clip at `idx` of `lane`, or `None` for an index that
5927 /// is not there.
5928 pub fn clip_pitch(&self, lane: Lane, idx: usize) -> Option<i8> {
5929 self.lane(lane).get(idx).map(|c| c.pitch)
5930 }
5931
5932 /// The placement animation of the clip at `idx` of `lane`, sorted by source
5933 /// frame ([`Clip::transform_keys`]). Empty for no keys and for an index
5934 /// that is not there.
5935 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[TransformKey] {
5936 self.lane(lane)
5937 .get(idx)
5938 .map_or(&[][..], |c| c.transform_keys.as_slice())
5939 }
5940
5941 /// Replace the whole placement animation of the clip at `idx` of `lane`; an
5942 /// empty list clears it back to [`Clip::transform`]. Sorted here, one undo
5943 /// step. `false` -- and no history -- for an audio lane, an index that is not
5944 /// there, more than [`MAX_TRANSFORM_KEYS`] keys, a key whose placement is not
5945 /// finite, two keys at one source frame, or a list already exactly so. An
5946 /// opacity is clamped to `0..=1`, as [`TransformParams::opacity`] requires.
5947 pub fn set_transform_keys(
5948 &mut self,
5949 lane: Lane,
5950 idx: usize,
5951 mut keys: Vec<TransformKey>,
5952 ) -> bool {
5953 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
5954 return false;
5955 }
5956 if keys.iter().any(|k| !transform_finite(&k.params)) {
5957 return false;
5958 }
5959 keys.sort_by_key(|k| k.at);
5960 if keys.windows(2).any(|w| w[0].at == w[1].at) {
5961 return false;
5962 }
5963 for k in &mut keys {
5964 k.params.opacity = k.params.opacity.clamp(0.0, 1.0);
5965 }
5966 let Some(current) = self.lane(lane).get(idx).map(|c| &c.transform_keys) else {
5967 return false;
5968 };
5969 if *current == keys {
5970 return false;
5971 }
5972 self.snapshot();
5973 self.lane_mut(lane).expect("checked above")[idx].transform_keys = keys;
5974 true
5975 }
5976
5977 /// The opacity animation of the clip at `idx` of `lane`, sorted by source
5978 /// frame ([`Clip::opacity_keys`]). Empty for no keys and for an index that
5979 /// is not there.
5980 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[OpacityKey] {
5981 self.lane(lane)
5982 .get(idx)
5983 .map_or(&[][..], |c| c.opacity_keys.as_slice())
5984 }
5985
5986 /// Replace the whole opacity animation of the clip at `idx` of `lane`; an
5987 /// empty list clears it. Sorted here, one undo step; opacities are clamped to
5988 /// `0..=1`. `false` -- and no history -- for an audio lane, an index that is
5989 /// not there, more than [`MAX_TRANSFORM_KEYS`] keys, a non-finite opacity, two
5990 /// keys at one source frame, or a list already exactly so.
5991 pub fn set_opacity_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<OpacityKey>) -> bool {
5992 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
5993 return false;
5994 }
5995 if keys.iter().any(|k| !k.opacity.is_finite()) {
5996 return false;
5997 }
5998 keys.sort_by_key(|k| k.at);
5999 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6000 return false;
6001 }
6002 for k in &mut keys {
6003 k.opacity = k.opacity.clamp(0.0, 1.0);
6004 }
6005 let Some(current) = self.lane(lane).get(idx).map(|c| &c.opacity_keys) else {
6006 return false;
6007 };
6008 if *current == keys {
6009 return false;
6010 }
6011 self.snapshot();
6012 self.lane_mut(lane).expect("checked above")[idx].opacity_keys = keys;
6013 true
6014 }
6015
6016 /// The colour animation of the clip at `idx` of `lane`, sorted by source
6017 /// frame ([`Clip::color_keys`]). Empty for no keys and for an index that is
6018 /// not there.
6019 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[ColorKey] {
6020 self.lane(lane)
6021 .get(idx)
6022 .map_or(&[][..], |c| c.color_keys.as_slice())
6023 }
6024
6025 /// The effects stack of the clip at `idx` of `lane` ([`Clip::effects`]).
6026 /// Empty for none and for an index that is not there.
6027 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
6028 self.lane(lane).get(idx).map_or(&[], |c| &c.effects)
6029 }
6030
6031 /// Replaces the effects stack of the clip at `idx` of `lane` (an empty list
6032 /// clears it), each effect's values clamped into range. One undo step; `false`
6033 /// for a lane that is not a video lane, a clip that is not there, more than
6034 /// [`crate::effects::MAX_EFFECTS`] effects, and a stack equal to the current one.
6035 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
6036 if lane.kind != LaneKind::Video || effects.len() > crate::effects::MAX_EFFECTS {
6037 return false;
6038 }
6039 let effects: Vec<_> = effects.into_iter().map(crate::effects::Effect::clamped).collect();
6040 let Some(current) = self.lane(lane).get(idx).map(|c| &c.effects) else {
6041 return false;
6042 };
6043 if *current == effects {
6044 return false;
6045 }
6046 self.snapshot();
6047 self.lane_mut(lane).expect("checked above")[idx].effects = effects;
6048 true
6049 }
6050
6051 /// The keys of the mask at stack position `slot` of the clip at `idx` of `lane`
6052 /// ([`crate::effects::Effect::keys`]); empty for anything else.
6053 pub fn mask_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::MaskKey] {
6054 self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)).map_or(&[], |e| &e.keys)
6055 }
6056
6057 /// Replaces the keys of the mask at stack position `slot` of the clip at `idx` of
6058 /// `lane`; an empty list clears them. Keys are source-frame keyed, sorted here with
6059 /// no two alike, each field clamped into the mask's range. Refused for a clip that is
6060 /// not a picture clip on a video lane, a slot that is not a rect or ellipse mask,
6061 /// more than [`MAX_TRANSFORM_KEYS`] keys, or a list equal to the current one. One undo step.
6062 pub fn set_mask_keys(&mut self, lane: Lane, idx: usize, slot: usize, mut keys: Vec<crate::effects::MaskKey>) -> bool {
6063 use crate::effects::{EffectKind, MaskKey};
6064 if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS {
6065 return false;
6066 }
6067 if keys.iter().any(|k| ![k.x, k.y, k.width, k.height, k.feather].iter().all(|v| v.is_finite())) {
6068 return false;
6069 }
6070 keys.sort_by_key(|k| k.at);
6071 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6072 return false;
6073 }
6074 let r = EffectKind::RectMask.params();
6075 for k in &mut keys {
6076 let c = |v: f32, i: usize| v.clamp(r[i].min, r[i].max);
6077 *k = MaskKey { x: c(k.x, 0), y: c(k.y, 1), width: c(k.width, 2), height: c(k.height, 3), feather: c(k.feather, 4), ..*k };
6078 }
6079 let Some(current) = self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)) else {
6080 return false;
6081 };
6082 if !matches!(current.kind, EffectKind::RectMask | EffectKind::EllipseMask) || current.keys == keys {
6083 return false;
6084 }
6085 self.snapshot();
6086 self.lane_mut(lane).expect("checked above")[idx].effects[slot].keys = keys;
6087 true
6088 }
6089
6090 /// Replace the whole colour animation of the clip at `idx` of `lane`; an
6091 /// empty list clears it. Sorted here, one undo step; each field is clamped to
6092 /// its range (brightness and tint `-1..=1`, contrast and saturation `0..=2`).
6093 /// `false` -- and no history -- for an audio lane, an index that is not there,
6094 /// more than [`MAX_COLOR_KEYS`] keys, a non-finite value, two keys at one
6095 /// source frame, or a list already exactly so.
6096 pub fn set_color_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<ColorKey>) -> bool {
6097 if lane.kind != LaneKind::Video || keys.len() > MAX_COLOR_KEYS {
6098 return false;
6099 }
6100 if keys.iter().any(|k| !color_finite(&k.params)) {
6101 return false;
6102 }
6103 keys.sort_by_key(|k| k.at);
6104 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6105 return false;
6106 }
6107 for k in &mut keys {
6108 let p = &mut k.params;
6109 p.brightness = p.brightness.clamp(-1.0, 1.0);
6110 p.contrast = p.contrast.clamp(0.0, 2.0);
6111 p.saturation = p.saturation.clamp(0.0, 2.0);
6112 p.tint = p.tint.clamp(-1.0, 1.0);
6113 }
6114 let Some(current) = self.lane(lane).get(idx).map(|c| &c.color_keys) else {
6115 return false;
6116 };
6117 if *current == keys {
6118 return false;
6119 }
6120 self.snapshot();
6121 self.lane_mut(lane).expect("checked above")[idx].color_keys = keys;
6122 true
6123 }
6124
6125 /// The source frame the keys of the clip at `idx` of `lane` are read at for
6126 /// timeline `frame`, rounded to the nearest whole frame: where a key set "at
6127 /// the playhead" lands. `None` for an index that is not there, a frame
6128 /// outside the clip and a lane that is not a video lane.
6129 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
6130 let c = self.lane(lane).get(idx)?;
6131 if lane.kind != LaneKind::Video || timeline_frame < c.start || timeline_frame >= c.end() {
6132 return None;
6133 }
6134 Some(key_pos(c, timeline_frame).round() as u32)
6135 }
6136
6137 /// Whether the clip has any key of `kind` at all.
6138 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: KeyKind) -> bool {
6139 self.lane(lane).get(idx).is_some_and(|c| match kind {
6140 KeyKind::Placement => !c.transform_keys.is_empty(),
6141 KeyKind::Opacity => !c.opacity_keys.is_empty(),
6142 KeyKind::Color => !c.color_keys.is_empty(),
6143 })
6144 }
6145
6146 /// The ease of the key of `kind` that sits exactly on timeline `frame`
6147 /// ([`key_source_frame`](Self::key_source_frame)), `None` with no key there.
6148 pub fn key_ease_at(&self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<KeyEase> {
6149 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6150 let c = self.lane(lane).get(idx)?;
6151 match kind {
6152 KeyKind::Placement => c.transform_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6153 KeyKind::Opacity => c.opacity_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6154 KeyKind::Color => c.color_keys.iter().find(|k| k.at == at).map(|k| k.ease),
6155 }
6156 }
6157
6158 /// The stopwatch: puts a key of `kind` on timeline `frame` holding the value the
6159 /// clip shows there (so the picture does not change), or takes the key that is
6160 /// there off. `Some(true)` for a key added, `Some(false)` for one removed, `None`
6161 /// -- and no history -- where no key can go (see
6162 /// [`key_source_frame`](Self::key_source_frame)) or the keys are full. One undo
6163 /// step. Removing the last key puts the clip back on its single value.
6164 pub fn toggle_key(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32) -> Option<bool> {
6165 let at = self.key_source_frame(lane, idx, timeline_frame)?;
6166 let had = self.key_ease_at(lane, idx, kind, timeline_frame).is_some();
6167 let c = self.lane(lane).get(idx)?.clone();
6168 let ok = match kind {
6169 KeyKind::Placement => {
6170 let mut keys = c.transform_keys.clone();
6171 if had {
6172 keys.retain(|k| k.at != at);
6173 } else {
6174 let params = self.transform_at(lane, idx, timeline_frame).unwrap_or_default();
6175 keys.push(TransformKey { at, params, ease: KeyEase::Linear });
6176 }
6177 self.set_transform_keys(lane, idx, keys)
6178 }
6179 KeyKind::Opacity => {
6180 let mut keys = c.opacity_keys.clone();
6181 if had {
6182 keys.retain(|k| k.at != at);
6183 } else {
6184 let opacity = self.opacity_at(lane, idx, timeline_frame);
6185 keys.push(OpacityKey { at, opacity, ease: KeyEase::Linear });
6186 }
6187 self.set_opacity_keys(lane, idx, keys)
6188 }
6189 KeyKind::Color => {
6190 let mut keys = c.color_keys.clone();
6191 if had {
6192 keys.retain(|k| k.at != at);
6193 } else {
6194 let params = self.color_at(lane, idx, timeline_frame).unwrap_or_default();
6195 keys.push(ColorKey { at, params, ease: KeyEase::Linear });
6196 }
6197 self.set_color_keys(lane, idx, keys)
6198 }
6199 };
6200 ok.then_some(!had)
6201 }
6202
6203 /// Sets the ease of the key of `kind` on timeline `frame`. `false` -- and no
6204 /// history -- with no key there or one already so. One undo step.
6205 pub fn set_key_ease_at(&mut self, lane: Lane, idx: usize, kind: KeyKind, timeline_frame: u32, ease: KeyEase) -> bool {
6206 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6207 return false;
6208 };
6209 if self.key_ease_at(lane, idx, kind, timeline_frame).is_none_or(|e| e == ease) {
6210 return false;
6211 }
6212 let Some(c) = self.lane(lane).get(idx) else {
6213 return false;
6214 };
6215 match kind {
6216 KeyKind::Placement => {
6217 let mut keys = c.transform_keys.clone();
6218 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6219 self.set_transform_keys(lane, idx, keys)
6220 }
6221 KeyKind::Opacity => {
6222 let mut keys = c.opacity_keys.clone();
6223 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6224 self.set_opacity_keys(lane, idx, keys)
6225 }
6226 KeyKind::Color => {
6227 let mut keys = c.color_keys.clone();
6228 keys.iter_mut().filter(|k| k.at == at).for_each(|k| k.ease = ease);
6229 self.set_color_keys(lane, idx, keys)
6230 }
6231 }
6232 }
6233
6234 /// Writes `keys` as the clip's keys of one kind with the undo step only when
6235 /// `snapshot`: the shape of a drag, whose first sample is a step and the
6236 /// rest are not. The lists were validated by the caller.
6237 fn put_key<K: Keyed>(
6238 &mut self,
6239 lane: Lane,
6240 idx: usize,
6241 snapshot: bool,
6242 key: K,
6243 slot: impl Fn(&mut Clip) -> &mut Vec<K>,
6244 ) -> bool {
6245 if lane.kind != LaneKind::Video {
6246 return false;
6247 }
6248 let Some(clip) = self.lane_mut(lane).and_then(|c| c.get_mut(idx)) else {
6249 return false;
6250 };
6251 let mut keys = slot(clip).clone();
6252 match keys.iter_mut().find(|k| k.at() == key.at()) {
6253 Some(k) => *k = key.placed(key.at(), k.ease()),
6254 None => {
6255 keys.push(key);
6256 keys.sort_by_key(|k| k.at());
6257 }
6258 }
6259 if keys.len() > MAX_TRANSFORM_KEYS {
6260 return false;
6261 }
6262 if snapshot {
6263 self.snapshot();
6264 }
6265 *slot(&mut self.lane_mut(lane).expect("checked")[idx]) = keys;
6266 true
6267 }
6268
6269 /// Sets the placement at timeline `frame` as a key there: a new key, or the
6270 /// existing key's value with its ease kept. The write a slider makes on a clip
6271 /// whose placement is keyed. `snapshot` is the undo step
6272 /// ([`set_transform_live`](Self::set_transform_live)'s rule). `false` where no
6273 /// key can go ([`key_source_frame`](Self::key_source_frame)) or a value is not finite.
6274 pub fn put_transform_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: TransformParams, snapshot: bool) -> bool {
6275 self.flat.clear();
6276 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6277 return false;
6278 };
6279 if !transform_finite(&params) {
6280 return false;
6281 }
6282 let params = TransformParams { opacity: params.opacity.clamp(0.0, 1.0), ..params };
6283 self.put_key(lane, idx, snapshot, TransformKey { at, params, ease: KeyEase::Linear }, |c| &mut c.transform_keys)
6284 }
6285
6286 /// [`put_transform_key_at`](Self::put_transform_key_at) for the opacity.
6287 pub fn put_opacity_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, opacity: f32, snapshot: bool) -> bool {
6288 self.flat.clear();
6289 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6290 return false;
6291 };
6292 if !opacity.is_finite() {
6293 return false;
6294 }
6295 let opacity = opacity.clamp(0.0, 1.0);
6296 self.put_key(lane, idx, snapshot, OpacityKey { at, opacity, ease: KeyEase::Linear }, |c| &mut c.opacity_keys)
6297 }
6298
6299 /// [`put_transform_key_at`](Self::put_transform_key_at) for the grade.
6300 pub fn put_color_key_at(&mut self, lane: Lane, idx: usize, timeline_frame: u32, params: ColorParams, snapshot: bool) -> bool {
6301 self.flat.clear();
6302 let Some(at) = self.key_source_frame(lane, idx, timeline_frame) else {
6303 return false;
6304 };
6305 if !color_finite(&params) {
6306 return false;
6307 }
6308 let params = ColorParams {
6309 brightness: params.brightness.clamp(-1.0, 1.0),
6310 contrast: params.contrast.clamp(0.0, 2.0),
6311 saturation: params.saturation.clamp(0.0, 2.0),
6312 tint: params.tint.clamp(-1.0, 1.0),
6313 // Keys animate the sliders; the look is the clip's base grade's.
6314 look: crate::color::Look::default(),
6315 };
6316 self.put_key(lane, idx, snapshot, ColorKey { at, params, ease: KeyEase::Linear }, |c| &mut c.color_keys)
6317 }
6318
6319 /// The grade the clip at `idx` of `lane` shows at timeline `frame`: its
6320 /// colour keys evaluated at the source frame that frame plays, or its single
6321 /// grade when it has none. `None` for an index that is not there or a clip
6322 /// with no grade at all and no keys.
6323 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
6324 let c = self.lane(lane).get(idx)?;
6325 if c.color_keys.is_empty() {
6326 return self.color_of(lane, idx).copied();
6327 }
6328 Some(clip_color_at(c, self.color_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6329 }
6330
6331 /// The opacity the clip at `idx` of `lane` shows at timeline `frame`, the
6332 /// fades not counted: its opacity keys evaluated at the source frame that
6333 /// frame plays, else its placement's (keyed or not). `1.0` for an index
6334 /// that is not there.
6335 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
6336 let Some(c) = self.lane(lane).get(idx) else {
6337 return 1.0;
6338 };
6339 let base = self
6340 .transform_at(lane, idx, timeline_frame)
6341 .map_or(1.0, |t| t.opacity);
6342 clip_opacity_at(c, base, timeline_frame)
6343 }
6344
6345 /// The placement the clip at `idx` of `lane` shows at timeline `frame`: its
6346 /// keys evaluated at the source frame that frame plays
6347 /// ([`keyed_transform`]), or its single [`Clip::transform`] when it has no
6348 /// keys. `None` for an index that is not there or a clip with no
6349 /// transform at all, which is the identity.
6350 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
6351 let c = self.lane(lane).get(idx)?;
6352 if c.transform_keys.is_empty() {
6353 return self.transform_of(lane, idx).copied();
6354 }
6355 Some(clip_transform_at(c, self.transform_of(lane, idx).copied().unwrap_or_default(), timeline_frame))
6356 }
6357
6358 /// The volume envelope of the clip at `idx` of `lane`, sorted by source
6359 /// frame ([`Clip::gain_keys`]). Empty for a clip with no points, and for an
6360 /// index that is not there.
6361 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
6362 self.lane(lane)
6363 .get(idx)
6364 .map_or(&[][..], |c| c.gain_keys.as_slice())
6365 }
6366
6367 /// Replace the whole volume envelope of the clip at `idx` of `lane`; an
6368 /// empty list clears it. The points are sorted here, and each dB is clamped
6369 /// to [`MIN_CLIP_GAIN_DB`]..=[`MAX_CLIP_GAIN_DB`]. One undo step.
6370 ///
6371 /// `false` -- and no history -- for a video lane, an index that is not
6372 /// there, more than [`MAX_GAIN_KEYS`] points, a point that is not finite,
6373 /// two points at one source frame, or an envelope already exactly so.
6374 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, mut keys: Vec<GainKey>) -> bool {
6375 if lane.kind != LaneKind::Audio || keys.len() > MAX_GAIN_KEYS {
6376 return false;
6377 }
6378 if keys.iter().any(|k| !k.db.is_finite()) {
6379 return false;
6380 }
6381 keys.sort_by_key(|k| k.at);
6382 if keys.windows(2).any(|w| w[0].at == w[1].at) {
6383 return false;
6384 }
6385 for k in &mut keys {
6386 k.db = k.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB);
6387 }
6388 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6389 return false;
6390 };
6391 if *current == keys {
6392 return false;
6393 }
6394 self.snapshot();
6395 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6396 true
6397 }
6398
6399 /// Put one point into the volume envelope of the clip at `idx` of `lane`:
6400 /// it replaces the point already at `key.at`, or is added in source order.
6401 /// The dB is clamped as [`set_gain_keys`](Self::set_gain_keys) clamps it.
6402 /// One undo step.
6403 ///
6404 /// `false` -- and no history -- for a video lane, an index that is not
6405 /// there, a dB that is not finite, a new point past
6406 /// [`MAX_GAIN_KEYS`], or a point already exactly as it is.
6407 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
6408 if lane.kind != LaneKind::Audio || !key.db.is_finite() {
6409 return false;
6410 }
6411 let key = GainKey {
6412 db: key.db.clamp(MIN_CLIP_GAIN_DB, MAX_CLIP_GAIN_DB),
6413 ..key
6414 };
6415 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6416 return false;
6417 };
6418 let mut keys = current.clone();
6419 match keys.binary_search_by_key(&key.at, |k| k.at) {
6420 Ok(at) => {
6421 if keys[at] == key {
6422 return false;
6423 }
6424 keys[at] = key;
6425 }
6426 Err(at) => {
6427 if keys.len() >= MAX_GAIN_KEYS {
6428 return false;
6429 }
6430 keys.insert(at, key);
6431 }
6432 }
6433 self.snapshot();
6434 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6435 true
6436 }
6437
6438 /// Take the point at source frame `at` out of the volume envelope of the
6439 /// clip at `idx` of `lane`. One undo step.
6440 ///
6441 /// `false` -- and no history -- for a video lane, an index that is not
6442 /// there, or no point at `at`.
6443 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
6444 if lane.kind != LaneKind::Audio {
6445 return false;
6446 }
6447 let Some(current) = self.lane(lane).get(idx).map(|c| &c.gain_keys) else {
6448 return false;
6449 };
6450 let Ok(pos) = current.binary_search_by_key(&at, |k| k.at) else {
6451 return false;
6452 };
6453 let mut keys = current.clone();
6454 keys.remove(pos);
6455 self.snapshot();
6456 self.lane_mut(lane).expect("checked above")[idx].gain_keys = keys;
6457 true
6458 }
6459
6460 /// The envelope's effective dB at timeline frame `timeline_frame` of the
6461 /// clip at `idx` of `lane`: its [`Clip::gain_db`] plus its keyed envelope
6462 /// at the source frame that timeline frame plays. The fades are not in it.
6463 /// `None` for a video lane or an index that is not there. Timeline frames
6464 /// before the clip read as its first frame.
6465 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
6466 if lane.kind != LaneKind::Audio {
6467 return None;
6468 }
6469 let c = self.lane(lane).get(idx)?;
6470 Some(c.gain_db + gain_keys_db_at(&c.gain_keys, key_pos(c, timeline_frame)))
6471 }
6472
6473 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
6474 /// ungraded (and for an index that is not there) -- what the renderer and
6475 /// the export ask before they call [`crate::color::apply_yuv`].
6476 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
6477 self.color
6478 .get(usize::from(self.lane(lane).get(idx)?.color?))
6479 }
6480
6481 /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
6482 /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
6483 /// (and no history) for an index that is not there or a value that is not
6484 /// finite, and equal settings share a table entry.
6485 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6486 self.write_color(lane, idx, params, true)
6487 }
6488
6489 /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
6490 /// one pointer drag, whose first write (a plain `set_color`) already took the
6491 /// snapshot the gesture rolls back to. A drag across a slider is one undo,
6492 /// not one per pixel -- and undoing it lands where the hand picked it up.
6493 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
6494 self.flat.clear();
6495 self.write_color(lane, idx, params, false)
6496 }
6497
6498 fn write_color(
6499 &mut self,
6500 lane: Lane,
6501 idx: usize,
6502 params: Option<ColorParams>,
6503 snapshot: bool,
6504 ) -> bool {
6505 if idx >= self.lane(lane).len() {
6506 return false;
6507 }
6508 let slot = match params {
6509 None => None,
6510 Some(params) => {
6511 if !color_finite(&params) {
6512 return false;
6513 }
6514 Some(match self.color.iter().position(|p| *p == params) {
6515 Some(at) => at as u16,
6516 // corner-cut: the 65535th *distinct* grade of one session is
6517 // refused rather than silently aliased, exactly as `set_eq`
6518 // refuses the 65535th curve; same upgrade path.
6519 None if self.color.len() >= usize::from(u16::MAX) => return false,
6520 None => {
6521 self.color.push(params);
6522 (self.color.len() - 1) as u16
6523 }
6524 })
6525 }
6526 };
6527 if snapshot {
6528 self.snapshot();
6529 }
6530 self.lane_mut(lane).expect("checked above")[idx].color = slot;
6531 true
6532 }
6533
6534 /// Every `.cube` file a clip's grade names, each once, in table order.
6535 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
6536 let used: std::collections::HashSet<u16> =
6537 self.lanes.iter().flat_map(|l| l.clips.iter().filter_map(|c| c.color)).collect();
6538 let mut out = Vec::new();
6539 for (i, p) in self.color.iter().enumerate() {
6540 if let Some(r) = p.look.lut
6541 && used.contains(&(i as u16))
6542 && !out.contains(&r)
6543 {
6544 out.push(r);
6545 }
6546 }
6547 out
6548 }
6549
6550 /// The `.cube` files clips name that cannot be used, and why -- a missing
6551 /// file or a malformed one. Such a clip plays and exports without its LUT
6552 /// (the rest of its grade still applies); this is the warning that says so.
6553 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
6554 self.luts().into_iter().filter_map(|r| r.problem().map(|e| (r.path(), e))).collect()
6555 }
6556
6557 /// Points every clip whose grade names the `.cube` file at `from` to `to`
6558 /// instead (re-reading `to` even if it is the same path, so an edited file is
6559 /// picked up). One undo step; the number of clips changed, 0 (and no history)
6560 /// when none names `from`. The colour table only grows, as every grade edit
6561 /// leaves it: the clips are re-pointed, which is what undo restores.
6562 pub fn relink_lut(&mut self, from: &Path, to: &Path) -> usize {
6563 let named = |p: &ColorParams| p.look.lut.is_some_and(|r| r.path() == from);
6564 let hits: Vec<(usize, usize)> = self
6565 .lanes
6566 .iter()
6567 .enumerate()
6568 .flat_map(|(l, lane)| {
6569 lane.clips.iter().enumerate().filter_map(move |(i, c)| c.color.map(|slot| (l, i, slot)))
6570 })
6571 .filter(|&(_, _, slot)| self.color.get(usize::from(slot)).is_some_and(named))
6572 .map(|(l, i, _)| (l, i))
6573 .collect();
6574 if hits.is_empty() {
6575 return 0;
6576 }
6577 let fresh = crate::cube::LutRef::reload(to);
6578 self.snapshot();
6579 for &(l, i) in &hits {
6580 let slot = usize::from(self.lanes[l].clips[i].color.expect("graded"));
6581 let mut params = self.color[slot];
6582 params.look.lut = Some(fresh);
6583 let at = match self.color.iter().position(|p| *p == params) {
6584 Some(at) => at,
6585 None => {
6586 self.color.push(params);
6587 self.color.len() - 1
6588 }
6589 };
6590 self.lanes[l].clips[i].color = Some(at as u16);
6591 }
6592 hits.len()
6593 }
6594
6595 /// How the clip at `idx` of `lane` is placed, or `None` for one at its fit
6596 /// policy's own placement (and for an index that is not there) -- what the
6597 /// renderer and the export ask before they place its picture.
6598 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
6599 self.transform
6600 .get(usize::from(self.lane(lane).get(idx)?.transform?))
6601 }
6602
6603 /// [`set_color`](Self::set_color)'s twin for [`Clip::transform`]: one undo
6604 /// step, `false` (and no history) for an index that is not there or a
6605 /// value that is not finite, and equal settings share a table entry.
6606 pub fn set_transform(
6607 &mut self,
6608 lane: Lane,
6609 idx: usize,
6610 params: Option<TransformParams>,
6611 ) -> bool {
6612 self.write_transform(lane, idx, params, true)
6613 }
6614
6615 /// [`set_transform`](Self::set_transform) without the undo step, for
6616 /// [`set_color_live`](Self::set_color_live)'s reason: the samples inside
6617 /// one drag on a position/scale/rotate/crop control are one undo, not one
6618 /// per pixel.
6619 pub fn set_transform_live(
6620 &mut self,
6621 lane: Lane,
6622 idx: usize,
6623 params: Option<TransformParams>,
6624 ) -> bool {
6625 self.flat.clear();
6626 self.write_transform(lane, idx, params, false)
6627 }
6628
6629 fn write_transform(
6630 &mut self,
6631 lane: Lane,
6632 idx: usize,
6633 params: Option<TransformParams>,
6634 snapshot: bool,
6635 ) -> bool {
6636 if idx >= self.lane(lane).len() {
6637 return false;
6638 }
6639 let slot = match params {
6640 None => None,
6641 Some(params) => {
6642 if !transform_finite(&params) {
6643 return false;
6644 }
6645 Some(match self.transform.iter().position(|p| *p == params) {
6646 Some(at) => at as u16,
6647 // corner-cut: the 65535th *distinct* transform of one
6648 // session is refused rather than silently aliased,
6649 // exactly as `write_color` refuses the 65535th grade;
6650 // same upgrade path.
6651 None if self.transform.len() >= usize::from(u16::MAX) => return false,
6652 None => {
6653 self.transform.push(params);
6654 (self.transform.len() - 1) as u16
6655 }
6656 })
6657 }
6658 };
6659 if snapshot {
6660 self.snapshot();
6661 }
6662 self.lane_mut(lane).expect("checked above")[idx].transform = slot;
6663 true
6664 }
6665
6666 /// How fast the clip at `idx` of `lane` plays. [`Speed::NORMAL`] for an
6667 /// index that is not there, which is what every clip starts at anyway.
6668 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
6669 self.lane(lane).get(idx).map_or(Speed::NORMAL, |c| c.speed)
6670 }
6671
6672 /// Sets it, for the clip **and its whole group**: a link is one span on
6673 /// however many lanes ([`links_are_consistent`]), so a picture sped up away
6674 /// from its sound would be a group no save could load. One snapshot, so the
6675 /// group's change is one [`Project::undo`].
6676 ///
6677 /// The source range is untouched -- a speed says how many timeline frames
6678 /// that range is spread over ([`Clip::frames`]), which is why a trim and a
6679 /// split still address the file afterwards.
6680 ///
6681 /// Refused, changing nothing and costing no undo step, when the clip would
6682 /// grow into the one after it on its own lane: slowing a clip down makes it
6683 /// wider, and a lane may not overlap itself. The refusal *names* the clip in
6684 /// the way -- by lane and timeline frame -- because "it did not fit" is not
6685 /// something a user can go and fix. Also for an index that is not there.
6686 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6687 self.write_speed(lane, idx, speed, true)
6688 }
6689
6690 /// [`set_speed`](Self::set_speed) without the undo step: the samples *inside*
6691 /// one pointer drag, whose first write (a plain `set_speed`) already took the
6692 /// snapshot the gesture rolls back to. A drag across the bar is one undo,
6693 /// not one per rate it passed through -- exactly as
6694 /// [`set_color_live`](Self::set_color_live) is for a slider.
6695 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
6696 self.write_speed(lane, idx, speed, false)
6697 }
6698
6699 /// Gives the clip at `idx` of `lane` (and the clips linked to it) a speed ramp
6700 /// `keys` ([`Clip::speed_keys`]); empty keys clear it, and the clip takes its
6701 /// constant [`Clip::speed`] again. Its source range stays, so its footprint is
6702 /// recomputed from the ramp. Nothing ripples: as a constant rate change, the new
6703 /// length must still fit before the next clip on its lane, or the edit is
6704 /// refused, and the caller is told how far it would have run.
6705 pub fn set_speed_ramp(&mut self, lane: Lane, idx: usize, keys: &[SpeedKey]) -> crate::Result<()> {
6706 if !keys.is_empty() && !valid_speed_keys(keys) {
6707 return Err("a speed ramp takes 1 to 8 keys, in strictly increasing frames".into());
6708 }
6709 let Some(members) = self.group_of(lane, idx) else {
6710 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6711 };
6712 if !members.subs.is_empty() {
6713 return Err("this clip is linked to captions, which a speed ramp cannot retime yet".into());
6714 }
6715 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6716 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6717 }
6718 let labels = handles(&self.lanes);
6719 for &(l, i) in &members.clips {
6720 let clips = &self.lanes[l].clips;
6721 let moved = Clip { speed_keys: keys.to_vec(), ..clips[i].clone() };
6722 if let Some(next) = clips.get(i + 1)
6723 && moved.end() > next.start
6724 {
6725 return Err(format!(
6726 "with that ramp the clip would run to frame {} and the next {} clip starts at {}: \
6727 move it along, or trim this one first",
6728 moved.end(),
6729 labels[l].label(),
6730 next.start
6731 )
6732 .into());
6733 }
6734 }
6735 self.snapshot();
6736 for (l, i) in members.clips {
6737 self.lanes[l].clips[i].speed_keys = keys.to_vec();
6738 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6739 }
6740 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6741 Ok(())
6742 }
6743
6744 fn write_speed(
6745 &mut self,
6746 lane: Lane,
6747 idx: usize,
6748 speed: Speed,
6749 snapshot: bool,
6750 ) -> crate::Result<()> {
6751 let Some(members) = self.group_of(lane, idx) else {
6752 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6753 };
6754 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6755 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6756 }
6757 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
6758 return Err("this clip has a speed ramp: clear the ramp before setting a constant speed".into());
6759 }
6760 let labels = handles(&self.lanes);
6761 // The clip the hand is holding is the group's clock: everything else
6762 // in the group, caption members included, re-times by the ratio its new
6763 // rate gives its own frames. The clips take the rate itself; a caption
6764 // has none, so it takes the *ratio* -- its span on the timeline
6765 // compresses or stretches about the held clip's head, while the words
6766 // it reads keep their own timing ([`write_sub_edge`]'s law: the
6767 // timeline moves, the track does not).
6768 let Some(held) = self.lane(lane).get(idx).cloned() else {
6769 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6770 };
6771 // The same per-member piece `speeded_playhead` builds for this op,
6772 // asked here instead of read there -- a caption's length comes from
6773 // the map's own ends (`end - start`), never `round(len * ratio)`
6774 // separately, which is what let the two answers drift apart by a
6775 // frame.
6776 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
6777 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
6778 let retimed = |s: SubClip| {
6779 let map = TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end())));
6780 let start = map.apply(s.start);
6781 let end = map.apply(s.end()).max(start.saturating_add(1));
6782 SubClip {
6783 start,
6784 frames: end - start,
6785 ..s
6786 }
6787 };
6788 for &(l, i) in &members.clips {
6789 let clips = &self.lanes[l].clips;
6790 let mut moved = clips[i].clone();
6791 moved.speed = speed;
6792 if let Some(next) = clips.get(i + 1)
6793 && moved.end() > next.start
6794 {
6795 let name = labels[l].label();
6796 return Err(format!(
6797 "at {speed} that clip would run to frame {} and the next {name} clip starts at {}: \
6798 move it along, or trim this one first",
6799 moved.end(),
6800 next.start
6801 )
6802 .into());
6803 }
6804 }
6805 // ...and the captions, against their own lanes' captions: a stretch
6806 // that runs one into its neighbour is refused for the clip arm's
6807 // reason -- a lane may not overlap itself -- and by name like it.
6808 let subs: Vec<(usize, usize, SubClip)> = members
6809 .subs
6810 .iter()
6811 .map(|&(l, i)| (l, i, retimed(self.lanes[l].subs[i])))
6812 .collect();
6813 for &(l, i, moved) in &subs {
6814 for (j, other) in self.lanes[l].subs.iter().enumerate() {
6815 if j != i && moved.start < other.end() && other.start < moved.end() {
6816 return Err(format!(
6817 "at {speed} the {} caption at frame {} would run to frame {} and the next \
6818 starts at {}: move it along, or trim this one first",
6819 labels[l].label(),
6820 self.lanes[l].subs[i].start,
6821 moved.end(),
6822 other.start
6823 )
6824 .into());
6825 }
6826 }
6827 }
6828 if snapshot {
6829 self.snapshot();
6830 }
6831 for (l, i) in members.clips {
6832 self.lanes[l].clips[i].speed = speed;
6833 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
6834 }
6835 for (l, i, moved) in subs {
6836 self.lanes[l].subs[i] = moved;
6837 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
6838 }
6839 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6840 Ok(())
6841 }
6842
6843 /// Whether the clip at `idx` of `lane` plays backwards ([`Clip::reversed`]);
6844 /// `false` for an index that is not there.
6845 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
6846 self.lane(lane).get(idx).is_some_and(|c| c.reversed)
6847 }
6848
6849 /// Plays the clip at `idx` of `lane` backwards (`on`) or forwards again, for the
6850 /// clip **and its whole group**, as [`set_speed`](Self::set_speed) does: a picture
6851 /// run backwards against its sound would be a take nobody recorded. One snapshot,
6852 /// so the group's change is one [`Project::undo`]. Nothing moves: a clip's
6853 /// footprint and window are the same either way, which is why this can never be
6854 /// refused for room.
6855 ///
6856 /// The keys read from the footage -- placement and volume points are source-keyed
6857 /// -- are mirrored across the window as the direction flips, so every animation
6858 /// still plays on the same timeline frames it did, and only the footage under it
6859 /// runs the other way. Flipping twice puts every key back on the frame it was on.
6860 ///
6861 /// Refused, changing nothing, for a still (it has no direction), and for an index
6862 /// that is not there. A group already in the asked state is `Ok` and costs no undo
6863 /// step.
6864 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
6865 let Some(members) = self.group_of(lane, idx) else {
6866 return Err(format!("there is no clip {idx} on {}", lane.label()).into());
6867 };
6868 if members.clips.iter().any(|&(l, i)| self.is_still(&self.lanes[l].clips[i])) {
6869 return Err("a still picture has no direction to reverse".into());
6870 }
6871 if members.clips.iter().any(|&(l, i)| is_sequence_source(self.lanes[l].clips[i].source)) {
6872 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
6873 }
6874 if members.clips.iter().all(|&(l, i)| self.lanes[l].clips[i].reversed == on) {
6875 return Ok(());
6876 }
6877 self.snapshot();
6878 for (l, i) in members.clips {
6879 let c = &mut self.lanes[l].clips[i];
6880 if c.reversed != on {
6881 c.reversed = on;
6882 mirror_keys(c);
6883 }
6884 }
6885 debug_assert!(links_are_consistent(&self.lanes).is_ok());
6886 Ok(())
6887 }
6888
6889 /// Where a re-rate of the clip at `idx` of `lane` to `speed` puts a
6890 /// playhead standing at `at` -- read off the geometry **before** the
6891 /// write, because the old ends are gone after it. The question a card
6892 /// asks as its bar moves: the picture under the cursor has to stay the
6893 /// picture under the cursor, or the scene changes with the rate.
6894 ///
6895 /// The answer is piecewise, exactly as [`write_speed`] re-times, and it
6896 /// is asked of the same [`TimelineMap`] the write itself is a shape of:
6897 /// a clip member keeps its own start and re-fits its length at the new
6898 /// rate -- its **old** rate against the new one, which is what the bar's
6899 /// live samples ask about as much as a first press does; a caption
6900 /// member scales about the held clip's start by the held clip's own
6901 /// proportion; and a playhead outside every member's old extent stays
6902 /// exactly where it was -- nothing ripples, so the gap a shrink leaves
6903 /// (or the room a stretch takes) absorbs the difference, not the
6904 /// playhead. `None` for an index that is not there.
6905 pub fn speeded_playhead(&self, lane: Lane, idx: usize, speed: Speed, at: u32) -> Option<u32> {
6906 // A ramped clip has no single rate to re-fit against: no answer, not a wrong one.
6907 if self.lane(lane).get(idx).is_some_and(|c| !c.speed_keys.is_empty()) {
6908 return None;
6909 }
6910 let members = self.group_of(lane, idx)?;
6911 let held = self.lane(lane).get(idx).cloned()?;
6912 let (held_old, new) = (held.speed.as_f64(), speed.as_f64());
6913 for &(l, i) in members.clips.iter().chain(&members.subs) {
6914 let (span, map) = match self.lanes[l]
6915 .clips
6916 .get(i)
6917 .filter(|_| members.clips.contains(&(l, i)))
6918 {
6919 // The clip's own span, re-fitted at its own old rate: one
6920 // piece of the map, anchored where the clip itself is. The
6921 // new length is the same *source* frames at the new rate --
6922 // len divided by it, never multiplied.
6923 Some(c) => (
6924 (c.start, c.start + c.frames()),
6925 TimelineMap::piece(
6926 (c.start, c.start + c.frames()),
6927 (c.start, c.start + (c.len() as f64 / new).round() as u32),
6928 ),
6929 ),
6930 // The caption's span, scaled about the held clip's head by
6931 // the held clip's proportion -- the offset the group keeps.
6932 None => {
6933 let s = self.lanes[l].subs.get(i)?;
6934 let scale = |f: u32| scaled_caption_frame(held.start, held_old, new, f);
6935 (
6936 (s.start, s.end()),
6937 TimelineMap::piece((s.start, s.end()), (scale(s.start), scale(s.end()))),
6938 )
6939 }
6940 };
6941 // The piece owns only its own old span: outside it the playhead
6942 // is another member's question, or nobody's.
6943 if (span.0..span.1).contains(&at) {
6944 return Some(map.apply(at));
6945 }
6946 }
6947 Some(at)
6948 }
6949
6950 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
6951 /// [`FitPolicy::Fit`] for an index that is not there, which is the default
6952 /// every clip starts at anyway.
6953 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
6954 self.lane(lane)
6955 .get(idx)
6956 .map_or(FitPolicy::default(), |c| c.fit)
6957 }
6958
6959 /// Sets it. One undo step like every other edit, and `false` (with no
6960 /// history) for an index that is not there. Unlike an eq or a grade there is
6961 /// no "off": every clip has a policy, and `Fit` is what "off" would mean.
6962 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
6963 if idx >= self.lane(lane).len() {
6964 return false;
6965 }
6966 self.snapshot();
6967 self.lane_mut(lane).expect("checked above")[idx].fit = fit;
6968 true
6969 }
6970
6971 /// Turns the stabilisation of the clip at `idx` of a video `lane` on (with its
6972 /// settings) or off (`None`). One undo step; `false` (no history) for an index
6973 /// that is not there, a lane that is not video, or no change.
6974 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
6975 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.stabilise == st) {
6976 return false;
6977 }
6978 self.snapshot();
6979 self.lane_mut(lane).expect("checked above")[idx].stabilise = st;
6980 true
6981 }
6982
6983 /// Sets how a video clip's interlaced source is deinterlaced
6984 /// ([`Clip::deinterlace`]). One undo step; `false`, and no history, for a
6985 /// lane that is not video, a clip that is not there, or no change.
6986 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: Deinterlace) -> bool {
6987 if lane.kind != LaneKind::Video || self.lane(lane).get(idx).is_none_or(|c| c.deinterlace == mode) {
6988 return false;
6989 }
6990 self.snapshot();
6991 self.lane_mut(lane).expect("checked above")[idx].deinterlace = mode;
6992 true
6993 }
6994
6995 /// Points the clip at `idx` of a video `lane` at another source -- how a generator's
6996 /// parameter is edited (a new spelling is a new source). The window is kept. One undo step;
6997 /// `false` and no history for a clip that is not there, a source that is not, or no change.
6998 pub fn set_clip_source(&mut self, lane: Lane, idx: usize, source: usize) -> bool {
6999 if lane.kind != LaneKind::Video || source >= self.sources.len() || self.lane(lane).get(idx).is_none_or(|c| c.source == source) {
7000 return false;
7001 }
7002 self.snapshot();
7003 self.lane_mut(lane).expect("checked above")[idx].source = source;
7004 true
7005 }
7006
7007 /// Sets the colour label of the clip at `idx` of `lane` (0 for none). One undo step; `false`
7008 /// and no history for a clip that is not there, a label outside the palette, or no change.
7009 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
7010 if label > LABEL_COUNT || self.lane(lane).get(idx).is_none_or(|c| c.mark.label == label) {
7011 return false;
7012 }
7013 self.snapshot();
7014 self.lane_mut(lane).expect("checked above")[idx].mark.label = label;
7015 true
7016 }
7017
7018 /// Switches the clip at `idx` of `lane` on or off ([`ClipMark::off`]). One undo step; `false`
7019 /// and no history for a clip that is not there or no change.
7020 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
7021 if self.lane(lane).get(idx).is_none_or(|c| c.mark.off != enabled) {
7022 return false;
7023 }
7024 self.snapshot();
7025 self.lane_mut(lane).expect("checked above")[idx].mark.off = !enabled;
7026 true
7027 }
7028
7029 /// The clip's mark, the default for no clip.
7030 pub fn mark_of(&self, lane: Lane, idx: usize) -> ClipMark {
7031 self.lane(lane).get(idx).map_or_else(ClipMark::default, |c| c.mark)
7032 }
7033
7034 /// The clip's deinterlace setting, `Frame` for no clip.
7035 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> Deinterlace {
7036 self.lane(lane).get(idx).map_or_else(Deinterlace::default, |c| c.deinterlace)
7037 }
7038
7039 /// The clip's stabilisation ([`Clip::stabilise`]), `None` for off or no clip.
7040 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
7041 self.lane(lane).get(idx)?.stabilise
7042 }
7043
7044 /// Waveform style flags on the clip at `idx` of `lane`. Bit 0 marks it
7045 /// a visualizer; the rest are outline/smooth/fast/tint. `false` (no
7046 /// history) for an index that is not there.
7047 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
7048 if idx >= self.lane(lane).len() {
7049 return false;
7050 }
7051 self.snapshot();
7052 self.lane_mut(lane).expect("checked above")[idx].visualizer = flags;
7053 true
7054 }
7055
7056 /// Give the clip at `idx` of `lane` this packed look: one undo step, and
7057 /// `false` (with no history) for an index that is not there, the way every
7058 /// other setter refuses.
7059 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7060 self.write_viz_paint(lane, idx, paint, true)
7061 }
7062
7063 /// [`set_viz_paint`](Self::set_viz_paint) without the undo step: the
7064 /// samples *inside* one pointer drag across the colour wheel, whose first
7065 /// write (a plain `set_viz_paint`) already took the snapshot the gesture
7066 /// rolls back to. One drag is one undo, not one per sample.
7067 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
7068 self.flat.clear();
7069 self.write_viz_paint(lane, idx, paint, false)
7070 }
7071
7072 fn write_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64, snapshot: bool) -> bool {
7073 if idx >= self.lane(lane).len() {
7074 return false;
7075 }
7076 if snapshot {
7077 self.snapshot();
7078 }
7079 self.lane_mut(lane).expect("checked above")[idx].viz_paint = paint;
7080 true
7081 }
7082
7083 /// Timeline frames of ramp-up from silence at the start of the clip at
7084 /// `idx` of `lane`. `0` for an index that is not there, same as a clip
7085 /// that has none.
7086 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
7087 self.lane(lane).get(idx).map_or(0, |c| c.fade_in)
7088 }
7089
7090 /// Sets it, clamped to the clip's own length ([`Clip::frames`]) -- a fade
7091 /// can shrink a clip's audible middle to nothing but never ask for more
7092 /// ramp than the clip has frames. One undo step like [`Project::set_fit`],
7093 /// and `false` (no history) for an index that is not there.
7094 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7095 if idx >= self.lane(lane).len() {
7096 return false;
7097 }
7098 self.snapshot();
7099 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7100 clip.fade_in = frames.min(clip.frames());
7101 true
7102 }
7103
7104 /// Timeline frames of ramp-down to silence at the end of the clip at
7105 /// `idx` of `lane`. Same promise as [`Project::fade_in_of`].
7106 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
7107 self.lane(lane).get(idx).map_or(0, |c| c.fade_out)
7108 }
7109
7110 /// Sets it. Same promises as [`Project::set_fade_in`].
7111 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7112 if idx >= self.lane(lane).len() {
7113 return false;
7114 }
7115 self.snapshot();
7116 let clip = &mut self.lane_mut(lane).expect("checked above")[idx];
7117 clip.fade_out = frames.min(clip.frames());
7118 true
7119 }
7120
7121 /// Timeline frames of cross-dissolve the clip at `idx` of `lane` plays
7122 /// into its successor, at its own end. `0` for an index that is not
7123 /// there, same as a clip that has none.
7124 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
7125 self.lane(lane).get(idx).map_or(0, |c| c.transition_out)
7126 }
7127
7128 /// Sets it, clamped to the clip's own length and to how many frames its
7129 /// successor on `lane` actually offers -- a dissolve can shrink a clip's
7130 /// visible middle to nothing but never ask for more than the two clips
7131 /// between them have. `false` -- no history -- unless `lane` is video,
7132 /// `idx + 1` is in bounds, and the two clips are adjacent: the second's
7133 /// [`Clip::start`] is exactly the first's [`Clip::end`], no gap between
7134 /// them. One undo step like [`Project::set_fade_out`].
7135 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7136 if lane.kind != LaneKind::Video {
7137 return false;
7138 }
7139 let clips = self.lane(lane);
7140 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7141 return false;
7142 };
7143 if a.end() != b.start {
7144 return false;
7145 }
7146 let cap = a.frames().min(b.frames());
7147 self.snapshot();
7148 self.lane_mut(lane).expect("checked above")[idx].transition_out = frames.min(cap);
7149 true
7150 }
7151
7152 /// The kind of the transition the clip at `idx` of `lane` plays into its
7153 /// successor; a dissolve for an index that is not there.
7154 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
7155 self.lane(lane).get(idx).map_or_else(Default::default, |c| c.transition_kind)
7156 }
7157
7158 /// [`Project::set_transition_out`] with a kind: sets both in one undo step.
7159 pub fn set_transition(
7160 &mut self,
7161 lane: Lane,
7162 idx: usize,
7163 kind: crate::transitions::TransitionKind,
7164 frames: u32,
7165 ) -> bool {
7166 if lane.kind != LaneKind::Video {
7167 return false;
7168 }
7169 let clips = self.lane(lane);
7170 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7171 return false;
7172 };
7173 if a.end() != b.start {
7174 return false;
7175 }
7176 let cap = a.frames().min(b.frames());
7177 self.snapshot();
7178 let a = &mut self.lane_mut(lane).expect("checked above")[idx];
7179 a.transition_out = frames.min(cap);
7180 a.transition_kind = kind;
7181 true
7182 }
7183
7184 /// Crossfades the audio clip at `idx` of `lane` into the one immediately
7185 /// after it, over `frames` timeline frames: sets `idx`'s
7186 /// [`Clip::fade_out`] and its neighbour's [`Clip::fade_in`] to `frames`,
7187 /// each clamped to its own clip's length. `false` -- no history -- unless
7188 /// `lane` is audio, `idx + 1` is in bounds, and the two clips are
7189 /// adjacent: the second's [`Clip::start`] is exactly the first's
7190 /// [`Clip::end`], no gap between them.
7191 ///
7192 /// This is the whole mechanism, not a stand-in for one: a *real*
7193 /// cross-fade -- both takes heard at once, blending -- is what two clips
7194 /// **overlapping** on separate lanes already get for free from the
7195 /// mixer's own per-lane sum ([`crate::audio::open_mixed_streams_master`]).
7196 /// This call only shapes the edges of two clips already sitting
7197 /// end-to-end on *one* lane, so the join between them fades like one did.
7198 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
7199 if lane.kind != LaneKind::Audio {
7200 return false;
7201 }
7202 let clips = self.lane(lane);
7203 let (Some(a), Some(b)) = (clips.get(idx), clips.get(idx + 1)) else {
7204 return false;
7205 };
7206 if a.end() != b.start {
7207 return false;
7208 }
7209 self.snapshot();
7210 let clips = self.lane_mut(lane).expect("checked above");
7211 clips[idx].fade_out = frames.min(clips[idx].frames());
7212 clips[idx + 1].fade_in = frames.min(clips[idx + 1].frames());
7213 true
7214 }
7215
7216 /// Every frame number on every lane rewritten onto a timeline counted at
7217 /// another rate: `k` is old timeline frames per new one, `counts` is how
7218 /// long each source is on the *new* timeline (indexed as
7219 /// [`Project::sources`] is), and the edit survives as the same seconds of
7220 /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to
7221 /// the edit list, and the only thing that touches the frame numbers without
7222 /// being an edit anyone made.
7223 ///
7224 /// Every position -- a clip's start and its end alike -- goes through the
7225 /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap
7226 /// stays a gap, and a take's picture and its sound land on the same frame on
7227 /// their two lanes: no lane can drift against another. A clip is then only
7228 /// ever made to *fit* the room its own start and end mapped to, never to
7229 /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor
7230 /// below is the backstop for the one case that could: a slow clip so short
7231 /// that no source range fits its new room at all).
7232 ///
7233 /// Rounded to the nearest frame of the new grid, every boundary, length and
7234 /// envelope ([`Rate::timeline_nearest`]), so no round trip drifts: a second
7235 /// trip lands where the first did. Not exact both ways in general: a frame
7236 /// of one grid can fall between two of the other, and a rate change keeps
7237 /// only the frame it rounds to. An edit whose frames sit on both grids (on
7238 /// a whole second at 30, 25 and 24 fps) comes back exactly; any other
7239 /// boundary comes back within one frame. The exact fix is to hold the edit
7240 /// in seconds rather than frames, which every frame number in this module
7241 /// is measured in.
7242 pub fn retime(&mut self, k: Rate, counts: &[u32]) {
7243 for lane in &mut self.lanes {
7244 let mut cursor = 0;
7245 for clip in &mut lane.clips {
7246 let start = k.timeline_nearest(clip.start).max(cursor);
7247 // The room its own end mapped to -- never zero, since a clip is
7248 // never empty even on a grid too coarse to hold it.
7249 let room = k.timeline_nearest(clip.end()).saturating_sub(start).max(1);
7250 let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1);
7251 // Its footage, held inside the file's new length: a clip whose
7252 // out-point was the last frame of its source must not come out
7253 // of this naming a frame past the end -- that is a project that
7254 // would not open again ([`crate::PlaybackSession::open_project`]
7255 // refuses one by name).
7256 let in_frame = k.timeline_nearest(clip.in_frame).min(count - 1);
7257 let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame);
7258 // The envelopes are frame counts measured from the clip's own
7259 // start (fades in), its own end (fades out and a dissolve into
7260 // the next clip). Each is its own length in seconds, rounded to the
7261 // nearest frame of the new grid, not a difference of two rounded
7262 // boundaries, which is what let a dissolve drift a frame per trip.
7263 let fade_in = k.timeline_nearest(clip.fade_in);
7264 let fade_out = k.timeline_nearest(clip.fade_out);
7265 let transition = k.timeline_nearest(clip.transition_out);
7266 clip.start = start;
7267 clip.in_frame = in_frame;
7268 clip.out_frame = in_frame + len;
7269 let frames = clip.frames();
7270 clip.fade_in = fade_in.min(frames);
7271 clip.fade_out = fade_out.min(frames);
7272 clip.transition_out = transition.min(frames);
7273 // A volume point is a source frame, numbered the way `in_frame`
7274 // is, so it moves with the footage. Two points that land on one
7275 // frame keep the first, since the envelope holds one per frame.
7276 let mut last = None;
7277 clip.gain_keys.retain_mut(|key| {
7278 key.at = k.timeline_nearest(key.at);
7279 let keep = last != Some(key.at);
7280 last = Some(key.at);
7281 keep
7282 });
7283 // The placement keys are source frames too, so they follow the
7284 // same grid, one point per frame as the envelope keeps them.
7285 let mut last = None;
7286 clip.transform_keys.retain_mut(|key| {
7287 key.at = k.timeline_nearest(key.at);
7288 let keep = last != Some(key.at);
7289 last = Some(key.at);
7290 keep
7291 });
7292 let mut last = None;
7293 clip.opacity_keys.retain_mut(|key| {
7294 key.at = k.timeline_nearest(key.at);
7295 let keep = last != Some(key.at);
7296 last = Some(key.at);
7297 keep
7298 });
7299 let mut last = None;
7300 clip.color_keys.retain_mut(|key| {
7301 key.at = k.timeline_nearest(key.at);
7302 let keep = last != Some(key.at);
7303 last = Some(key.at);
7304 keep
7305 });
7306 cursor = clip.end();
7307 }
7308 // A dissolve is only as long as the clip it dissolves into allows
7309 // too, which the rescale above cannot see one clip at a time.
7310 for i in 1..lane.clips.len() {
7311 let (before, after) = lane.clips.split_at_mut(i);
7312 let (a, b) = (&mut before[i - 1], &after[0]);
7313 if a.end() == b.start {
7314 a.transition_out = a.transition_out.min(b.frames());
7315 }
7316 }
7317 // A subtitle's *window* is in microseconds and a rate change moves
7318 // no seconds, so only where it sits is remapped -- through the same
7319 // [`Rate::timeline_at`] every clip boundary goes through, so a
7320 // caption still starts on the frame its picture does.
7321 let mut cursor = 0;
7322 for sub in &mut lane.subs {
7323 let start = k.timeline_nearest(sub.start).max(cursor);
7324 sub.frames = k.timeline_nearest(sub.end()).saturating_sub(start).max(1);
7325 sub.start = start;
7326 cursor = sub.end();
7327 }
7328 }
7329 // A title is placed and sized in frames like a clip and its captions,
7330 // so it takes the same grid: its window maps start to end, and its
7331 // fades are re-measured from the boundary each one is counted from.
7332 // Held inside the largest frame a title may end on, which is the check
7333 // a load makes of every title.
7334 for title in &mut self.titles {
7335 let (old_start, old_end) = (title.start, title.end());
7336 let start = k.timeline_nearest(old_start);
7337 let end = k.timeline_nearest(old_end).min(MAX_TITLE_END).max(start + 1);
7338 let frames = end - start;
7339 title.fade_in = k.timeline_nearest(title.fade_in).min(frames);
7340 title.fade_out = k.timeline_nearest(title.fade_out).min(frames);
7341 title.start = start;
7342 title.frames = frames;
7343 }
7344 // A chapter is a single frame, so it takes the grid as a title's start
7345 // does; two that land on one frame keep the first.
7346 for chapter in &mut self.chapters {
7347 chapter.frame = k.timeline_nearest(chapter.frame);
7348 }
7349 self.chapters.dedup_by_key(|c| c.frame);
7350 // A marker's start and end take the grid the same way.
7351 for m in &mut self.markers {
7352 let end = k.timeline_nearest(m.frame + m.length);
7353 m.frame = k.timeline_nearest(m.frame);
7354 m.length = end.saturating_sub(m.frame);
7355 }
7356 self.markers.sort_by_key(|m| m.frame);
7357 }
7358
7359 /// Length of the timeline in frames: where the *last* lane runs out. A lane
7360 /// that ends early is a trailing gap in that lane, not a shorter timeline.
7361 ///
7362 /// A subtitle lane counts like any other: a caption placed past the last
7363 /// picture holds the timeline open under it, exactly as an `A2` running
7364 /// past `V1` does, rather than being silently clipped away by the length
7365 /// ([`crate::export::timeline_cues`] clips cues to this).
7366 pub fn timeline_frames(&self) -> u32 {
7367 self.lanes
7368 .iter()
7369 .filter_map(|l| match l.kind {
7370 LaneKind::Subtitle => l.subs.last().map(SubClip::end),
7371 _ => l.clips.last().map(Clip::end),
7372 })
7373 .max()
7374 .unwrap_or(0)
7375 .max(self.title_end())
7376 }
7377
7378 /// The same, counting the *media* alone: where the last picture or sound
7379 /// runs out, with the captions over them ignored.
7380 ///
7381 /// What an export actually writes ends here -- the picture loop walks the
7382 /// composite spans and the file stops with them -- so this is the length a
7383 /// cue has to be inside of to be written at all (what
7384 /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to
7385 /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last
7386 /// thing is a picture or a sound, which is every timeline that has no
7387 /// caption hanging past the end of both.
7388 pub fn media_frames(&self) -> u32 {
7389 self.lanes
7390 .iter()
7391 .filter(|l| l.kind != LaneKind::Subtitle)
7392 .filter_map(|l| l.clips.last().map(Clip::end))
7393 .max()
7394 .unwrap_or(0)
7395 // A title is picture too: one past the last clip runs on over black,
7396 // so the export and the picture cover it.
7397 .max(self.title_end())
7398 }
7399
7400 /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs
7401 /// to lay clips out. Gaps show up as the holes between consecutive entries.
7402 pub fn clip_spans(&self) -> Vec<(u32, u32)> {
7403 self.lane_spans(Lane::V1)
7404 }
7405
7406 pub fn lane_spans(&self, lane: Lane) -> Vec<(u32, u32)> {
7407 // Timeline frames, not source ones: a box on a lane is as wide as the
7408 // clip is long *there*, which a speed halves or quadruples.
7409 self.lane(lane)
7410 .iter()
7411 .map(|c| (c.start, c.frames()))
7412 .collect()
7413 }
7414
7415 /// Timeline frame -> `(clip index, source frame)` in `lane`. `None` in a gap
7416 /// and past the end -- [`Project::span_at`] is the version that tells those
7417 /// two apart.
7418 pub fn map(&self, lane: Lane, timeline_frame: u32) -> Option<(usize, u32)> {
7419 let clips = self.lane(lane);
7420 let idx = at(clips, timeline_frame)?;
7421 Some((idx, source_frame(&clips[idx], timeline_frame)))
7422 }
7423
7424 /// [`map`](Project::map) on `V1` -- the mapping a decoder follows.
7425 pub fn map_timeline(&self, timeline_frame: u32) -> Option<(usize, u32)> {
7426 self.map(Lane::V1, timeline_frame)
7427 }
7428
7429 /// What `lane` holds from `timeline_frame` on: the rest of the clip covering
7430 /// it, or the gap running to the next clip (or to the end of the timeline,
7431 /// which is where a lane shorter than its neighbour keeps showing black).
7432 /// `None` at or past the end of the timeline, which is the only "nothing
7433 /// left" there is.
7434 pub fn span_at(&self, lane: Lane, timeline_frame: u32) -> Option<Span> {
7435 let total = self.timeline_frames();
7436 if timeline_frame >= total {
7437 return None;
7438 }
7439 let clips = self.lane(lane);
7440 Some(match at(clips, timeline_frame) {
7441 Some(idx) => {
7442 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7443 Span {
7444 start: timeline_frame,
7445 len: clips[idx].end() - timeline_frame,
7446 from: Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7447 speed,
7448 ramp,
7449 reverse: clips[idx].reversed,
7450 pitch: clips[idx].pitch,
7451 }
7452 }
7453 None => Span {
7454 start: timeline_frame,
7455 speed: Speed::NORMAL,
7456 ramp: None,
7457 reverse: false,
7458 pitch: 0,
7459 // The next placement, or the end of the timeline: a gap is
7460 // bounded by what comes after it, never by its own bookkeeping.
7461 len: clips
7462 .iter()
7463 .find(|c| c.start > timeline_frame)
7464 .map_or(total, |c| c.start)
7465 - timeline_frame,
7466 from: None,
7467 },
7468 })
7469 }
7470
7471 /// Every span of `lane` from `timeline_frame` to the end of the timeline,
7472 /// gaps included -- the whole play list, which is what an export walks.
7473 pub fn spans_from(&self, lane: Lane, timeline_frame: u32) -> Vec<Span> {
7474 let mut out = Vec::new();
7475 let mut t = timeline_frame;
7476 while let Some(span) = self.span_at(lane, t) {
7477 t = span.end();
7478 out.push(span);
7479 }
7480 out
7481 }
7482
7483 /// What the *composite* shows from `timeline_frame` on -- the answer
7484 /// [`span_at`](Project::span_at) gives for one lane, resolved across every
7485 /// video lane by one rule: **the topmost lane with a clip there wins**, and
7486 /// topmost is the *last* video lane in display order, so `V2` covers `V1`
7487 /// (the usual overlay convention). A frame no video lane covers is a gap,
7488 /// which is black however many lanes are above or below it.
7489 ///
7490 /// No blending, so exactly one lane is visible at a time and the composite
7491 /// is itself a span list -- which is why one decoder plays it, the same one
7492 /// a single-lane timeline uses, rather than N running at once.
7493 ///
7494 /// The span is cut short wherever a *higher* lane's clip starts, because
7495 /// from that frame on a different lane wins; that is what makes walking
7496 /// [`composite_spans_from`](Project::composite_spans_from) correct.
7497 ///
7498 /// corner-cut: alpha, opacity or any blend mode makes this untrue -- two
7499 /// lanes would then be visible in one frame and the caller needs a decoder
7500 /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
7501 /// (this same walk, per lane) feeding N decoders.
7502 pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
7503 let total = self.timeline_frames();
7504 if timeline_frame >= total {
7505 return None;
7506 }
7507 let video = self.video_lanes();
7508 // The last covering lane is the winner; only the lanes above it can
7509 // interrupt what it shows.
7510 let winner = video
7511 .iter()
7512 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
7513 let (from, speed, ramp, until, reverse) = match winner {
7514 Some(i) => {
7515 let clips = self.lane(video[i]);
7516 let idx = at(clips, timeline_frame).expect("just found above");
7517 let (speed, ramp) = span_speed_of(&clips[idx], timeline_frame);
7518 (
7519 Some((clips[idx].source, source_frame(&clips[idx], timeline_frame))),
7520 speed,
7521 ramp,
7522 clips[idx].end(),
7523 clips[idx].reversed,
7524 )
7525 }
7526 // Nothing covers it: black until something above the floor starts.
7527 None => (None, Speed::NORMAL, None, total, false),
7528 };
7529 let takeover = video[winner.map_or(0, |i| i + 1)..]
7530 .iter()
7531 .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
7532 .map(|c| c.start)
7533 .min();
7534 Some(Span {
7535 start: timeline_frame,
7536 len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
7537 from,
7538 speed,
7539 ramp,
7540 reverse,
7541 pitch: 0,
7542 })
7543 }
7544
7545 /// The video lanes in display order, topmost last -- the order the composite
7546 /// rule counts in. A hidden one is not in it: the picture is composed from
7547 /// what is visible, so a hidden lane is black where it is the only one
7548 /// covering and the lane below shows through where it is not.
7549 fn video_lanes(&self) -> Vec<Lane> {
7550 self.lanes()
7551 .into_iter()
7552 .filter(|l| l.kind == LaneKind::Video && !self.lane_hidden(*l))
7553 .collect()
7554 }
7555
7556 /// *Which* clip the composite shows at `timeline_frame`, named: the winner
7557 /// of [`composite_span_at`](Project::composite_span_at)'s own rule and its
7558 /// index on that lane. `None` over a gap and past the end. What a front-end
7559 /// asks to act on "the clip on screen" without re-deriving the rule.
7560 pub fn composite_clip_at(&self, timeline_frame: u32) -> Option<(Lane, usize)> {
7561 let video = self.video_lanes();
7562 let winner = video
7563 .iter()
7564 .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some())?;
7565 Some((video[winner], at(self.lane(video[winner]), timeline_frame)?))
7566 }
7567
7568 /// Which clip of *one* lane `timeline_frame` falls on, or `None` over a gap
7569 /// and past that lane's end. [`composite_clip_at`](Project::composite_clip_at)
7570 /// answers "the clip on screen"; this answers it per lane, which is what
7571 /// walking the lanes for something to select needs.
7572 pub fn lane_clip_at(&self, lane: Lane, timeline_frame: u32) -> Option<usize> {
7573 at(self.lane(lane), timeline_frame)
7574 }
7575
7576 /// How the composite is graded at `timeline_frame`, so the picture playback
7577 /// converts and the one an export encodes are graded from one answer.
7578 /// `None` over a gap (black is black) and for a clip nobody has graded,
7579 /// which is the byte-identical path everywhere.
7580 pub fn composite_color_at(&self, timeline_frame: u32) -> Option<&ColorParams> {
7581 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7582 self.color_of(lane, idx)
7583 }
7584
7585 /// [`composite_color_at`](Self::composite_color_at)'s twin for
7586 /// [`Clip::transform`]: `None` over a gap and for a clip at its fit
7587 /// policy's own placement.
7588 pub fn composite_transform_at(&self, timeline_frame: u32) -> Option<&TransformParams> {
7589 let (lane, idx) = self.composite_clip_at(timeline_frame)?;
7590 self.transform_of(lane, idx)
7591 }
7592
7593 /// How the composite meets the project canvas at `timeline_frame`, so the
7594 /// picture playback composes and the one an export encodes are placed from
7595 /// one answer. `Fit` over a gap, where black is already the canvas.
7596 pub fn composite_fit_at(&self, timeline_frame: u32) -> FitPolicy {
7597 self.composite_clip_at(timeline_frame)
7598 .map_or(FitPolicy::default(), |(lane, idx)| self.fit_of(lane, idx))
7599 }
7600
7601 /// Waveform flags of the topmost video clip at `timeline_frame`, or 0
7602 /// over a gap / a picture that is not a visualizer.
7603 pub fn composite_visualizer_at(&self, timeline_frame: u32) -> u8 {
7604 self.composite_clip_at(timeline_frame)
7605 .map(|(lane, idx)| self.lane(lane)[idx].visualizer)
7606 .unwrap_or(0)
7607 }
7608
7609 /// Packed look ([`Clip::viz_paint`]) of the topmost video clip at
7610 /// `timeline_frame`, or zero over a gap / a picture that is not a
7611 /// visualizer.
7612 pub fn composite_viz_paint_at(&self, timeline_frame: u32) -> u64 {
7613 self.composite_clip_at(timeline_frame)
7614 .map(|(lane, idx)| self.lane(lane)[idx].viz_paint)
7615 .unwrap_or(0)
7616 }
7617
7618 /// [`spans_from`](Project::spans_from) over the composite: every stretch the
7619 /// viewer sees from `timeline_frame` to the end, in order. What an export
7620 /// encodes and what playback walks at a clip boundary.
7621 pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
7622 let mut out = Vec::new();
7623 let mut t = timeline_frame;
7624 while let Some(span) = self.composite_span_at(t) {
7625 t = span.end();
7626 out.push(span);
7627 }
7628 out
7629 }
7630
7631 /// The frame nearest `frame`, within `reach` frames either side, at which a cut lands
7632 /// cleanly on every lane -- `frame` itself when it does. `None` when no such frame is
7633 /// that near, which is what a cut or a freeze there is refused for.
7634 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
7635 let clean = |f: u32| {
7636 self.lanes.iter().all(|l| {
7637 l.clips
7638 .iter()
7639 .all(|c| !(c.start < f && f < c.end()) || split_source(c, f).is_some())
7640 })
7641 };
7642 (0..=reach)
7643 .flat_map(|d| [frame.checked_add(d), frame.checked_sub(d)])
7644 .flatten()
7645 .find(|&f| clean(f))
7646 }
7647
7648 /// Split every lane at `timeline_frame`, so that frame becomes the first
7649 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
7650 /// (`false`, no change) when no lane has a clip to split there -- at a
7651 /// placement's own start, in a gap, and past the end -- all of which would
7652 /// produce an empty clip or nothing at all.
7653 ///
7654 /// Lanes' halves share an id only where they are the *same* span: the lanes
7655 /// are edited apart, so the clip being cut here may start (or end)
7656 /// somewhere else on another lane, and a group id whose clips disagree
7657 /// about their span is not one take (see [`links_are_consistent`], which
7658 /// refuses to load one).
7659 ///
7660 /// Metadata only: no mapping changes, in any lane.
7661 pub fn split(&mut self, timeline_frame: u32) -> bool {
7662 self.write_split(timeline_frame, true, &all_lanes(&self.lanes))
7663 }
7664
7665 /// [`split`](Project::split) on the lanes in `scope` only: the lanes outside
7666 /// it keep their clip across the frame. `false`, no change, as `split`.
7667 pub fn split_on(&mut self, timeline_frame: u32, scope: &[Lane]) -> bool {
7668 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
7669 self.write_split(timeline_frame, true, &on)
7670 }
7671
7672 /// [`split`](Project::split), with the snapshot optional and the lanes
7673 /// named: a batch that has already taken a snapshot
7674 /// ([`speed_regions`](Project::speed_regions)) splits at two frames per
7675 /// region and must still be one undo press, and a *scoped* batch must not
7676 /// cut a lane it was told to leave alone.
7677 fn write_split(&mut self, timeline_frame: u32, snapshot: bool, on: &[usize]) -> bool {
7678 let cut: Vec<Option<Clip>> = self
7679 .lanes
7680 .iter()
7681 .enumerate()
7682 .map(|(i, l)| {
7683 on.contains(&i)
7684 .then(|| splittable(&l.clips, timeline_frame).map(|idx| l.clips[idx].clone()))
7685 .flatten()
7686 })
7687 .collect();
7688 // The same question on the subtitle lanes, in their own arithmetic: a
7689 // razor cuts the captions with the picture, and a frame where only a
7690 // caption can be cut is still a cut.
7691 let cut_subs: Vec<bool> = self
7692 .lanes
7693 .iter()
7694 .enumerate()
7695 .map(|(i, l)| {
7696 on.contains(&i)
7697 && l.subs
7698 .iter()
7699 .any(|s| s.start < timeline_frame && timeline_frame < s.end())
7700 })
7701 .collect();
7702 // The links the captions carry, read before the room is opened below
7703 // -- `sub_open_room` takes the id off both halves, exactly as
7704 // `open_room` does for a clip, and the split hands the halves theirs
7705 // back afterwards.
7706 let sub_orig: Vec<Option<u32>> = self
7707 .lanes
7708 .iter()
7709 .zip(&cut_subs)
7710 .map(|(l, &cut)| {
7711 cut.then(|| {
7712 l.subs
7713 .iter()
7714 .find(|s| s.start < timeline_frame && timeline_frame < s.end())
7715 .and_then(|s| s.link)
7716 })
7717 .flatten()
7718 })
7719 .collect();
7720 if cut.iter().all(Option::is_none) && !cut_subs.contains(&true) {
7721 return false;
7722 }
7723 if snapshot {
7724 self.snapshot();
7725 }
7726 // The captions' words are divided before their windows are cut, so
7727 // the words on the far side of the split stay with the far side.
7728 self.split_cues_across(on, &[timeline_frame], false);
7729 for (data, _) in self
7730 .lanes
7731 .iter_mut()
7732 .zip(&cut_subs)
7733 .filter(|&(_, &cut)| cut)
7734 {
7735 // A split is room of no width: the halves keep their windows by
7736 // proportion and nothing moves.
7737 sub_open_room(&mut data.subs, timeline_frame, 0);
7738 debug_assert!(subs_sorted_disjoint(&data.subs));
7739 }
7740 // Each side is its own question, and the answer is the group the clip
7741 // already carried: the left half *keeps* its take's id -- the take the
7742 // frames before the cut still are -- and the right halves of one take
7743 // share one fresh id of their own, clips and captions alike. A lane
7744 // holding no group (a `place`ment, a caption nobody grouped) comes out
7745 // of the cut holding none, which is what it went in with. The captions'
7746 // own links were drawn above, before the room opened.
7747 let orig: Vec<Option<u32>> = cut
7748 .iter()
7749 .map(|c| c.as_ref().and_then(|c| c.link))
7750 .collect();
7751 let mut distinct: Vec<u32> = Vec::new();
7752 for id in orig.iter().chain(&sub_orig).flatten() {
7753 if !distinct.contains(id) {
7754 distinct.push(*id);
7755 }
7756 }
7757 // A cut on a *subset* of the lanes leaves the take's other members whole
7758 // on lanes that were not cut: the cut halves no longer agree with them
7759 // about their span, so the take is unlinked at the cut -- every member,
7760 // in this same snapshot (one undo puts it back).
7761 let detach = distinct.iter().any(|&id| {
7762 self.lanes.iter().enumerate().any(|(j, d)| {
7763 !on.contains(&j)
7764 && (d.clips.iter().any(|c| c.link == Some(id))
7765 || d.subs.iter().any(|s| s.link == Some(id)))
7766 })
7767 });
7768 let fresh: Vec<u32> = (0..distinct.len()).map(|_| self.new_link()).collect();
7769 let right_of = |link: Option<u32>| {
7770 link.and_then(|id| distinct.iter().position(|&d| d == id))
7771 .map(|at| fresh[at])
7772 };
7773 for (l, data) in self.lanes.iter_mut().enumerate() {
7774 if !cut_subs[l] {
7775 continue;
7776 }
7777 // The pair the razor just made: they touch at the frame it cut.
7778 if let Some(idx) = data
7779 .subs
7780 .iter()
7781 .position(|s| s.end() == timeline_frame)
7782 .filter(|&idx| {
7783 data.subs
7784 .get(idx + 1)
7785 .is_some_and(|n| n.start == timeline_frame)
7786 })
7787 {
7788 data.subs[idx].link = sub_orig[l];
7789 data.subs[idx + 1].link = right_of(sub_orig[l]);
7790 }
7791 }
7792 for (data_i, data) in self.lanes.iter_mut().enumerate() {
7793 // The lanes this call was not scoped to are not cut, whatever their
7794 // own clips would allow.
7795 let Some(idx) =
7796 splittable(&data.clips, timeline_frame).filter(|_| cut[data_i].is_some())
7797 else {
7798 continue;
7799 };
7800 let mut tail = data.clips[idx].clone();
7801 // Where the cut lands *in the file*, which is the clip's own rate
7802 // away from where it lands on the timeline. Both halves keep the
7803 // speed, and `splittable` has already refused any frame at which
7804 // the two would not add up to the one being cut.
7805 let cut_at = split_source(&tail, timeline_frame).expect("splittable said so");
7806 let (head_speed, tail_speed) = split_keys(&tail, timeline_frame);
7807 tail.speed_keys = tail_speed;
7808 data.clips[idx].speed_keys = head_speed;
7809 let reversed = tail.reversed;
7810 match reversed {
7811 true => tail.out_frame = cut_at,
7812 false => tail.in_frame = cut_at,
7813 }
7814 tail.start = timeline_frame;
7815 // The placement animation is divided, not copied: each half keeps
7816 // its own keys and a key at the cut (see `split_transform_keys`). The
7817 // lower keys go to the tail of a reversed clip, which plays them last.
7818 let (below, above) = split_transform_keys(&data.clips[idx].transform_keys, cut_at);
7819 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7820 tail.transform_keys = tail_keys;
7821 data.clips[idx].transform_keys = head_keys;
7822 let (head_keys, tail_keys) =
7823 split_transform_keys(&data.clips[idx].opacity_keys, tail.in_frame);
7824 tail.opacity_keys = tail_keys;
7825 data.clips[idx].opacity_keys = head_keys;
7826 let (head_keys, tail_keys) =
7827 split_transform_keys(&data.clips[idx].color_keys, tail.in_frame);
7828 tail.color_keys = tail_keys;
7829 data.clips[idx].color_keys = head_keys;
7830 // Each mask's keys divide the same way as the placement's, per stack position.
7831 let masks: Vec<_> = data.clips[idx]
7832 .effects
7833 .iter()
7834 .map(|e| split_transform_keys(&e.keys, cut_at))
7835 .collect();
7836 for ((tail_e, head_e), (below, above)) in tail.effects.iter_mut().zip(data.clips[idx].effects.iter_mut()).zip(masks) {
7837 let (head_keys, tail_keys) = if reversed { (above, below) } else { (below, above) };
7838 tail_e.keys = tail_keys;
7839 head_e.keys = head_keys;
7840 }
7841 tail.link = right_of(orig[data_i]);
7842 // A split makes a new edge for each half, and a fade is a promise
7843 // about an edge: only the half that *kept* the original edge
7844 // keeps that fade, re-clamped to its own now-shorter length (a
7845 // cut inside the ramp shortens it, never leaves it pointing past
7846 // the clip it is on); the edge the cut itself made starts, or
7847 // ends, flat -- there was no silence there to ramp out of.
7848 tail.fade_in = 0;
7849 tail.fade_out = tail.fade_out.min(tail.frames());
7850 // A dissolve is a promise about the *end* edge, same as
7851 // `fade_out`: only the half that kept the clip's original end
7852 // (the tail) keeps it, re-clamped to its own now-shorter length;
7853 // the head's new end is the cut the razor just made, which starts
7854 // flat -- there was no successor to dissolve into there.
7855 tail.transition_out = tail.transition_out.min(tail.frames());
7856 match reversed {
7857 true => data.clips[idx].in_frame = cut_at,
7858 false => data.clips[idx].out_frame = cut_at,
7859 }
7860 data.clips[idx].link = orig[data_i];
7861 data.clips[idx].fade_out = 0;
7862 data.clips[idx].transition_out = 0;
7863 data.clips[idx].transition_kind = Default::default();
7864 data.clips[idx].fade_in = data.clips[idx].fade_in.min(data.clips[idx].frames());
7865 data.clips.insert(idx + 1, tail);
7866 }
7867 if detach {
7868 // Every member of the take gets an id of its own, as `ungroup` gives
7869 // them: each half is detached (a lone id), never a whole take.
7870 let gone: Vec<u32> = distinct.iter().chain(&fresh).copied().collect();
7871 let count: usize = self
7872 .lanes
7873 .iter()
7874 .map(|d| {
7875 d.clips.iter().filter(|c| c.link.is_some_and(|id| gone.contains(&id))).count()
7876 + d.subs.iter().filter(|s| s.link.is_some_and(|id| gone.contains(&id))).count()
7877 })
7878 .sum();
7879 let mut own = (0..count).map(|_| self.new_link()).collect::<Vec<_>>();
7880 for data in &mut self.lanes {
7881 for c in data.clips.iter_mut().filter(|c| c.link.is_some_and(|id| gone.contains(&id))) {
7882 c.link = own.pop();
7883 }
7884 for s in data.subs.iter_mut().filter(|s| s.link.is_some_and(|id| gone.contains(&id))) {
7885 s.link = own.pop();
7886 }
7887 }
7888 }
7889 true
7890 }
7891
7892 /// The inverse of [`split`](Project::split): rejoin the placements that meet
7893 /// at `timeline_frame` in every lane and put the result back in one group.
7894 /// Only what a split could have produced is rejoined -- the two sides must
7895 /// touch on the timeline *and* be consecutive frames of the same source --
7896 /// so the clip list comes back exactly as it was and traversal with it.
7897 /// `false` when no lane has such a pair. The rejoined placement keeps the
7898 /// **left** half's id, which is the take the split left on it: rejoining a
7899 /// cut take puts the take back, id and all.
7900 pub fn regroup(&mut self, timeline_frame: u32) -> bool {
7901 // What each lane would end up covering, if it joins here at all.
7902 let joined: Vec<Option<(u32, u32)>> = self
7903 .lanes
7904 .iter()
7905 .map(|l| {
7906 joinable(&l.clips, timeline_frame)
7907 .map(|idx| (l.clips[idx].start, l.clips[idx + 1].end()))
7908 })
7909 .collect();
7910 // ...and the subtitle lanes' own halves, by [`sub_joinable`]'s rule.
7911 let join_subs: Vec<Option<usize>> = self
7912 .lanes
7913 .iter()
7914 .map(|l| sub_joinable(&l.subs, timeline_frame))
7915 .collect();
7916 if joined.iter().all(Option::is_none) && join_subs.iter().all(Option::is_none) {
7917 return false;
7918 }
7919 self.snapshot();
7920 for (data, sub) in self.lanes.iter_mut().zip(join_subs) {
7921 if let Some(idx) = sub {
7922 data.subs[idx].frames += data.subs[idx + 1].frames;
7923 // The left half's `in_us`, the right half's `out_us` -- which
7924 // is the SUM of two legal widths, because `sub_joinable` has
7925 // just established that the two halves are consecutive in the
7926 // *source* (`next.in_us == subs[idx].out_us`). Neither half
7927 // broke the ceiling and the whole does, so this is a composer
7928 // a per-arm check on one writer could never have found:
7929 // `set_window` is what makes the closed set closed.
7930 let (in_us, out_us) = (data.subs[idx].in_us, data.subs[idx + 1].out_us);
7931 set_window(&mut data.subs[idx], in_us, out_us);
7932 data.subs.remove(idx + 1);
7933 debug_assert!(subs_sorted_disjoint(&data.subs));
7934 }
7935 let Some(idx) = joinable(&data.clips, timeline_frame) else {
7936 continue;
7937 };
7938 match data.clips[idx].reversed {
7939 true => data.clips[idx].in_frame = data.clips[idx + 1].in_frame,
7940 false => data.clips[idx].out_frame = data.clips[idx + 1].out_frame,
7941 }
7942 data.clips.remove(idx + 1);
7943 }
7944 true
7945 }
7946
7947 /// Take the placement at `idx` of `lane` out of its group: every clip and
7948 /// every caption carrying its id -- on however many lanes -- is handed an
7949 /// id of its own, so from here on each half moves, trims and is deleted
7950 /// alone. The music video whose sound is to be cut against its picture
7951 /// starts here, and so does the caption that has to come off the picture it
7952 /// was pinned to.
7953 ///
7954 /// A group that holds more than one take gives each take back whole: a
7955 /// [`group`](Project::group_all) with a take member merges that take into
7956 /// the group, and one id cannot say which halves were a take before, so
7957 /// the halves are matched by what a take is -- clips with the same source,
7958 /// start and in/out points -- and each match keeps one id of its own. So
7959 /// ungrouping the picture of a take that was grouped with another clip
7960 /// leaves the take linked and detaches only the other clip. A group of one
7961 /// take, or one with a caption, is taken apart whole, as before.
7962 ///
7963 /// An id of its own rather than none at all: a half no other lane is grouped
7964 /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
7965 /// (see [`links_are_consistent`]), and it is what a front-end already draws
7966 /// as detached. `None` would instead say "was never part of a take", which
7967 /// is what a one-lane [`place`](Project::place) means.
7968 ///
7969 /// Metadata only, like a [`split`](Project::split): no mapping changes, so
7970 /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
7971 /// the group back. Refused (`false`, nothing changed) for an index that is
7972 /// not there, a placement in no group at all, and one whose group has no
7973 /// other half -- that one is already detached, and a refusal must not cost
7974 /// an undo step.
7975 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
7976 let Some(members) = self.group_of(lane, idx) else {
7977 return false;
7978 };
7979 if members.alone() {
7980 return false;
7981 }
7982 let Some(id) = self
7983 .lane(lane)
7984 .get(idx)
7985 .and_then(|c| c.link)
7986 .or_else(|| self.sub_lane(lane).get(idx).and_then(|s| s.link))
7987 else {
7988 return false;
7989 };
7990 self.snapshot();
7991 // The takes the group holds, by what a take is: its halves share these.
7992 let mut takes: Vec<TakeKey> = Vec::new();
7993 for data in &self.lanes {
7994 for c in data.clips.iter().filter(|c| c.link == Some(id)) {
7995 let k = take_key(c);
7996 if !takes.contains(&k) {
7997 takes.push(k);
7998 }
7999 }
8000 }
8001 let whole = takes.len() == 1 && members.subs.is_empty();
8002 // Drawn before the walk: `new_link` takes the whole project, and the
8003 // walk holds the lanes. One id per take (or per clip, when the group is
8004 // one take that comes apart), then one per caption.
8005 let clip_ids = if whole { members.clips.len() } else { takes.len() };
8006 let mut fresh = (0..clip_ids + members.subs.len()).map(|_| self.new_link()).collect::<Vec<_>>();
8007 let mut sub_fresh = fresh.split_off(clip_ids).into_iter();
8008 let mut next = 0;
8009 for data in &mut self.lanes {
8010 for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
8011 c.link = Some(if whole {
8012 next += 1;
8013 fresh[next - 1]
8014 } else {
8015 let k = take_key(c);
8016 fresh[takes.iter().position(|t| *t == k).expect("collected above")]
8017 });
8018 }
8019 for s in data.subs.iter_mut().filter(|s| s.link == Some(id)) {
8020 s.link = sub_fresh.next();
8021 }
8022 }
8023 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8024 true
8025 }
8026
8027 /// Put two clips on two lanes into one group, so what moves one moves the
8028 /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
8029 /// how a picture is regrouped with sound it was never opened with. Whatever
8030 /// either of them was grouped with comes along: those clips cover this same
8031 /// span already, so the result is one group and not two overlapping ones.
8032 ///
8033 /// Same frames or nothing: a group id names **one span** on however many
8034 /// lanes ([`links_are_consistent`] refuses to load anything else), so two
8035 /// clips that do not cover the same frames cannot be one take, and the
8036 /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
8037 /// run on `V1` and `V2` at once, and picture-with-sound is the case people
8038 /// mean, not the rule.
8039 ///
8040 /// Metadata only, one snapshot. The error says what is wrong, because
8041 /// `false` would not: a bad index, one lane twice (a group is at most one
8042 /// clip per lane), spans that disagree, and a pair that is already one take
8043 /// -- nothing changes, and none of them costs an undo step.
8044 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
8045 if a == b {
8046 return Err(format!(
8047 "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
8048 a.label()
8049 )
8050 .into());
8051 }
8052 let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
8053 p.lane(lane)
8054 .get(idx)
8055 .cloned()
8056 .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
8057 };
8058 let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
8059 if (x.start, x.end()) != (y.start, y.end()) {
8060 return Err(format!(
8061 "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
8062 a.label(),
8063 x.start,
8064 x.end(),
8065 b.label(),
8066 y.start,
8067 y.end()
8068 )
8069 .into());
8070 }
8071 if x.link.is_some() && x.link == y.link {
8072 return Err("those two are one take already".into());
8073 }
8074 self.snapshot();
8075 let id = self.new_link();
8076 // Every clip either of them was grouped with, by the same rule: all of
8077 // them cover this span, so one id over the lot stays consistent.
8078 let old = [x.link, y.link];
8079 for data in &mut self.lanes {
8080 for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
8081 if old.contains(&c.link) {
8082 c.link = Some(id);
8083 }
8084 }
8085 }
8086 // And the two themselves, which a `place` may have left in no group.
8087 self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
8088 self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
8089 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8090 Ok(())
8091 }
8092
8093 /// Put every placement the picks name into one group -- the group a hand
8094 /// builds with ctrl-click and a menu: the picture, its sound and the
8095 /// caption over it, on as many lanes as the picks name. What any of them
8096 /// was already grouped with rides along (one group, not two sharing a
8097 /// member), and the members keep their own spans: a group is one id over
8098 /// one placement per lane, and the offsets between them are what the group
8099 /// preserves -- a drag, a trim and a delete all move the members *by the
8100 /// same distance*, not to the same frames.
8101 ///
8102 /// No two picks may name one lane -- that is the one clip-per-lane rule,
8103 /// and the refusal says which lane -- and a pick that names nothing is
8104 /// refused with its own words. At least two picks, or there is nothing to
8105 /// group.
8106 ///
8107 /// Metadata only, one snapshot, so one [`Project::undo`] takes the group
8108 /// apart again. None of the refusals changes anything or costs an undo
8109 /// step.
8110 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
8111 if picks.len() < 2 {
8112 return Err("a group is two placements or more: pick another one first".into());
8113 }
8114 let mut seen: Vec<Lane> = Vec::with_capacity(picks.len());
8115 for &(lane, idx) in picks {
8116 if seen.contains(&lane) {
8117 return Err(format!(
8118 "a group is one placement per lane: {} is picked twice -- keep one clip per \
8119 track",
8120 lane.label()
8121 )
8122 .into());
8123 }
8124 seen.push(lane);
8125 let there = if lane.kind == LaneKind::Subtitle {
8126 idx < self.sub_lane(lane).len()
8127 } else {
8128 idx < self.lane(lane).len()
8129 };
8130 if !there {
8131 let what = if lane.kind == LaneKind::Subtitle {
8132 "subtitle"
8133 } else {
8134 "clip"
8135 };
8136 return Err(format!("there is no {what} {idx} on {}", lane.label()).into());
8137 }
8138 }
8139 let links: Vec<Option<u32>> = picks
8140 .iter()
8141 .map(|&(lane, idx)| {
8142 if lane.kind == LaneKind::Subtitle {
8143 self.sub_lane(lane)[idx].link
8144 } else {
8145 self.lane(lane)[idx].link
8146 }
8147 })
8148 .collect();
8149 // The picks are already one per lane (`seen`, above), but a pick's
8150 // *existing* group can carry a second member onto a lane another
8151 // pick (or another existing group in the merge) already occupies --
8152 // two captions on one sub lane, say, each grouped with a different
8153 // clip before this call. Merging both in would leave that lane with
8154 // two members of one id, which `links_are_consistent` may never see:
8155 // refused by name, before anything moves, rather than a group closed
8156 // broken.
8157 let labels = handles(&self.lanes);
8158 let mut per_lane: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
8159 for (li, data) in self.lanes.iter().enumerate() {
8160 let n = data
8161 .clips
8162 .iter()
8163 .filter(|c| c.link.is_some() && links.contains(&c.link))
8164 .count()
8165 + data
8166 .subs
8167 .iter()
8168 .filter(|s| s.link.is_some() && links.contains(&s.link))
8169 .count();
8170 if n > 0 {
8171 per_lane.insert(li, n as u32);
8172 }
8173 }
8174 // A pick that carries no link of its own is invisible to the scan
8175 // above (there is no `Some` to match): it still claims its lane.
8176 for &(lane, _) in picks {
8177 let li = self.index(lane).expect("checked above");
8178 per_lane.entry(li).or_insert(0);
8179 if !self.lanes[li]
8180 .clips
8181 .iter()
8182 .any(|c| c.link.is_some() && links.contains(&c.link))
8183 && !self.lanes[li]
8184 .subs
8185 .iter()
8186 .any(|s| s.link.is_some() && links.contains(&s.link))
8187 {
8188 *per_lane.get_mut(&li).expect("just inserted") += 1;
8189 }
8190 }
8191 if let Some((&li, _)) = per_lane.iter().find(|&(_, &n)| n > 1) {
8192 return Err(format!(
8193 "a group is one placement per lane: merging these groups would put two on {}",
8194 labels[li].label()
8195 )
8196 .into());
8197 }
8198 self.snapshot();
8199 let id = self.new_link();
8200 // Whatever any pick was grouped with comes along, for [`group`]'s
8201 // reason -- one id over the lot, not two groups sharing a member.
8202 for data in &mut self.lanes {
8203 for c in data.clips.iter_mut() {
8204 if c.link.is_some() && links.contains(&c.link) {
8205 c.link = Some(id);
8206 }
8207 }
8208 for s in data.subs.iter_mut() {
8209 if s.link.is_some() && links.contains(&s.link) {
8210 s.link = Some(id);
8211 }
8212 }
8213 }
8214 // And the picks themselves, which a `place` may have left in no group.
8215 // The lane seats are read before the walk, which holds the lanes.
8216 let seats: Vec<(usize, bool)> = picks
8217 .iter()
8218 .map(|&(lane, _)| {
8219 (
8220 self.index(lane).expect("checked above"),
8221 lane.kind == LaneKind::Subtitle,
8222 )
8223 })
8224 .collect();
8225 for (&(lane, idx), &(at, sub)) in picks.iter().zip(&seats) {
8226 let _ = lane;
8227 if sub {
8228 self.lanes[at].subs[idx].link = Some(id);
8229 } else {
8230 self.lanes[at].clips[idx].link = Some(id);
8231 }
8232 }
8233 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8234 Ok(())
8235 }
8236
8237 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
8238 /// lands on and leaving every other clip exactly where it is -- the
8239 /// per-lane paste. Anything already there is trimmed away (and split in two
8240 /// if `clip` lands inside it), which is what keeps the lane sorted and
8241 /// disjoint; nothing ripples, so a gap before the placement simply stays a
8242 /// gap. Refused only for an empty `clip`.
8243 ///
8244 /// The placement belongs to no group: a clipboard clip carries the link id
8245 /// of the take it was copied from, and placing it twice -- or placing a copy
8246 /// back over the clip it came from -- would put that id on two clips of one
8247 /// lane, which is what a link may never mean (see [`links_are_consistent`]).
8248 /// `None` rather than a fresh id because a one-lane placement has nothing on
8249 /// another lane to be grouped *with*; [`Project::regroup`] is how clips
8250 /// become a group again.
8251 ///
8252 /// Refused for an empty `clip`, for a lane that is not there, and for a
8253 /// subtitle lane, which carries no picture and no sound
8254 /// ([`Project::place_sub`] is its door).
8255 pub fn place(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8256 if clip.out_frame <= clip.in_frame
8257 || lane.kind == LaneKind::Subtitle
8258 || self.index(lane).is_none()
8259 || self.cycles(&clip)
8260 {
8261 return false;
8262 }
8263 self.snapshot();
8264 let clip = Clip {
8265 fade_in: 0,
8266 fade_out: 0,
8267 transition_out: 0,
8268 transition_kind: Default::default(),
8269 start: timeline_frame,
8270 link: None,
8271 ..clip
8272 };
8273 self.insert_over(lane, clip, &[]);
8274 true
8275 }
8276
8277 /// Place `clip` on `lane` **and its sound on that lane's own audio row** as
8278 /// one grouped take -- what a picture let go over a further video track
8279 /// means: `V2`'s picture plays on `V2` and its sound on `A2`, which is added
8280 /// if it is not there yet (the `+ V` button adds a video row alone). Without
8281 /// this half a file with sound landed on a layer silent, and the only way to
8282 /// hear it was to drop it a second time on an audio lane.
8283 ///
8284 /// Both halves overwrite what they land on and neither ripples, exactly as
8285 /// [`place`](Project::place) does -- a layer is laid *over* the timeline, so
8286 /// nothing under it moves. One history snapshot for the pair, the added lane
8287 /// included, so one [`Project::undo`] takes the whole placement back. The two
8288 /// carry one link, which is what makes them one take to a drag, a trim and a
8289 /// save.
8290 ///
8291 /// Refused, changing nothing, for an empty `clip` and for a lane that is not
8292 /// there or is not a video lane: sound placed alone is
8293 /// [`place`](Project::place)'s door, and a still has no sound to pair.
8294 pub fn place_take(&mut self, lane: Lane, timeline_frame: u32, clip: Clip) -> bool {
8295 if clip.out_frame <= clip.in_frame
8296 || lane.kind != LaneKind::Video
8297 || self.index(lane).is_none()
8298 || self.cycles(&clip)
8299 {
8300 return false;
8301 }
8302 self.snapshot();
8303 // `A2` for `V2` -- and the rows between it and the last audio lane, since
8304 // an ord names a lane only while every ord below it does.
8305 while self.lane_count(LaneKind::Audio) <= lane.ord {
8306 self.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
8307 }
8308 let clip = Clip {
8309 fade_in: 0,
8310 fade_out: 0,
8311 transition_out: 0,
8312 transition_kind: Default::default(),
8313 start: timeline_frame,
8314 link: Some(self.new_link()),
8315 ..clip
8316 };
8317 for half in [lane, Lane::new(LaneKind::Audio, lane.ord)] {
8318 self.insert_over(half, clip.clone(), &[]);
8319 }
8320 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8321 true
8322 }
8323
8324 /// A source range onto the timeline at `at`, the way an editor's
8325 /// three-point edit puts it: `items` are the `(lane, clip)` halves of one
8326 /// take (a picture on a video lane, its sound on an audio lane, or either
8327 /// alone), each landing with its head on `at` whatever `clip.start` says.
8328 ///
8329 /// * [`SourceEdit::Overwrite`] replaces what is there for the take's length:
8330 /// a clip it covers is trimmed or split around it, and nothing moves.
8331 /// * [`SourceEdit::Insert`] opens room first: on the lanes the items land
8332 /// on, a clip `at` falls inside is cut there and everything from `at` on
8333 /// moves later by the take's length. Lanes that are not item lanes do not
8334 /// move and are never cut -- so, as in a scoped ripple
8335 /// ([`Project::scope_holds_takes_whole`]), a take that would be pulled
8336 /// apart by it (one half on an item lane, the other not) refuses the
8337 /// insert by name. Captions keep their own clock, as a paste leaves them.
8338 ///
8339 /// The halves share one fresh link when there are several and run the same
8340 /// length; a lone half belongs to no group. Exactly one history snapshot,
8341 /// so one [`Project::undo`] takes the whole edit back. Changes the
8342 /// timeline->source mapping: the caller must reseek.
8343 ///
8344 /// Refused, changing nothing and costing no undo step, for no items, a lane
8345 /// that is not there, is locked or is a caption lane, a lane twice, a source
8346 /// that is not there or cannot play on the lane (a song on a video lane, a
8347 /// still on an audio one), an empty range, a start or ripple that would pass
8348 /// the last frame there is, and an insert inside a speeded clip at a frame
8349 /// its rate cannot cut.
8350 pub fn edit_from_source(&mut self, kind: SourceEdit, at: u32, items: &[(Lane, Clip)]) -> crate::Result<()> {
8351 if items.is_empty() {
8352 return Err("nothing to place".into());
8353 }
8354 let labels = handles(&self.lanes);
8355 let mut on: Vec<usize> = Vec::with_capacity(items.len());
8356 for (lane, clip) in items {
8357 let Some(i) = self.index(*lane) else {
8358 return Err(format!("no {} track on this timeline", lane.label()).into());
8359 };
8360 if lane.kind == LaneKind::Subtitle {
8361 return Err(format!("{} is a caption track: a source cannot go on it", labels[i].label()).into());
8362 }
8363 if on.contains(&i) {
8364 return Err(format!("{} is named twice", labels[i].label()).into());
8365 }
8366 if self.lanes[i].locked {
8367 return Err(format!("{} is locked: unlock it to edit it", labels[i].label()).into());
8368 }
8369 if is_sequence_source(clip.source) {
8370 return Err("a sequence is placed with the sequence ops, not as a source".into());
8371 }
8372 let Some(source) = self.sources.get(clip.source) else {
8373 return Err("that source is not in the project".into());
8374 };
8375 if clip.out_frame <= clip.in_frame {
8376 return Err("the range to place is empty".into());
8377 }
8378 if lane.kind == LaneKind::Video && crate::is_audio(&source.path) {
8379 return Err(format!("that source has no picture: it cannot go on {}", labels[i].label()).into());
8380 }
8381 if lane.kind == LaneKind::Audio && crate::is_image(&source.path) {
8382 return Err(format!("a still has no sound: it cannot go on {}", labels[i].label()).into());
8383 }
8384 on.push(i);
8385 }
8386 let len = items.iter().map(|(_, c)| c.frames()).max().unwrap_or(0);
8387 if len == 0 || at.checked_add(len).is_none() {
8388 return Err("the range to place is empty or runs past the last frame there is".into());
8389 }
8390 if kind == SourceEdit::Insert {
8391 for &i in &on {
8392 let clips = &self.lanes[i].clips;
8393 if clips.iter().any(|c| c.end() > at && c.end().checked_add(len).is_none()) {
8394 return Err("the insert would push a clip past the last frame there is".into());
8395 }
8396 if clips.iter().any(|c| c.start < at && at < c.end()) && splittable(clips, at).is_none() {
8397 return Err(format!(
8398 "{} cannot be cut at frame {at}: the clip there plays at a rate that has no source frame at it; pick a neighbouring frame",
8399 labels[i].label()
8400 )
8401 .into());
8402 }
8403 }
8404 self.scope_holds_takes_whole(&on, at)?;
8405 }
8406 self.snapshot();
8407 if kind == SourceEdit::Insert {
8408 self.write_split(at, false, &on);
8409 for &i in &on {
8410 for c in self.lanes[i].clips.iter_mut().filter(|c| c.start >= at) {
8411 c.start += len;
8412 }
8413 }
8414 }
8415 let link = (items.len() > 1 && items.iter().all(|(_, c)| c.frames() == len)).then(|| self.new_link());
8416 // A take the overwrite cuts through keeps its take, when every member of it sits on a lane
8417 // this edit writes: each member is then cut at the same frames, so the head keeps the id and
8418 // the tail takes one fresh id shared by them all. A take with a member on a lane left alone
8419 // would be cut out of step with it, so it is detached as a delete detaches it.
8420 let end = at + len;
8421 let mut straddled: Vec<u32> = Vec::new();
8422 for &i in &on {
8423 for c in &self.lanes[i].clips {
8424 if let Some(id) = c.link.filter(|_| c.start < end && c.end() > at)
8425 && !straddled.contains(&id)
8426 {
8427 straddled.push(id);
8428 }
8429 }
8430 }
8431 let mut keep: Vec<(u32, u32)> = Vec::new();
8432 for id in straddled {
8433 let whole = self
8434 .lanes
8435 .iter()
8436 .enumerate()
8437 .all(|(j, d)| on.contains(&j) || !d.clips.iter().any(|c| c.link == Some(id)));
8438 if whole {
8439 keep.push((id, self.new_link()));
8440 }
8441 }
8442 for (lane, clip) in items {
8443 let clip = Clip {
8444 fade_in: 0,
8445 fade_out: 0,
8446 transition_out: 0,
8447 transition_kind: Default::default(),
8448 start: at,
8449 link,
8450 ..clip.clone()
8451 };
8452 self.insert_over(*lane, clip, &keep);
8453 }
8454 debug_assert!(links_are_consistent(&self.lanes).is_ok());
8455 Ok(())
8456 }
8457
8458 /// `clip` into `lane` at its own start, over whatever it lands on: the
8459 /// insert both placement doors make, which is what keeps a lane sorted and
8460 /// disjoint. The caller has checked that the lane is there.
8461 fn insert_over(&mut self, lane: Lane, clip: Clip, keep: &[(u32, u32)]) {
8462 let clips = self.lane_mut(lane).expect("the caller checked the lane");
8463 // The pieces a cut leaves keep their take where `keep` says so (see `edit_from_source`);
8464 // everywhere else a straddled clip's pieces are detached.
8465 clear_with(clips, clip.start, clip.end(), &mut |link| match link.and_then(|id| keep.iter().find(|k| k.0 == id)) {
8466 Some(&(head, tail)) => (Some(head), Some(tail)),
8467 None => (None, None),
8468 });
8469 let idx = clips.partition_point(|c| c.start < clip.start);
8470 clips.insert(idx, clip);
8471 debug_assert!(sorted_disjoint(clips));
8472 }
8473
8474 /// Move the clip at `idx` of `from` onto `to` with its head at timeline
8475 /// frame `start`: the drag that rearranges takes, along a track and across
8476 /// them alike. One snapshot, so one [`Project::undo`] puts it back where it
8477 /// was. `start` at the clip's own is the pure lane change.
8478 ///
8479 /// The whole group travels the same distance, each half on the lane it
8480 /// already sits on -- a link means "these cover one span on however many
8481 /// lanes" ([`links_are_consistent`]), so a picture that slid away from its
8482 /// sound would be a group no save could load. Only the dragged half changes
8483 /// lane, and that is not a desync: a link names no lane at all.
8484 ///
8485 /// `start` is **clamped**, never refused, to the room the group has: no
8486 /// member crosses a neighbour on the lane it lands on, exactly as
8487 /// [`trim`](Project::trim) stops an edge at the clip in front of it. A hand
8488 /// dragging past a neighbour means "as far as it goes", and butting up
8489 /// against the take next door is how clips are laid end to end. The
8490 /// tightest member's wall wins, so a sound half boxed in between two others
8491 /// holds its picture still.
8492 ///
8493 /// Refused, changing nothing and costing no undo step, for a lane that is
8494 /// not there, an index that is not there, a move across *kinds* (a picture
8495 /// cannot play on an audio lane, and the save it wrote would not open
8496 /// again), a head let go *inside* another clip or into a gap too narrow to
8497 /// hold this one -- a move that overwrote what it landed on would destroy a
8498 /// take the pointer never named, which is what [`place`](Project::place)
8499 /// may do and a drag may not -- a half let go onto the lane its own partner
8500 /// is on, and a drop that changes neither lane nor frame, which is a clip
8501 /// picked up and put back down, i.e. a click.
8502 pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
8503 self.move_selection(&[(from, idx)], from, idx, to, start)
8504 }
8505
8506 /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks`
8507 /// (each with its own link group, exactly as [`group_of`](Self::group_of)
8508 /// reads it) travels the same distance as the clip at `idx` of `from`,
8509 /// which alone changes lane, onto `to`. One clamp across the whole set
8510 /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a
8511 /// neighbour that boxes in *any* member narrows the delta every member
8512 /// moves by, and a member with no room at all (`lo > hi`) refuses the
8513 /// whole set rather than moving the rest and leaving that one behind.
8514 /// `move_clip` is this with a selection of one -- the dragged clip's own
8515 /// group and nothing else -- so a drag on a clip outside the selection is
8516 /// byte-identical to before this existed.
8517 pub fn move_selection(
8518 &mut self,
8519 picks: &[(Lane, usize)],
8520 from: Lane,
8521 idx: usize,
8522 to: Lane,
8523 start: u32,
8524 ) -> bool {
8525 let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).cloned()) else {
8526 return false;
8527 };
8528 if from.kind != to.kind {
8529 return false;
8530 }
8531 let held = self.index(from).expect("the clip was found on it");
8532 // Every pick's own group, unioned: the whole selection moves as one,
8533 // and a pick's link partners (not themselves picked) come along with
8534 // it exactly as a lone drag's do.
8535 let mut members = Members::default();
8536 for &(lane, i) in picks {
8537 let Some(group) = self.group_of(lane, i) else {
8538 continue;
8539 };
8540 for m in group.clips {
8541 if !members.clips.contains(&m) {
8542 members.clips.push(m);
8543 }
8544 }
8545 for m in group.subs {
8546 if !members.subs.contains(&m) {
8547 members.subs.push(m);
8548 }
8549 }
8550 }
8551 if !members.clips.contains(&(held, idx)) {
8552 members.clips.push((held, idx));
8553 }
8554 // The two halves of *the dragged clip's own* group would land on one
8555 // span of one lane, which is the one thing a link may never mean --
8556 // checked against that group alone, not the whole moving set: an
8557 // unlinked fellow pick already sitting on `dest` is no conflict at
8558 // all, since it travels by the same delta and `move_room` below
8559 // leaves it the room to. Refused rather than clamped: the partner
8560 // moves the same distance, so there is no room for it anywhere on
8561 // that lane.
8562 let own_group = self.group_of(from, idx).expect("the clip was found");
8563 if dest != held
8564 && own_group
8565 .clips
8566 .iter()
8567 .chain(&own_group.subs)
8568 .any(|&(l, _)| l == dest)
8569 {
8570 return false;
8571 }
8572 let want = i64::from(start) - i64::from(clip.start);
8573 // First the placement as asked: every member's span shifted by the one
8574 // delta the pointer named, each read against the gap it would land in.
8575 // A drop on empty frames lands exactly there -- jumping over whatever
8576 // clips lie between, on its lane and its linked partners' -- and only
8577 // a member whose new span would meet another clip refuses it.
8578 let as_asked = self
8579 .move_room(&members, Some((held, idx, dest, start)), Some(want))
8580 .filter(|&(lo, hi)| lo <= want && want <= hi);
8581 // Otherwise the drag as it always was: how far the group may travel,
8582 // in timeline frames and signed, with every member narrowing it to the
8583 // gap it stands in (its own lane, or the lane the pointer let it go
8584 // over), and what is left is what the pointer is clamped to.
8585 let Some((lo, hi)) = as_asked.or_else(|| {
8586 self.move_room(&members, Some((held, idx, dest, start)), None)
8587 }) else {
8588 return false;
8589 };
8590 if lo > hi {
8591 return false;
8592 }
8593 let delta = want.clamp(lo, hi);
8594 if delta == 0 && dest == held {
8595 return false;
8596 }
8597 self.snapshot();
8598 for &(l, i) in &members.clips {
8599 let c = &mut self.lanes[l].clips[i];
8600 // In range by the walls above, which are `u32` frames throughout.
8601 c.start = (i64::from(c.start) + delta) as u32;
8602 }
8603 for &(l, i) in &members.subs {
8604 let s = &mut self.lanes[l].subs[i];
8605 s.start = (i64::from(s.start) + delta) as u32;
8606 }
8607 if dest != held {
8608 let clip = self.lanes[held].clips.remove(idx);
8609 let clips = &mut self.lanes[dest].clips;
8610 let at = clips.partition_point(|c| c.start < clip.start);
8611 clips.insert(at, clip);
8612 }
8613 // A jump can carry a member past clips it did not pass before, on its
8614 // own lane as much as onto another, so every lane the set touched is
8615 // put back in order. The members keep their spacing among themselves
8616 // (one delta), so the order is all that can have changed.
8617 let mut touched: Vec<usize> = members
8618 .clips
8619 .iter()
8620 .chain(&members.subs)
8621 .map(|&(l, _)| l)
8622 .chain([dest])
8623 .collect();
8624 touched.sort_unstable();
8625 touched.dedup();
8626 for l in touched {
8627 self.lanes[l].clips.sort_by_key(|c| c.start);
8628 self.lanes[l].subs.sort_by_key(|s| s.start);
8629 }
8630 debug_assert!(sorted_disjoint(&self.lanes[dest].clips));
8631 debug_assert!(members.clips.iter().chain(&members.subs).all(|&(l, _)| {
8632 sorted_disjoint(&self.lanes[l].clips) && subs_sorted_disjoint(&self.lanes[l].subs)
8633 }));
8634 true
8635 }
8636
8637 /// How far a group drag may travel, `(least, most)` in timeline frames and
8638 /// signed: every member narrows the range to the gap it is landing in --
8639 /// the clips against their lanes' clips and the captions against their
8640 /// lanes' captions -- and what is left is what the pointer is clamped to.
8641 /// `travelling` names the one member that changes lane, if any: the clip a
8642 /// hand is carrying onto another track, whose walls are read on the lane it
8643 /// is let go over at the frame the pointer named. `None` when a member has
8644 /// no gap to land in at all.
8645 ///
8646 /// `requested`, when given, reads every member's walls where it would sit
8647 /// with the whole group shifted by that many frames, rather than where it
8648 /// stands; a member whose requested spot is inside another placement, or
8649 /// has no gap wide enough, is `None`.
8650 fn move_room(
8651 &self,
8652 members: &Members,
8653 travelling: Option<(usize, usize, usize, u32)>,
8654 requested: Option<i64>,
8655 ) -> Option<(i64, i64)> {
8656 let (mut lo, mut hi) = (i64::MIN, i64::MAX);
8657 for &(l, i) in members.clips.iter().chain(&members.subs) {
8658 let sub = members.subs.contains(&(l, i));
8659 let (start, frames) = match self.lanes[l]
8660 .clips
8661 .get(i)
8662 .filter(|_| !sub)
8663 .map(|c| (c.start, c.frames()))
8664 {
8665 Some(pair) => pair,
8666 None => {
8667 let s = self.lanes[l].subs.get(i)?;
8668 (s.start, s.frames)
8669 }
8670 };
8671 let land = travelling
8672 .filter(|&(fl, fi, ..)| (fl, fi) == (l, i))
8673 .map_or(l, |(_, _, dest, _)| dest);
8674 // Which gap this member's walls are read off: its own place on the
8675 // lane it stays on, and the frame the pointer named on the lane it
8676 // is let go over. A clip's neighbours are the clips of the lane it
8677 // lands on and a caption's are its captions -- the two lists of one
8678 // lane never meet.
8679 let at = match (requested, travelling) {
8680 (Some(shift), _) => match u32::try_from(i64::from(start) + shift) {
8681 Ok(at) => at,
8682 Err(_) => return None,
8683 },
8684 (None, Some((fl, fi, _, asked))) if (fl, fi) == (l, i) && land != l => asked,
8685 (None, _) => start,
8686 };
8687 let (mut wall_lo, mut wall_hi) = (0, u32::MAX);
8688 let neighbours: Vec<(u32, u32)> = if sub {
8689 self.lanes[land]
8690 .subs
8691 .iter()
8692 .map(|s| (s.start, s.end()))
8693 .collect()
8694 } else {
8695 self.lanes[land]
8696 .clips
8697 .iter()
8698 .map(|c| (c.start, c.end()))
8699 .collect()
8700 };
8701 for (j, (other_start, other_end)) in neighbours.iter().enumerate() {
8702 if members.clips.contains(&(land, j)) || members.subs.contains(&(land, j)) {
8703 continue;
8704 }
8705 if *other_start <= at && at < *other_end {
8706 // A head let go inside another placement, which a clamp
8707 // has no answer for: the drop is refused.
8708 return None;
8709 }
8710 match other_end <= &at {
8711 true => wall_lo = wall_lo.max(*other_end),
8712 false => wall_hi = wall_hi.min(*other_start),
8713 }
8714 }
8715 if wall_hi - wall_lo < frames {
8716 return None;
8717 }
8718 lo = lo.max(i64::from(wall_lo) - i64::from(start));
8719 hi = hi.min(i64::from(wall_hi - frames) - i64::from(start));
8720 }
8721 Some((lo, hi))
8722 }
8723
8724 /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
8725 /// the drag on a clip's end that makes it play more or less of its source.
8726 /// The rest of the lane stays exactly where it is (nothing ripples), so what
8727 /// a shortened clip leaves behind is a gap and what a lengthened one takes
8728 /// is room that was already empty. One snapshot, so a whole drag is one
8729 /// [`Project::undo`] -- commit once, at the release, rather than per pointer
8730 /// sample. Changes the timeline->source mapping: the caller must reseek.
8731 ///
8732 /// [`Edge::Start`] moves the in-point with it: the frames that stay play
8733 /// exactly what they played before, which is what makes this a trim and not
8734 /// a slip.
8735 ///
8736 /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
8737 /// legal means "as far as it goes", and stopping the box there is the
8738 /// affordance. The walls are: one frame of clip always survives, an edge
8739 /// never crosses the neighbouring clip on its own lane, an in-point never
8740 /// walks back past the source's first frame, and an out-point never runs
8741 /// past `source_frames[clip.source]` -- the caller's table of how long each
8742 /// source actually is ([`Project`] does not know, and a clip ending past its
8743 /// file's last frame is a save that will not open again; see
8744 /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
8745 /// there may not grow at all.
8746 ///
8747 /// Linked placements trim *together*, by one delta: every member's same
8748 /// edge moves the distance the dragged one did, clamped to the room its
8749 /// own walls leave -- offsets between the members of a hand-built group
8750 /// survive the trim, exactly as they survive a drag.
8751 ///
8752 /// `false`, changing nothing and costing no undo step, for an index that is
8753 /// not there and for an edge that is already where it was asked to go.
8754 pub fn trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8755 self.trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8756 }
8757
8758 /// [`trim`](Project::trim) measured against each lane's own table
8759 /// ([`SourceWalls`]): what a linked take needs, since its audio and picture
8760 /// members end on different frames.
8761 pub fn trim_with_walls(
8762 &mut self,
8763 lane: Lane,
8764 idx: usize,
8765 edge: Edge,
8766 to: u32,
8767 walls: SourceWalls<'_>,
8768 ) -> bool {
8769 let (Some((lo, hi)), Some(clip)) = (
8770 self.trim_room_with_walls(lane, idx, edge, walls),
8771 self.lane(lane).get(idx).cloned(),
8772 ) else {
8773 return false;
8774 };
8775 let to = to.clamp(lo, hi);
8776 let at = match edge {
8777 Edge::Start => clip.start,
8778 Edge::End => clip.end(),
8779 };
8780 if to == at {
8781 return false;
8782 }
8783 // Worked out before anything moves: at a slow rate a room can be too
8784 // narrow to hold even one source frame ([`Speed::fit`]), and the
8785 // dragged clip refusing to fit must refuse the whole gesture rather
8786 // than be given a range wider than its room -- which is the overlap
8787 // the lane invariant exists to forbid. The walls below leave that room,
8788 // so this is the backstop for a project that came in through another
8789 // door.
8790 // A ramp's head is not moved yet: its keys are measured from the clip's own
8791 // start, so a head trim would have to rebase them. Refused, as a split is.
8792 if matches!(edge, Edge::Start) && !clip.speed_keys.is_empty() {
8793 return false;
8794 }
8795 let room = match edge {
8796 // The frames that stay play what they played, so what survives is
8797 // measured from the *end*.
8798 Edge::Start => clip.end() - to,
8799 Edge::End => to - clip.start,
8800 };
8801 let Some(keep) = clip.fit_source(room) else {
8802 return false;
8803 };
8804 // An end edge never keeps more source than the source has past the
8805 // in-point: [`Speed::fit`] rounds by the same footprint the wall does, so
8806 // at a fast rate it can name one frame past the source's end, one the wall
8807 // (`clip_walls`) never offers. Held to the wall, the edit it commits is
8808 // the edit a save will accept.
8809 let keep = keep.min(keep_cap(&clip, edge, walls.for_kind(lane.kind)));
8810 let members = self.group_of(lane, idx).expect("checked above");
8811 self.snapshot();
8812 let still = self.is_still(&clip);
8813 let held = self.index(lane).expect("checked above");
8814 write_trim(&mut self.lanes[held].clips[idx], edge, to, keep, still);
8815 rekey_trimmed(&mut self.lanes[held].clips[idx], &clip, edge, still);
8816 debug_assert!(sorted_disjoint(&self.lanes[held].clips));
8817 self.follow_group(
8818 &members,
8819 &(held, idx),
8820 edge,
8821 i64::from(to) - i64::from(at),
8822 walls,
8823 );
8824 true
8825 }
8826
8827 /// **Ripple trim**: [`trim`](Project::trim), except that the hole the trim leaves is closed
8828 /// (or opened) and what comes after moves with the edge, as Premiere's ripple trim does. A
8829 /// start edge keeps the clip where it began and cuts its head out, so the clips behind it
8830 /// move up by as much; an end edge moves what follows by the length it gained or lost. A
8831 /// linked member moves the same way on its own lane. The room an end edge may grow into is
8832 /// still the room its neighbour leaves, as a plain trim's is. One undo step.
8833 pub fn ripple_trim(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, source_frames: &[u32]) -> bool {
8834 self.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls::same(source_frames))
8835 }
8836
8837 /// [`ripple_trim`](Project::ripple_trim) measured against each lane's own table
8838 /// ([`SourceWalls`]), as [`trim_with_walls`](Project::trim_with_walls) is.
8839 pub fn ripple_trim_with_walls(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32, walls: SourceWalls<'_>) -> bool {
8840 let Some(members) = self.group_of(lane, idx) else {
8841 return false;
8842 };
8843 let before: Vec<(usize, usize, u32, u32)> = members
8844 .clips
8845 .iter()
8846 .filter_map(|&(l, i)| self.lanes[l].clips.get(i).map(|c| (l, i, c.start, c.end())))
8847 .collect();
8848 if !self.trim_with_walls(lane, idx, edge, to, walls) {
8849 return false;
8850 }
8851 for (l, i, old_start, old_end) in before {
8852 let clip = &self.lanes[l].clips[i];
8853 let (new_start, new_end) = (clip.start, clip.end());
8854 match edge {
8855 Edge::Start => {
8856 // The head went (or came back): the clip starts where it did, and the
8857 // hole between it and what it was cut from closes behind it.
8858 let g = i64::from(new_start) - i64::from(old_start);
8859 if g != 0 {
8860 shift_behind(&mut self.lanes[l], old_end, -g);
8861 self.lanes[l].clips[i].start = old_start;
8862 }
8863 }
8864 Edge::End => {
8865 let g = i64::from(new_end) - i64::from(old_end);
8866 if g != 0 {
8867 shift_behind(&mut self.lanes[l], old_end, g);
8868 }
8869 }
8870 }
8871 }
8872 true
8873 }
8874
8875 /// The rest of a group after one member's `edge` has moved by `delta`:
8876 /// every other member's same edge moves the same distance, clamped to the
8877 /// room its own walls leave -- a clip's against its lane and its source,
8878 /// a caption's against its own lane, its window following by the
8879 /// placement's own proportion. The undo step is the caller's: this is the
8880 // second half of one edit, not an edit of its own.
8881 fn follow_group(
8882 &mut self,
8883 members: &Members,
8884 dragged: &(usize, usize),
8885 edge: Edge,
8886 delta: i64,
8887 walls: SourceWalls<'_>,
8888 ) {
8889 for &(l, i) in &members.clips {
8890 if (l, i) == *dragged {
8891 continue;
8892 }
8893 let old = self.lanes[l].clips[i].clone();
8894 let c = &old;
8895 let at = match edge {
8896 Edge::Start => c.start,
8897 Edge::End => c.end(),
8898 };
8899 let (lo, hi) = self.clip_room(l, i, edge, walls);
8900 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
8901 if to == at {
8902 continue;
8903 }
8904 let room = match edge {
8905 Edge::Start => c.end() - to,
8906 Edge::End => to - c.start,
8907 };
8908 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
8909 continue;
8910 }
8911 let Some(keep) = c.fit_source(room) else {
8912 continue;
8913 };
8914 // Held to the member's own source, as the dragged clip is.
8915 let keep = keep.min(keep_cap(c, edge, walls.for_kind(self.lanes[l].kind)));
8916 let still = self.is_still(&self.lanes[l].clips[i]);
8917 write_trim(&mut self.lanes[l].clips[i], edge, to, keep, still);
8918 rekey_trimmed(&mut self.lanes[l].clips[i], &old, edge, still);
8919 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
8920 }
8921 for &(l, i) in &members.subs {
8922 if (l, i) == *dragged {
8923 continue;
8924 }
8925 let s = self.lanes[l].subs[i];
8926 let at = match edge {
8927 Edge::Start => s.start,
8928 Edge::End => s.end(),
8929 };
8930 let (lo, hi) = sub_edge_room(&self.lanes[l].subs, i, edge);
8931 let to = (i64::from(at) + delta).clamp(i64::from(lo), i64::from(hi)) as u32;
8932 if to == at {
8933 continue;
8934 }
8935 write_sub_edge(&mut self.lanes[l].subs[i], edge, to);
8936 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
8937 }
8938 }
8939
8940 /// How far that edge may travel, `(first, last)` timeline frame inclusive --
8941 /// the walls [`trim`](Project::trim) clamps to, without moving anything.
8942 /// What a front-end drawing the box *during* a drag asks, so the live width
8943 /// is the width the release will commit and an edge stops under the pointer
8944 /// rather than snapping back. The **clip's own** walls: the rest of its
8945 /// group follows by the same delta within their own ([`follow_group`]), so
8946 /// what is drawn for the dragged edge is what its own clip will commit.
8947 /// `None` for an index that is not there.
8948 pub fn trim_room(
8949 &self,
8950 lane: Lane,
8951 idx: usize,
8952 edge: Edge,
8953 source_frames: &[u32],
8954 ) -> Option<(u32, u32)> {
8955 self.trim_room_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
8956 }
8957
8958 /// [`trim_room`](Project::trim_room) against each lane's own table.
8959 pub fn trim_room_with_walls(
8960 &self,
8961 lane: Lane,
8962 idx: usize,
8963 edge: Edge,
8964 walls: SourceWalls<'_>,
8965 ) -> Option<(u32, u32)> {
8966 let l = self.index(lane)?;
8967 (idx < self.lanes[l].clips.len()).then(|| self.clip_room(l, idx, edge, walls))
8968 }
8969
8970 /// [`trim_room`](Project::trim_room) with the same two walls, and for each
8971 /// one whether it is the source's media limit (head for a start edge, tail
8972 /// for an end edge) rather than a neighbouring clip. Stills never report
8973 /// media. `None` for an index that is not there.
8974 pub fn trim_walls(
8975 &self,
8976 lane: Lane,
8977 idx: usize,
8978 edge: Edge,
8979 source_frames: &[u32],
8980 ) -> Option<TrimWalls> {
8981 self.trim_walls_with_walls(lane, idx, edge, SourceWalls::same(source_frames))
8982 }
8983
8984 /// [`trim_walls`](Project::trim_walls) against each lane's own table.
8985 pub fn trim_walls_with_walls(
8986 &self,
8987 lane: Lane,
8988 idx: usize,
8989 edge: Edge,
8990 walls: SourceWalls<'_>,
8991 ) -> Option<TrimWalls> {
8992 let l = self.index(lane)?;
8993 (idx < self.lanes[l].clips.len()).then(|| self.clip_walls(l, idx, edge, walls).0)
8994 }
8995
8996 /// [`trim_walls`](Project::trim_walls) with each wall's bound named: what
8997 /// sets the low wall and what the high one, as a [`WallBound`]. The same
8998 /// walls, so a trim to one of them lands on the bound named for it. Asked
8999 /// before the trim: a clip committed at a wall sits on it, and the name is
9000 /// the one for the place it was asked to go. `None` for a bad index.
9001 pub fn trim_bounds(
9002 &self,
9003 lane: Lane,
9004 idx: usize,
9005 edge: Edge,
9006 walls: SourceWalls<'_>,
9007 ) -> Option<(WallBound, WallBound)> {
9008 let l = self.index(lane)?;
9009 (idx < self.lanes[l].clips.len()).then(|| {
9010 let (_, lo, hi) = self.clip_walls(l, idx, edge, walls);
9011 (lo, hi)
9012 })
9013 }
9014
9015 // ---- roll, slip, slide ------------------------------------------------
9016 //
9017 // The three trims that move *two* things at once, so no single-edge
9018 // [`trim`](Project::trim) can do them: the pair of edges at a cut, the
9019 // window a clip reads, the clip between its neighbours. Each is one undo
9020 // step, carries the clip's linked take along by the same delta, and is
9021 // measured against the same source tables a trim is. The engine ignores
9022 // locks, as everywhere: the front-end refuses first.
9023 //
9024 // Each plans the whole edit on clones and commits only a plan every member
9025 // can take *exactly*: at a rate that does not divide the frame grid a
9026 // timeline length can be unreachable for a source range ([`Speed::fit`]),
9027 // and an edit that lands one frame off would open a gap or an overlap and
9028 // move the timeline's length. The delta therefore backs off toward zero
9029 // until the plan is exact; a delta of zero is "no change" and costs no step.
9030
9031 /// `c` with its `edge` at timeline frame `to`, as [`trim`](Project::trim)
9032 /// would leave it, ignoring the neighbours (the caller owns them). `None`
9033 /// where a trim would refuse: a ramped head, no room for a source frame.
9034 fn edge_moved(&self, c: &Clip, edge: Edge, to: u32, table: &[u32]) -> Option<Clip> {
9035 if matches!(edge, Edge::Start) && !c.speed_keys.is_empty() {
9036 return None;
9037 }
9038 let still = self.is_still(c);
9039 let room = match edge {
9040 Edge::Start => c.end().checked_sub(to)?,
9041 Edge::End => to.checked_sub(c.start)?,
9042 };
9043 let keep = c.fit_source(room)?;
9044 let mut n = c.clone();
9045 match edge {
9046 Edge::End => n.out_frame = c.in_frame + keep.min(source_left(c, table)),
9047 Edge::Start if still => {
9048 n.in_frame = 0;
9049 n.out_frame = keep.min(table.get(c.source).copied().unwrap_or(c.len())).max(1);
9050 n.start = to;
9051 }
9052 Edge::Start => {
9053 n.in_frame = c.out_frame - keep.min(c.out_frame);
9054 n.start = to;
9055 }
9056 }
9057 rekey_trimmed(&mut n, c, edge, still);
9058 Some(n)
9059 }
9060
9061 /// The lane slot and index of every cut a roll at `(lane, idx)` moves: the
9062 /// clip before the cut first, then the same cut of each other member of its
9063 /// take that has a clip abutting behind it. `None` when `idx` has no clip
9064 /// abutting behind it.
9065 fn roll_pairs(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9066 let l = self.index(lane)?;
9067 let abuts = |l: usize, i: usize| {
9068 let clips = &self.lanes[l].clips;
9069 matches!((clips.get(i), clips.get(i + 1)), (Some(a), Some(b)) if a.end() == b.start)
9070 };
9071 if lane.kind == LaneKind::Subtitle || !abuts(l, idx) {
9072 return None;
9073 }
9074 let members = self.group_of(lane, idx)?;
9075 let mut out = vec![(l, idx)];
9076 out.extend(members.clips.into_iter().filter(|&(ml, mi)| (ml, mi) != (l, idx) && abuts(ml, mi)));
9077 Some(out)
9078 }
9079
9080 /// How far the cut after `(l, i)` may travel on its media alone, as the
9081 /// delta range `(back, forward)` around where it is: the clip before it can
9082 /// play on to the end of its source, the one behind it back to the start of
9083 /// its own, and each keeps a frame.
9084 fn roll_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9085 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9086 let t = walls.for_kind(self.lanes[l].kind);
9087 let cut = i64::from(a.end());
9088 if !b.speed_keys.is_empty() {
9089 return (0, 0);
9090 }
9091 let tail = i64::from(a.start)
9092 + i64::from(footprint(a, t.get(a.source).copied().unwrap_or(a.out_frame).saturating_sub(a.in_frame)));
9093 let head = if self.is_still(b) {
9094 i64::from(b.end()) - i64::from(b.speed.room(t.get(b.source).copied().unwrap_or(b.len())))
9095 } else {
9096 i64::from(b.start) - i64::from(footprint(b, b.in_frame))
9097 };
9098 let lo = head.max(0).max(i64::from(a.start) + i64::from(footprint(a, 1)));
9099 let hi = tail.min(i64::from(b.end()) - i64::from(footprint(b, 1)));
9100 ((lo - cut).min(0), (hi - cut).max(0))
9101 }
9102
9103 /// The two clips of the cut after `(l, i)` once it sits at `to`, or `None`
9104 /// when either cannot take it *exactly* (see the section note).
9105 fn rolled(&self, l: usize, i: usize, to: u32, walls: SourceWalls<'_>) -> Option<(Clip, Clip)> {
9106 let (a, b) = (&self.lanes[l].clips[i], &self.lanes[l].clips[i + 1]);
9107 let t = walls.for_kind(self.lanes[l].kind);
9108 let na = self.edge_moved(a, Edge::End, to, t)?;
9109 let nb = self.edge_moved(b, Edge::Start, to, t)?;
9110 (na.end() == to && nb.start == to && nb.end() == b.end()).then_some((na, nb))
9111 }
9112
9113 /// Where the cut at the end of the clip at `idx` of `lane` may travel,
9114 /// `(first, last)` timeline frame inclusive: the walls [`roll`](Project::roll)
9115 /// clamps to -- the media of both clips of every member of the take, and a
9116 /// frame of each. `None` for a clip with nothing abutting behind it.
9117 pub fn roll_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9118 let pairs = self.roll_pairs(lane, idx)?;
9119 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9120 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9121 Some(((cut + back) as u32, (cut + fwd) as u32))
9122 }
9123
9124 fn roll_delta_span(&self, pairs: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9125 pairs.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9126 let (b, f) = self.roll_span(l, i, walls);
9127 (back.max(b), fwd.min(f))
9128 })
9129 }
9130
9131 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to
9132 /// timeline frame `to`. The out-point of that clip and the in-point of the
9133 /// clip abutting behind it move together, so the pair keeps its joint span
9134 /// and nothing else on the lane moves: the timeline's length does not
9135 /// change. The frames that stay play what they played.
9136 ///
9137 /// Like [`trim`](Project::trim), `to` is clamped to the walls
9138 /// ([`roll_room`](Project::roll_room)), never refused. The rest of the take
9139 /// rolls its own cut by the same delta -- the ones that have a cut there --
9140 /// and the whole take is held to the tightest member. At a rate where the
9141 /// exact frame is unreachable the cut stops on the nearest one that is.
9142 ///
9143 /// `Some(cut)`: where the cut is now (the old place when nothing moved, at
9144 /// no cost in undo steps; one step otherwise). `None`, changing nothing:
9145 /// no clip there, or none abutting behind it -- a roll needs a cut. A
9146 /// speed-ramped clip behind the cut cannot take a new in-point (as a trim
9147 /// refuses a ramped head), which pins the cut.
9148 pub fn roll(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9149 let pairs = self.roll_pairs(lane, idx)?;
9150 let cut = i64::from(self.lanes[pairs[0].0].clips[pairs[0].1].end());
9151 let (back, fwd) = self.roll_delta_span(&pairs, walls);
9152 let mut d = (i64::from(to) - cut).clamp(back, fwd);
9153 let plan = loop {
9154 if d == 0 {
9155 return Some(cut as u32);
9156 }
9157 let plan: Option<Vec<_>> = pairs
9158 .iter()
9159 .map(|&(l, i)| {
9160 let at = i64::from(self.lanes[l].clips[i].end()) + d;
9161 let at = u32::try_from(at).ok()?;
9162 self.rolled(l, i, at, walls).map(|p| (l, i, p))
9163 })
9164 .collect();
9165 if let Some(plan) = plan {
9166 break plan;
9167 }
9168 d -= d.signum();
9169 };
9170 self.snapshot();
9171 for (l, i, (a, b)) in plan {
9172 self.lanes[l].clips[i] = a;
9173 self.lanes[l].clips[i + 1] = b;
9174 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9175 }
9176 Some((cut + d) as u32)
9177 }
9178
9179 /// The clips a slide at `(lane, idx)` moves, as lane slot and index: the
9180 /// clip itself first, then the rest of its take. `None` unless every one of
9181 /// them has a clip on both sides -- sliding needs neighbours to give to.
9182 fn slide_members(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
9183 let l = self.index(lane)?;
9184 if lane.kind == LaneKind::Subtitle || self.lanes[l].clips.get(idx).is_none() {
9185 return None;
9186 }
9187 let members = self.group_of(lane, idx)?;
9188 let mut out = vec![(l, idx)];
9189 out.extend(members.clips.into_iter().filter(|&m| m != (l, idx)));
9190 out.iter()
9191 .all(|&(ml, mi)| mi > 0 && mi + 1 < self.lanes[ml].clips.len())
9192 .then_some(out)
9193 }
9194
9195 /// How far the clip at `(l, i)` may slide on its neighbours' media alone, as
9196 /// the delta range `(back, forward)`. A neighbour it abuts gives or takes
9197 /// frames at its cut, up to its own media and a frame of itself; a
9198 /// neighbour across a gap only bounds the move where it begins.
9199 fn slide_span(&self, l: usize, i: usize, walls: SourceWalls<'_>) -> (i64, i64) {
9200 let clips = &self.lanes[l].clips;
9201 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9202 let t = walls.for_kind(self.lanes[l].kind);
9203 let (start, end) = (i64::from(c.start), i64::from(c.end()));
9204 let (mut back, mut fwd) = (i64::MIN, i64::MAX);
9205 if p.end() == c.start {
9206 let tail = i64::from(p.start)
9207 + i64::from(footprint(p, t.get(p.source).copied().unwrap_or(p.out_frame).saturating_sub(p.in_frame)));
9208 back = back.max(i64::from(p.start) + i64::from(footprint(p, 1)) - start);
9209 fwd = fwd.min(tail - start);
9210 } else {
9211 back = back.max(i64::from(p.end()) - start);
9212 }
9213 if n.start == c.end() {
9214 if n.speed_keys.is_empty() {
9215 let head = if self.is_still(n) {
9216 i64::from(n.end()) - i64::from(n.speed.room(t.get(n.source).copied().unwrap_or(n.len())))
9217 } else {
9218 i64::from(n.start) - i64::from(footprint(n, n.in_frame))
9219 };
9220 back = back.max(head - end);
9221 fwd = fwd.min(i64::from(n.end()) - i64::from(footprint(n, 1)) - end);
9222 } else {
9223 back = back.max(0);
9224 fwd = fwd.min(0);
9225 }
9226 } else {
9227 fwd = fwd.min(i64::from(n.start) - end);
9228 }
9229 (back.min(0), fwd.max(0))
9230 }
9231
9232 /// The three clips of the slide at `(l, i)` once the middle one starts
9233 /// `d` frames later: the previous clip and the next one `None` when a gap
9234 /// (not a cut) lies on that side and so nothing there changes.
9235 fn slid(&self, l: usize, i: usize, d: i64, walls: SourceWalls<'_>) -> Option<(Option<Clip>, Clip, Option<Clip>)> {
9236 let clips = &self.lanes[l].clips;
9237 let (p, c, n) = (&clips[i - 1], &clips[i], &clips[i + 1]);
9238 let t = walls.for_kind(self.lanes[l].kind);
9239 let start = u32::try_from(i64::from(c.start) + d).ok()?;
9240 let end = start.checked_add(c.frames())?;
9241 let np = if p.end() == c.start {
9242 let np = self.edge_moved(p, Edge::End, start, t)?;
9243 (np.end() == start).then_some(())?;
9244 Some(np)
9245 } else {
9246 (start >= p.end()).then_some(())?;
9247 None
9248 };
9249 let nn = if n.start == c.end() {
9250 let nn = self.edge_moved(n, Edge::Start, end, t)?;
9251 (nn.start == end && nn.end() == n.end()).then_some(())?;
9252 Some(nn)
9253 } else {
9254 (end <= n.start).then_some(())?;
9255 None
9256 };
9257 Some((np, Clip { start, ..c.clone() }, nn))
9258 }
9259
9260 /// Where the clip at `idx` of `lane` may start when slid, `(first, last)`
9261 /// timeline frame inclusive: the walls [`slide`](Project::slide) clamps to.
9262 /// `None` for a clip that lacks a neighbour on either side (or any member
9263 /// of its take does).
9264 pub fn slide_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(u32, u32)> {
9265 let members = self.slide_members(lane, idx)?;
9266 let (back, fwd) = self.slide_delta_span(&members, walls);
9267 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9268 Some(((start + back).max(0) as u32, (start + fwd).min(i64::from(u32::MAX)) as u32))
9269 }
9270
9271 fn slide_delta_span(&self, members: &[(usize, usize)], walls: SourceWalls<'_>) -> (i64, i64) {
9272 members.iter().fold((i64::MIN, i64::MAX), |(back, fwd), &(l, i)| {
9273 let (b, f) = self.slide_span(l, i, walls);
9274 (back.max(b), fwd.min(f))
9275 })
9276 }
9277
9278 /// **Slide**: starts the clip at `idx` of `lane` at timeline frame `to`,
9279 /// between its neighbours. Its content and length stay; the out-point of the
9280 /// clip before it and the in-point of the clip after it absorb the move
9281 /// (each gives or takes the frames at its cut), so the timeline's length
9282 /// does not change. A neighbour across a gap is not edited: the clip just
9283 /// may not run into it.
9284 ///
9285 /// Clamped like [`trim`](Project::trim) to [`slide_room`](Project::slide_room);
9286 /// the take slides by the same delta, held to its tightest member, and at a
9287 /// rate where the exact frame is unreachable stops on the nearest one that
9288 /// is. `Some(start)`: where the clip starts now (the old place when nothing
9289 /// moved, costing no undo step; one step otherwise). `None`, changing
9290 /// nothing: no clip, or no neighbour on a side -- the first and last clip
9291 /// of a lane have nothing to give or take. A speed-ramped clip *after* the
9292 /// slid one cannot take a new in-point, which pins the slide.
9293 pub fn slide(&mut self, lane: Lane, idx: usize, to: u32, walls: SourceWalls<'_>) -> Option<u32> {
9294 let members = self.slide_members(lane, idx)?;
9295 let start = i64::from(self.lanes[members[0].0].clips[members[0].1].start);
9296 let (back, fwd) = self.slide_delta_span(&members, walls);
9297 let mut d = (i64::from(to) - start).clamp(back, fwd);
9298 let plan = loop {
9299 if d == 0 {
9300 return Some(start as u32);
9301 }
9302 let plan: Option<Vec<_>> = members
9303 .iter()
9304 .map(|&(l, i)| self.slid(l, i, d, walls).map(|p| (l, i, p)))
9305 .collect();
9306 if let Some(plan) = plan {
9307 break plan;
9308 }
9309 d -= d.signum();
9310 };
9311 self.snapshot();
9312 for (l, i, (p, c, n)) in plan {
9313 if let Some(p) = p {
9314 self.lanes[l].clips[i - 1] = p;
9315 }
9316 self.lanes[l].clips[i] = c;
9317 if let Some(n) = n {
9318 self.lanes[l].clips[i + 1] = n;
9319 }
9320 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
9321 }
9322 Some((start + d) as u32)
9323 }
9324
9325 /// The source frames that `by` timeline frames are worth for the clip at
9326 /// `idx` of `lane`: `by` itself at real time, `by * speed` at a constant
9327 /// rate and at the ramp's average rate for a ramped clip. Rounded to the
9328 /// nearest frame, so a tiny `by` on a slow clip can be zero. What a
9329 /// front-end turns a pointer or a typed timeline distance into before
9330 /// [`slip`](Project::slip), which works in the media's own frames.
9331 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
9332 let c = self.lane(lane).get(idx)?;
9333 let (len, frames) = (i128::from(c.len()), i128::from(c.frames()));
9334 let n = i128::from(by) * len;
9335 // Round half away from zero.
9336 let r = (n.abs() * 2 + frames) / (frames * 2) * n.signum();
9337 Some(r as i64)
9338 }
9339
9340 /// How far the clip at `idx` of `lane` may slip, `(back, forward)` in
9341 /// source frames (`back <= 0 <= forward`): back to the first frame of the
9342 /// source and forward to its last, which is where the clip's own window
9343 /// stops. `None` for a bad index and for a still, which has no frames to
9344 /// slip through.
9345 pub fn slip_room(&self, lane: Lane, idx: usize, walls: SourceWalls<'_>) -> Option<(i64, i64)> {
9346 let l = self.index(lane)?;
9347 let c = self.lanes[l].clips.get(idx)?;
9348 if self.is_still(c) {
9349 return None;
9350 }
9351 let t = walls.for_kind(self.lanes[l].kind);
9352 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9353 Some((-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0)))
9354 }
9355
9356 /// **Slip**: shifts the source window of the clip at `idx` of `lane` by
9357 /// `by` source frames (see [`slip_source_delta`](Project::slip_source_delta)
9358 /// for timeline frames), later in the file for positive. Its place on the
9359 /// timeline and its length -- at its speed or ramp -- are unchanged: the
9360 /// same slot shows different content. Gain and placement keys stay on the
9361 /// footage they were set on.
9362 ///
9363 /// Clamped to [`slip_room`](Project::slip_room), never refused; the rest of
9364 /// the take slips by the same source frames, each within its own media. A
9365 /// source with no known length may not slip forward, as it may not grow in
9366 /// a trim. `Some(shift)`: the source frames the clip actually moved (`0`
9367 /// when pinned at a limit or asked for nothing, costing no undo step; one
9368 /// step otherwise). `None`, changing nothing: no clip, or a still.
9369 pub fn slip(&mut self, lane: Lane, idx: usize, by: i64, walls: SourceWalls<'_>) -> Option<i64> {
9370 let (lo, hi) = self.slip_room(lane, idx, walls)?;
9371 let d = by.clamp(lo, hi);
9372 if d == 0 {
9373 return Some(0);
9374 }
9375 let l = self.index(lane)?;
9376 let members = self.group_of(lane, idx)?;
9377 let mut plan: Vec<(usize, usize, Clip)> = Vec::new();
9378 for &(ml, mi) in &members.clips {
9379 let c = &self.lanes[ml].clips[mi];
9380 let t = walls.for_kind(self.lanes[ml].kind);
9381 let limit = i64::from(t.get(c.source).copied().unwrap_or(c.out_frame));
9382 let own = if (ml, mi) == (l, idx) {
9383 d
9384 } else if self.is_still(c) {
9385 continue;
9386 } else {
9387 d.clamp(-i64::from(c.in_frame), (limit - i64::from(c.out_frame)).max(0))
9388 };
9389 if own == 0 {
9390 continue;
9391 }
9392 let mut n = c.clone();
9393 n.in_frame = (i64::from(c.in_frame) + own) as u32;
9394 n.out_frame = (i64::from(c.out_frame) + own) as u32;
9395 if !c.transform_keys.is_empty() {
9396 n.transform_keys = keys_within(&c.transform_keys, n.in_frame, n.out_frame);
9397 }
9398 for (ne, ce) in n.effects.iter_mut().zip(&c.effects) {
9399 if !ce.keys.is_empty() {
9400 ne.keys = keys_within(&ce.keys, n.in_frame, n.out_frame);
9401 }
9402 }
9403 plan.push((ml, mi, n));
9404 }
9405 self.snapshot();
9406 for (ml, mi, n) in plan {
9407 self.lanes[ml].clips[mi] = n;
9408 }
9409 Some(d)
9410 }
9411
9412 /// [`trim_room`](Project::trim_room) for a clip the caller already holds by
9413 /// its lane's storage index: the one wall computation, asked for the clip
9414 /// itself and for each member a group trim carries.
9415 fn clip_room(&self, l: usize, i: usize, edge: Edge, walls: SourceWalls<'_>) -> (u32, u32) {
9416 let (w, _, _) = self.clip_walls(l, i, edge, walls);
9417 (w.lo, w.hi)
9418 }
9419
9420 /// The walls [`clip_room`](Self::clip_room) measures, with the media flags
9421 /// [`trim_walls`](Project::trim_walls) reports. Every wall is computed here
9422 /// once; the flags are read off the same comparisons that pick the wall.
9423 fn clip_walls(
9424 &self,
9425 l: usize,
9426 i: usize,
9427 edge: Edge,
9428 walls: SourceWalls<'_>,
9429 ) -> (TrimWalls, WallBound, WallBound) {
9430 // The lane's own table: a sound's length on an audio lane, the picture's
9431 // everywhere else.
9432 let source_frames = walls.for_kind(self.lanes[l].kind);
9433 let clips = &self.lanes[l].clips;
9434 let c = clips[i].clone();
9435 // A still has no media limit to report: its head and tail reach as far
9436 // as the caller's table says, which is a cap, not a source's end.
9437 let still = self.is_still(&c);
9438 let prev_end = i.checked_sub(1).map_or(0, |p| clips[p].end());
9439 let (lo, hi, lo_media, hi_media, lo_bound, hi_bound) = match edge {
9440 Edge::Start => {
9441 // Back to the source's own first frame -- as many *timeline*
9442 // frames as that head is worth at the clip's rate, which at
9443 // real time is the head itself -- and never over the clip in
9444 // front of it. Saturating because a clip may hold *more*
9445 // head than the timeline has room for -- a ripple delete
9446 // slides a clip back to frame 0 with its in-point wherever
9447 // the cut left it -- and frame 0 is the other wall.
9448 //
9449 // A still is measured from its *tail* instead: it has no
9450 // in-point worth the name (every frame the same picture), so
9451 // its head reaches exactly as far as its tail does -- out to
9452 // the length the caller's table gives it, whole. Measured
9453 // from the in-point it would have no head room at all, which
9454 // is a placed picture whose left edge cannot be dragged out.
9455 // No entry in the table means no growth, as it does at the
9456 // other end.
9457 let head = if still {
9458 c.end().saturating_sub(
9459 c.speed
9460 .room(source_frames.get(c.source).copied().unwrap_or(c.len())),
9461 )
9462 } else if c.reversed {
9463 // The head is the window's far end: what it can still grow into
9464 // is what the file has past the out-point.
9465 c.start.saturating_sub(c.speed.room(
9466 source_frames
9467 .get(c.source)
9468 .copied()
9469 .unwrap_or(c.out_frame)
9470 .saturating_sub(c.out_frame),
9471 ))
9472 } else {
9473 c.start.saturating_sub(c.speed.room(c.in_frame))
9474 };
9475 (
9476 head.max(prev_end),
9477 // One *frame of clip* always survives, and at a rate below
9478 // real time one frame of clip is several frames of timeline
9479 // ([`Speed::room`]): an edge dragged closer than that would
9480 // ask for a range no source frame fits in. At real time this
9481 // is `end - 1`, unchanged.
9482 c.end() - c.speed.room(1),
9483 // The head is the binding wall when it is not behind the
9484 // neighbour; equal walls count as media. With no neighbour
9485 // the wall is frame 0, which the head always meets or beats.
9486 !still && head >= prev_end,
9487 // The clip's own minimum length, not a neighbour or media.
9488 false,
9489 // A neighbour that sits on the same frame as the source's
9490 // head is named: the two walls coincide, and the neighbour is
9491 // the one a caller can move, so a tie is worded as it.
9492 if i > 0 && head <= prev_end {
9493 WallBound::Neighbour(prev_end)
9494 } else if still {
9495 WallBound::Cap
9496 } else {
9497 WallBound::Source
9498 },
9499 WallBound::MinLength,
9500 )
9501 }
9502 Edge::End => {
9503 // Out to whatever is left of the source -- again in timeline
9504 // frames, at this clip's rate -- and never over the clip
9505 // behind it.
9506 let tail = c.start.saturating_add(c.speed.room(match c.reversed {
9507 // The tail is the window's near end, which grows down to the
9508 // file's first frame.
9509 true => c.out_frame,
9510 false => source_frames
9511 .get(c.source)
9512 .copied()
9513 .unwrap_or(c.out_frame)
9514 .saturating_sub(c.in_frame),
9515 }));
9516 let next = clips.get(i + 1).map_or(u32::MAX, |n| n.start);
9517 (
9518 // ...and the same wall from the other end: the shortest this
9519 // clip can be is the room one source frame of it takes.
9520 c.start + c.speed.room(1),
9521 tail.min(next),
9522 false,
9523 // The tail is the binding wall when it is not past the
9524 // neighbour; equal walls count as media.
9525 !still && tail <= next,
9526 WallBound::MinLength,
9527 // A tie with the neighbour's start is named as the neighbour
9528 // too, for the same reason as the start edge's.
9529 if clips.get(i + 1).is_some() && tail >= next {
9530 WallBound::Neighbour(next)
9531 } else if still {
9532 WallBound::Cap
9533 } else {
9534 WallBound::Source
9535 },
9536 )
9537 }
9538 };
9539 // `hi.max(lo)`: for a clip the invariants hold for, the range always
9540 // contains the edge's own place, and a caller's wrong `source_frames`
9541 // must not become an empty range (or a panicking `clamp`) here.
9542 (
9543 TrimWalls {
9544 lo,
9545 hi: hi.max(lo),
9546 lo_media,
9547 hi_media,
9548 },
9549 lo_bound,
9550 hi_bound,
9551 )
9552 }
9553
9554 /// Whether `clip` plays a still image ([`crate::is_image`]): a file whose
9555 /// every frame is the same picture, so which frame of it a clip's in-point
9556 /// names is not a question -- what [`Project::trim`] lets grow at either
9557 /// end. `false` for a source that is not there.
9558 fn is_still(&self, clip: &Clip) -> bool {
9559 self.sources
9560 .get(clip.source)
9561 .is_some_and(|s| crate::is_image(&s.path))
9562 }
9563
9564 /// The placements that move as one with the one at `idx` of `lane` --
9565 /// itself and whatever carries its link, on the media lanes and the
9566 /// subtitle ones alike. `None` for an index that is not there.
9567 /// Whether the clip at `idx` is in a take: its link is shared with another clip. A lone link
9568 /// (what [`ungroup`](Self::ungroup) leaves) is not a take, so the clip moves on its own.
9569 fn in_take(&self, lane: Lane, idx: usize) -> bool {
9570 self.group_of(lane, idx).is_some_and(|m| !m.alone())
9571 }
9572
9573 fn group_of(&self, lane: Lane, idx: usize) -> Option<Members> {
9574 let sub = lane.kind == LaneKind::Subtitle;
9575 let link = if sub {
9576 self.sub_lane(lane).get(idx)?.link
9577 } else {
9578 self.lane(lane).get(idx)?.link
9579 };
9580 let mut members = Members::default();
9581 match link {
9582 Some(link) => {
9583 for (l, data) in self.lanes.iter().enumerate() {
9584 if let Some(i) = data.clips.iter().position(|c| c.link == Some(link)) {
9585 members.clips.push((l, i));
9586 }
9587 if let Some(i) = data.subs.iter().position(|s| s.link == Some(link)) {
9588 members.subs.push((l, i));
9589 }
9590 }
9591 }
9592 None => {
9593 let l = self.index(lane).expect("the placement was found on it");
9594 if sub {
9595 members.subs.push((l, idx));
9596 } else {
9597 members.clips.push((l, idx));
9598 }
9599 }
9600 }
9601 Some(members)
9602 }
9603
9604 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
9605 /// new group, pushing everything from there on later by its length in
9606 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
9607 /// the clip it lands in is split around it; past the end of the timeline it
9608 /// goes down where it was asked for, with black in front of it -- which is
9609 /// what a library row let go on the open bed means, and what the ghost under
9610 /// the pointer promised. A clipboard means "put it here", not "here and
9611 /// black in front", and clamps to the end at its own door
9612 /// ([`crate::PlaybackSession::paste_at`]).
9613 /// Use [`place`](Project::place) to paste into one lane, or to make a gap.
9614 ///
9615 /// `V1` and `A1` and no other lane, because a take is one picture and one
9616 /// sound: copying it onto every lane there is would play the same audio
9617 /// twice over (and leave an mp4 export with two tracks to copy). A clip of a
9618 /// source with no picture ([`crate::is_audio`]) reaches `A1` only -- on a
9619 /// video lane it is a clip that decodes to nothing, and a save carrying one
9620 /// does not open again -- and a still image ([`crate::is_image`]) reaches
9621 /// `V1` only, for the mirror of that reason. The room is still opened on
9622 /// every media lane, or the lanes it was not inserted into would slide out
9623 /// of step with the ones it was -- and the subtitle lanes are left alone:
9624 /// the words keep their own clock, and a caption that should travel with a
9625 /// clip is what a group is for.
9626 ///
9627 /// Exactly one history snapshot, so one [`Project::undo`] takes it back.
9628 /// Changes the timeline->source mapping: the caller must reseek. Refused for
9629 /// an empty `clip` and for one naming a source that is not there (both of
9630 /// which the public fields let a caller build), and for a paste whose ripple
9631 /// would push a clip past the last frame there is -- nothing is changed by
9632 /// any of them.
9633 pub fn paste(&mut self, timeline_frame: u32, clip: Clip) -> bool {
9634 let source = self.sources.get(clip.source);
9635 let compound = is_sequence_source(clip.source);
9636 if source.is_none() && (!compound || self.compound_refusal(&clip).is_some()) {
9637 return false;
9638 }
9639 if clip.out_frame <= clip.in_frame {
9640 return false;
9641 }
9642 let audio_only = source.is_some_and(|s| crate::is_audio(&s.path));
9643 // ...and its mirror: a still is a picture and no sound, so a copy of one
9644 // reaches `V1` only. Pasted onto `A1` as well it is a PNG the audio
9645 // worker tries to demux -- which silences the *whole session*, not just
9646 // that clip -- and a save the engine's own `open_project` then refuses.
9647 let picture_only = source.is_some_and(|s| crate::is_image(&s.path));
9648 // The frame it was asked for and no other: a row let go on the empty
9649 // bed past the last clip lands *there*, under the ghost that promised
9650 // it, with black in front. Clamping to the end here made every drop on
9651 // open bed an append -- the clipboard's rule, applied to a hand that
9652 // had named a place.
9653 let at = timeline_frame;
9654 // The room it takes on the timeline, which its speed decides -- not the
9655 // source range it reads.
9656 let len = clip.frames();
9657 // Room for it: `open_room` adds `len` to every start from `at` on, and a
9658 // hand-written file may hold a clip that ends at the very last frame
9659 // (`edith::check` permits `start + len == u32::MAX`). Refused here
9660 // rather than wrapped there -- a wrapped start lands *behind* the clip
9661 // it belongs after, which is an overlap no save will read back.
9662 if at.checked_add(len).is_none()
9663 || self
9664 .lanes
9665 .iter()
9666 .flat_map(|l| &l.clips)
9667 .any(|c| c.end() > at && c.end().checked_add(len).is_none())
9668 {
9669 return false;
9670 }
9671 // ...and room *to open*: the paste splits whatever it lands inside of,
9672 // and a speeded clip can only be cut where its own rate has a source
9673 // frame ([`Speed::split_at`]). Refused rather than pasted over the top
9674 // of one, which is the overlap a lane may never hold. At real time every
9675 // frame answers, so this cannot refuse an unspeeded paste.
9676 let lands_inside = |clips: &[Clip]| clips.iter().any(|c| c.start < at && at < c.end());
9677 if self
9678 .lanes
9679 .iter()
9680 .any(|l| lands_inside(&l.clips) && splittable(&l.clips, at).is_none())
9681 {
9682 return false;
9683 }
9684 self.snapshot();
9685 let clip = Clip {
9686 fade_in: 0,
9687 fade_out: 0,
9688 transition_out: 0,
9689 transition_kind: Default::default(),
9690 start: at,
9691 link: Some(self.new_link()),
9692 ..clip
9693 };
9694 // Only lanes that can play the source: a file with no picture belongs on
9695 // an audio lane and nowhere else, exactly as `place_stream_at` decides
9696 // it for an import. On a video lane it would decode to nothing, and the
9697 // save it wrote would not open again.
9698 let kinds: &[LaneKind] = match (audio_only, picture_only) {
9699 (true, _) => &[LaneKind::Audio],
9700 (_, true) => &[LaneKind::Video],
9701 _ => &[LaneKind::Video, LaneKind::Audio],
9702 };
9703 let takes: Vec<usize> = kinds
9704 .iter()
9705 .filter_map(|&kind| self.index(Lane::new(kind, 0)))
9706 .collect();
9707 for (i, data) in self.lanes.iter_mut().enumerate() {
9708 open_room(&mut data.clips, at, len);
9709 // The subtitle lanes are NOT touched: a paste inserts media, and
9710 // the words keep their own clock. Opening room here used to split
9711 // a caption the paste landed inside and slide the rest behind it
9712 // -- "a caption that stayed put while the picture moved on no
9713 // longer says the same thing" -- but a caption pinned to nothing
9714 // (and a video arriving on a timeline of words alone) has no
9715 // picture to follow, and the split did to the words what no hand
9716 // asked for. A caption that should travel with a clip is what a
9717 // group is for, and a group moves as one.
9718 if takes.contains(&i) {
9719 let idx = data.clips.partition_point(|c| c.start < at);
9720 data.clips.insert(idx, clip.clone());
9721 }
9722 debug_assert!(sorted_disjoint(&data.clips));
9723 debug_assert!(subs_sorted_disjoint(&data.subs));
9724 }
9725 true
9726 }
9727
9728 /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in
9729 /// `items` lands on the lane it names, its head moved by the offset every
9730 /// other item moves by too -- `at` less the earliest `start` among them,
9731 /// so the set's own gaps and lane assignment survive the trip from
9732 /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the
9733 /// way a lone clip's copy does.
9734 ///
9735 /// All-or-nothing, and **refused** rather than opening room or splitting
9736 /// a neighbour the way [`paste`](Project::paste) does for one clip:
9737 /// a set-paste never ripples the bed, so a landing that overlaps so much
9738 /// as one existing clip on its own lane refuses the whole set, changing
9739 /// nothing -- the paste's own [`move_selection`](Project::move_selection)
9740 /// clamps instead of refusing, but a paste has no drag to clamp against,
9741 /// and a landing moved off the frame asked for is not what a paste means.
9742 /// `items` empty, naming a lane or a source that is not there, or a clip
9743 /// with `out_frame <= in_frame`, refuses too, before anything is touched.
9744 ///
9745 /// Exactly one history snapshot for the whole set, so one
9746 /// [`Project::undo`] takes it back. Changes the timeline->source mapping
9747 /// on every lane an item lands on: the caller must reseek.
9748 pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool {
9749 let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else {
9750 return false;
9751 };
9752 // Resolved once, up front, off the lanes as they stand now: a lane or
9753 // source that is not there, or a landing that would overlap a
9754 // neighbour, refuses the whole set before any of it is written.
9755 let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len());
9756 for (lane, clip) in items.iter().cloned() {
9757 let Some(li) = self.index(lane) else {
9758 return false;
9759 };
9760 let known = self.sources.get(clip.source).is_some()
9761 || (is_sequence_source(clip.source) && self.compound_refusal(&clip).is_none());
9762 if !known || clip.out_frame <= clip.in_frame {
9763 return false;
9764 }
9765 let delta = i64::from(clip.start) - i64::from(anchor);
9766 let Ok(start) = u32::try_from(i64::from(at) + delta) else {
9767 return false;
9768 };
9769 let Some(end) = start.checked_add(clip.frames()) else {
9770 return false;
9771 };
9772 if self.lanes[li]
9773 .clips
9774 .iter()
9775 .any(|c| c.start < end && start < c.end())
9776 {
9777 return false;
9778 }
9779 landings.push((li, Clip { start, ..clip }));
9780 }
9781 self.snapshot();
9782 for (li, mut clip) in landings {
9783 clip.link = Some(self.new_link());
9784 clip.fade_in = 0;
9785 clip.fade_out = 0;
9786 clip.transition_out = 0;
9787 let clips = &mut self.lanes[li].clips;
9788 let idx = clips.partition_point(|c| c.start < clip.start);
9789 clips.insert(idx, clip);
9790 }
9791 true
9792 }
9793
9794 /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or
9795 /// silence, and nothing else moves. Refused only for an out-of-range index
9796 /// (which a lane that is not there always is) -- lifting the last placement
9797 /// there is leaves an *empty* timeline, which is a state the project holds
9798 /// like any other and an undo brings back.
9799 /// Swaps the placements at `a` and `b` of `lane`: `b` takes `a`'s start, the
9800 /// placements between them move by the difference in their lengths (the
9801 /// ripple within this one lane), and `a` lands where `b` was, moved by the
9802 /// same difference. The span the two cover keeps its length, so nothing
9803 /// after `b` moves. One snapshot.
9804 ///
9805 /// `false`, nothing changed, for an index that is not there, `a == b`, and a
9806 /// placement in a group: a take is moved as a take, never swapped apart.
9807 pub fn swap(&mut self, lane: Lane, a: usize, b: usize) -> bool {
9808 let (a, b) = if a < b { (a, b) } else { (b, a) };
9809 let Some(new) = (|| {
9810 let clips = self.lane(lane);
9811 if a == b || b >= clips.len() || self.in_take(lane, a) || self.in_take(lane, b) {
9812 return None;
9813 }
9814 let span = &clips[a..=b];
9815 let (sa, sb) = (span[0].start, span[span.len() - 1].start);
9816 let d = i64::from(span[span.len() - 1].frames()) - i64::from(span[0].frames());
9817 let shift = |x: u32, by: i64| (i64::from(x) + by) as u32;
9818 let last = span.len() - 1;
9819 let mut out = Vec::with_capacity(span.len());
9820 let mut first_in = span[last].clone();
9821 first_in.start = sa;
9822 out.push(first_in);
9823 for c in &span[1..last] {
9824 let mut m = c.clone();
9825 m.start = shift(m.start, d);
9826 out.push(m);
9827 }
9828 let mut back = span[0].clone();
9829 back.start = shift(sb, d);
9830 out.push(back);
9831 Some(out)
9832 })() else {
9833 return false;
9834 };
9835 self.snapshot();
9836 self.lane_mut(lane).expect("checked above").splice(a..=b, new);
9837 true
9838 }
9839
9840 /// Exchanges the positions of two unlinked clips on `lane` without rippling
9841 /// anything: each takes the other's head, and whatever lies between them stays
9842 /// where it is. When the two differ in length the shorter leaves a gap where it
9843 /// was and the longer must fit its new place -- the one that does not fit is
9844 /// refused, naming the clip it would overlap, and nothing changes.
9845 ///
9846 /// Both new footprints are checked against every clip that stays put, at once,
9847 /// so a clip moving into the slot the other one vacates is not refused for
9848 /// overlapping a slot that is about to be free (which is what sequencing three
9849 /// single moves did). One undo step.
9850 pub fn swap_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
9851 let label = lane.label();
9852 let clips = self.lane(lane);
9853 if a == b {
9854 return Err("the same clip twice: name two different clips".into());
9855 }
9856 let (Some(ca), Some(cb)) = (clips.get(a).cloned(), clips.get(b).cloned()) else {
9857 return Err(format!("there is no clip {} or {} on {label}", a.max(b), a.min(b)).into());
9858 };
9859 if self.in_take(lane, a) || self.in_take(lane, b) {
9860 return Err(format!(
9861 "clip {a} and clip {b} on {label} are grouped with other lanes: a take moves as a take, not swapped apart"
9862 )
9863 .into());
9864 }
9865 let mut moved_a = ca.clone();
9866 moved_a.start = cb.start;
9867 let mut moved_b = cb.clone();
9868 moved_b.start = ca.start;
9869 let placed = [(a, &moved_a), (b, &moved_b)];
9870 for (idx, moved) in placed {
9871 for (i, other) in clips.iter().enumerate() {
9872 if i == a || i == b {
9873 continue;
9874 }
9875 if moved.start < other.end() && other.start < moved.end() {
9876 return Err(format!(
9877 "swapping {a} and {b} on {label} would put clip {idx} at {}f..{}f, which overlaps clip {i} at {}f..{}f: move that clip or trim this one first",
9878 moved.start,
9879 moved.end(),
9880 other.start,
9881 other.end()
9882 )
9883 .into());
9884 }
9885 }
9886 }
9887 if moved_a.start < moved_b.end() && moved_b.start < moved_a.end() {
9888 return Err(format!(
9889 "swapping {a} and {b} on {label} would overlap the two clips with each other ({}f..{}f and {}f..{}f): the longer one is wider than the space between them",
9890 moved_b.start,
9891 moved_b.end(),
9892 moved_a.start,
9893 moved_a.end()
9894 )
9895 .into());
9896 }
9897 self.snapshot();
9898 let list = self.lane_mut(lane).expect("checked above");
9899 list[a] = moved_a;
9900 list[b] = moved_b;
9901 list.sort_by_key(|c| c.start);
9902 debug_assert!(sorted_disjoint(list));
9903 Ok(())
9904 }
9905
9906 pub fn lift(&mut self, lane: Lane, idx: usize) -> bool {
9907 if idx >= self.lane(lane).len() {
9908 return false;
9909 }
9910 self.snapshot();
9911 self.lane_mut(lane).expect("checked above").remove(idx);
9912 true
9913 }
9914
9915 /// Cut the timeline frames `[at, at + len)` out of *every* lane and close
9916 /// the hole: everything after slides back by `len`. The rippling delete --
9917 /// [`lift`](Project::lift) is the one that leaves a gap. Refused only for an
9918 /// empty range; a delete that leaves nothing behind empties the timeline,
9919 /// which is a state like any other and one undo away.
9920 pub fn ripple_delete(&mut self, at: u32, len: u32) -> bool {
9921 if len == 0 {
9922 return false;
9923 }
9924 // Nothing reaches past `at`: there is nothing to cut and nothing to
9925 // slide back, and a delete that changes nothing must not cost an undo
9926 // step (see [`snapshot`](Project::snapshot)).
9927 if !self
9928 .lanes
9929 .iter()
9930 .flat_map(|l| &l.clips)
9931 .any(|c| c.end() > at)
9932 {
9933 return false;
9934 }
9935 self.snapshot();
9936 let on = all_lanes(&self.lanes);
9937 let tracks = self.caption_tracks_on(&on);
9938 let placed = self.placed_cues(&tracks);
9939 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
9940 ripple(&mut self.lanes, &on, at, len);
9941 self.drop_unplaced(&tracks, &placed, &pieces);
9942 true
9943 }
9944
9945 /// The empty stretch of `lane` covering `frame`, as `(start, len)` -- what
9946 /// a right-click on empty bench space names before offering to close it.
9947 /// `None` when `frame` sits inside a placement, or past the last one: the
9948 /// open end of a lane is not a gap, since there is nothing after it to slide
9949 /// back ([`gap`]). Subtitle lanes are asked of their [`SubClip`] list, not
9950 /// the media [`Clip`] list they deliberately never hold.
9951 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
9952 let data = self.index(lane).map(|i| &self.lanes[i])?;
9953 match data.kind {
9954 LaneKind::Subtitle => gap(&data.subs, frame),
9955 LaneKind::Video | LaneKind::Audio => gap(&data.clips, frame),
9956 }
9957 }
9958
9959 /// How many bounded holes `lane` holds. The open end after the last
9960 /// placement is not counted, like [`gap_at`](Self::gap_at), because closing
9961 /// it would move nothing.
9962 pub fn gap_count(&self, lane: Lane) -> usize {
9963 let Some(data) = self.index(lane).map(|i| &self.lanes[i]) else {
9964 return 0;
9965 };
9966 match data.kind {
9967 LaneKind::Subtitle => gaps(&data.subs).len(),
9968 LaneKind::Video | LaneKind::Audio => gaps(&data.clips).len(),
9969 }
9970 }
9971
9972 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
9973 /// together to keep sync -- what a right-click on empty bench space asks
9974 /// before the menu offers to close it, and what widens
9975 /// [`cut_regions`](Project::cut_regions)'s scope from the one lane a hand
9976 /// named to the whole take the gap might be half of.
9977 ///
9978 /// A clip bordering the gap on `lane` -- the one ending where it starts,
9979 /// the one starting where it ends -- carries a link when it is one take
9980 /// with a clip on another lane. That lane joins the scope only when the
9981 /// *exact same* stretch is empty there too (same start, same length): the
9982 /// ripple then removes nothing but silence, on every lane it touches, and
9983 /// both halves stay the length they always were. A link whose partner
9984 /// lane is not empty there -- a gap of a different length, or none at all
9985 /// -- is named back to the caller rather than silently widened past
9986 /// (which would cut real media out of a lane nothing asked to touch) or
9987 /// silently left out (which is the defect this closes: a per-lane ripple
9988 /// would leave [`scope_holds_takes_whole`](Project::scope_holds_takes_whole)
9989 /// to refuse it after the fact, on the very half this could have carried
9990 /// along).
9991 ///
9992 /// `Ok(vec![lane])` alone for a gap that borders no take, or none whose
9993 /// partner clip sits on another lane -- the unlinked case, untouched.
9994 ///
9995 /// Subtitle lanes have no media take halves to inspect. A caption can be
9996 /// hand-grouped with clips, but it is not the imported A/V take this method
9997 /// widens for, so a subtitle gap stays scoped to its own lane; the later
9998 /// scoped cut still refuses an explicit group split.
9999 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
10000 let Some(li) = self.index(lane) else {
10001 return Err("no track to work on".into());
10002 };
10003 let labels = handles(&self.lanes);
10004 let end = start + frames;
10005 let mut scope = vec![lane];
10006 for c in self.lanes[li]
10007 .clips
10008 .iter()
10009 .filter(|c| c.end() == start || c.start == end)
10010 {
10011 let Some(id) = c.link else { continue };
10012 for (j, data) in self.lanes.iter().enumerate() {
10013 if j == li {
10014 continue;
10015 }
10016 if !data.clips.iter().any(|o| o.link == Some(id)) {
10017 continue;
10018 }
10019 match gap(&data.clips, start) {
10020 Some((s, f)) if s == start && f == frames => {
10021 let other = labels[j];
10022 if !scope.contains(&other) {
10023 scope.push(other);
10024 }
10025 }
10026 _ => {
10027 // One plain line: the partner by name, and the reason in a word.
10028 return Err(format!("Can't close this gap: it would put {} out of sync.", labels[j].label()).into());
10029 }
10030 }
10031 }
10032 }
10033 Ok(scope)
10034 }
10035
10036 /// Close every bounded gap on `lane`, as one undo step, without making the
10037 /// lane's scope global. Media lanes use the same take-safety widening
10038 /// [`gap_take_scope`](Self::gap_take_scope) gives a single close: linked
10039 /// halves ride along only when their matching lane is empty over that exact
10040 /// stretch; mismatches are skipped and reported. Subtitle lanes close their
10041 /// own [`SubClip`] list only: captions may be hand-grouped, but they are not
10042 /// halves of an imported A/V take, so the media take-widening rule has
10043 /// nothing to add there.
10044 ///
10045 /// The walk is back-to-front. Closing a gap shifts everything after it, so
10046 /// later holes must be consumed while their measured starts are still true;
10047 /// earlier starts are unchanged by cuts to their right. A snapshot is taken
10048 /// only before the first successful close, so an all-skipped sweep is not an
10049 /// undo step.
10050 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
10051 let Some(i) = self.index(lane) else {
10052 return Err("no track to work on".into());
10053 };
10054 if self.lanes[i].kind == LaneKind::Subtitle {
10055 return Ok(self.close_all_subtitle_gaps_on_lane(i));
10056 }
10057 let mut report = GapSweep::default();
10058 let mut snapshot = false;
10059 for (start, frames) in gaps(self.lane(lane)).into_iter().rev() {
10060 match self.gap_take_scope(lane, start, frames).and_then(|scope| {
10061 let on = self.scoped(&scope)?;
10062 self.scope_holds_takes_whole(&on, start)?;
10063 Ok(on)
10064 }) {
10065 Ok(on) => {
10066 if !snapshot {
10067 self.snapshot();
10068 snapshot = true;
10069 }
10070 ripple(&mut self.lanes, &on, start, frames);
10071 report.closed += 1;
10072 }
10073 Err(e) => report.skipped.push(GapSkip {
10074 start,
10075 reason: e.to_string(),
10076 }),
10077 }
10078 }
10079 report.skipped.reverse();
10080 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10081 Ok(report)
10082 }
10083
10084 /// Subtitle lanes have the same bounded-gap sweep as media lanes, but no
10085 /// take-scope widening: a caption is not one half of an A/V take. Explicit
10086 /// hand groups still obey [`scope_holds_takes_whole`](Self::scope_holds_takes_whole),
10087 /// so a grouped caption is refused rather than pulled away from its group.
10088 fn close_all_subtitle_gaps_on_lane(&mut self, i: usize) -> GapSweep {
10089 let mut report = GapSweep::default();
10090 let mut snapshot = false;
10091 let on = [i];
10092 for (start, frames) in gaps(&self.lanes[i].subs).into_iter().rev() {
10093 match self.scope_holds_takes_whole(&on, start) {
10094 Ok(()) => {
10095 if !snapshot {
10096 self.snapshot();
10097 snapshot = true;
10098 }
10099 ripple(&mut self.lanes, &on, start, frames);
10100 report.closed += 1;
10101 }
10102 Err(e) => report.skipped.push(GapSkip {
10103 start,
10104 reason: e.to_string(),
10105 }),
10106 }
10107 }
10108 report.skipped.reverse();
10109 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10110 report
10111 }
10112
10113 /// Cut **every** one of `regions` -- `(start, len)` in timeline frames --
10114 /// out of the lanes in `scope` and close each hole, as one edit: the
10115 /// jumpcut a silence scan asks for ([`crate::silence`]).
10116 ///
10117 /// A lane that is not in `scope` **does not move**, which is the whole
10118 /// point of the parameter: the silences of a podcast track come out
10119 /// without the music track under it sliding. `scope` is an arbitrary set of
10120 /// lanes and not a kind or a range, so a caller with its own idea of what
10121 /// is selected (a take, a track, everything) says it in lanes and nothing
10122 /// here has to learn about selection.
10123 ///
10124 /// One [`snapshot`](Project::snapshot) for the lot, which is the whole
10125 /// reason this exists rather than a caller's loop over
10126 /// [`ripple_delete`](Project::ripple_delete): forty silences must be one
10127 /// undo press, not forty. Cut back to front, so a region's frames still
10128 /// mean what the caller measured while the ones before it are cut.
10129 ///
10130 /// The list is sorted and overlapping entries are merged before anything is
10131 /// cut ([`tidy`]) -- two regions that overlap would otherwise cut each
10132 /// other's frames. Refused, with no undo step, for an empty list, for a
10133 /// scope naming no lane that is there, and -- by name -- when the scope
10134 /// would take one half of a take with it
10135 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole)).
10136 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
10137 let regions = tidy(regions);
10138 let on = self.scoped(scope)?;
10139 let Some(&(first, _)) = regions.first() else {
10140 return Err("nothing to cut".into());
10141 };
10142 self.scope_holds_takes_whole(&on, first)?;
10143 self.snapshot();
10144 for &(at, len) in regions.iter().rev() {
10145 let tracks = self.caption_tracks_on(&on);
10146 let placed = self.placed_cues(&tracks);
10147 let pieces = self.split_cues_across(&on, &[at, at.saturating_add(len)], true);
10148 ripple_keeping_takes(&mut self.lanes, &on, at, len, &mut self.next_link);
10149 self.drop_unplaced(&tracks, &placed, &pieces);
10150 }
10151 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10152 self.settle();
10153 Ok(())
10154 }
10155
10156 /// The storage indices of `scope`, which is what every batch below walks.
10157 /// `Err` for a scope that names nothing there rather than a silent no-op:
10158 /// an edit asked for on a lane that is not there did not happen, and the
10159 /// caller has to hear so.
10160 fn scoped(&self, scope: &[Lane]) -> crate::Result<Vec<usize>> {
10161 let on: Vec<usize> = scope.iter().filter_map(|&l| self.index(l)).collect();
10162 match on.is_empty() {
10163 true => Err("no track to work on".into()),
10164 false => Ok(on),
10165 }
10166 }
10167
10168 /// The law a scoped ripple lives under: **a group travels as one**, so a
10169 /// batch that moves one half of a take and not the other would leave the
10170 /// halves disagreeing about where they stand -- an offset no hand asked
10171 /// for, and the reason the take's lanes have to be scoped together.
10172 ///
10173 /// Refused by name rather than widened silently. Widening would edit a
10174 /// track the user did not scope, which is exactly the surprise scoping
10175 /// exists to end; a front-end that wants the take is free to *say* the
10176 /// take's lanes, and to name them in what it tells the user afterwards.
10177 ///
10178 /// Only from `from` on: a take sitting entirely before the first cut does
10179 /// not move, so it is not this rule's business.
10180 fn scope_holds_takes_whole(&self, on: &[usize], from: u32) -> crate::Result<()> {
10181 let labels = handles(&self.lanes);
10182 // The halves of a group are on either of a lane's lists, and the
10183 // refusal names whichever sits outside the scope -- a clip like it
10184 // always has, and a caption now that a group may hold one.
10185 let halves = |start: u32, link: Option<u32>, what: &str| -> crate::Result<()> {
10186 let Some(id) = link else {
10187 return Ok(());
10188 };
10189 for (j, data) in self.lanes.iter().enumerate() {
10190 if on.contains(&j) {
10191 continue;
10192 }
10193 let clip = data.clips.iter().find(|o| o.link == Some(id));
10194 let sub = data.subs.iter().find(|s| s.link == Some(id));
10195 if let Some(half) = clip {
10196 return Err(format!(
10197 "the {what} at frame {start} is one take with the {} clip at frame {}: \
10198 moving one track of a take would pull it apart -- take the whole take, \
10199 or detach them first",
10200 labels[j].label(),
10201 half.start
10202 )
10203 .into());
10204 }
10205 if let Some(half) = sub {
10206 return Err(format!(
10207 "the {what} at frame {start} is one take with the {} caption at frame {}: \
10208 moving one track of a take would pull it apart -- take the whole take, \
10209 or detach them first",
10210 labels[j].label(),
10211 half.start
10212 )
10213 .into());
10214 }
10215 }
10216 Ok(())
10217 };
10218 for &i in on {
10219 for c in self.lanes[i].clips.iter().filter(|c| c.end() > from) {
10220 halves(c.start, c.link, &format!("{} clip", labels[i].label()))?;
10221 }
10222 // A caption before the first cut does not move, so it is not this
10223 // rule's business -- exactly the clip test's own line.
10224 for s in self.lanes[i].subs.iter().filter(|s| s.end() > from) {
10225 halves(s.start, s.link, &format!("{} caption", labels[i].label()))?;
10226 }
10227 }
10228 Ok(())
10229 }
10230
10231 /// Play every one of `regions` at `speed` instead of cutting it: each is
10232 /// split out of whatever covers it, re-rated, and the room it no longer
10233 /// needs closed up behind it -- [`set_speed`](Project::set_speed) alone
10234 /// does not ripple, and a hole where a silence shrank is the one thing this
10235 /// must not leave. One snapshot for the lot, like
10236 /// [`cut_regions`](Project::cut_regions).
10237 ///
10238 /// The rate is **absolute**, not a multiplier on what is there: running it
10239 /// twice over the same stretch leaves it at `speed`, not at `speed`
10240 /// squared, so a second pass over an already-cut timeline changes nothing.
10241 ///
10242 /// Scoped exactly as [`cut_regions`](Project::cut_regions) is, and under
10243 /// the same take law: a lane outside `scope` is neither re-rated nor moved.
10244 ///
10245 /// Refused by name, with nothing changed and no undo step, when:
10246 ///
10247 /// * the scope would take one half of a take with it
10248 /// ([`scope_holds_takes_whole`](Project::scope_holds_takes_whole));
10249 /// * a clip on a scoped lane covers only *part* of a region -- the lanes
10250 /// shrink by different amounts and the ripple would pull them apart,
10251 /// which is what cutting does not suffer and why delete mode has no such
10252 /// refusal;
10253 /// * a rate cannot address a region's edge ([`Speed::split_at`]), so the
10254 /// piece could not be split out exactly;
10255 /// * two lanes' pieces would end up different lengths, which is a group
10256 /// whose halves disagree about their span (the refusal
10257 /// [`write_speed`](Project::write_speed) already makes, in its words);
10258 /// * the region would grow rather than shrink, i.e. it already plays faster
10259 /// than `speed`.
10260 pub fn speed_regions(
10261 &mut self,
10262 regions: &[(u32, u32)],
10263 speed: Speed,
10264 scope: &[Lane],
10265 ) -> crate::Result<()> {
10266 let regions = tidy(regions);
10267 let on = self.scoped(scope)?;
10268 let Some(&(first, _)) = regions.first() else {
10269 return Err("nothing to speed up".into());
10270 };
10271 self.scope_holds_takes_whole(&on, first)?;
10272 if self.lanes.iter().any(|l| {
10273 l.clips.iter().any(|c| {
10274 is_sequence_source(c.source) && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10275 })
10276 }) {
10277 return Err("a compound clip plays forward at normal speed: change the speed of the clips inside it".into());
10278 }
10279 if self.lanes.iter().any(|l| {
10280 l.clips.iter().any(|c| {
10281 !c.speed_keys.is_empty()
10282 && regions.iter().any(|&(a, b)| c.start < b && a < c.end())
10283 })
10284 }) {
10285 return Err("a clip under the region has a speed ramp: clear the ramp first".into());
10286 }
10287 let labels = handles(&self.lanes);
10288 // Before anything is touched, because this is the refusal a person can
10289 // act on: a clip that laps over the edge of a silence has to be trimmed
10290 // (or the silences cut instead), and saying so after a rollback would
10291 // be saying it about a timeline that already looks different.
10292 for &(at, len) in &regions {
10293 for &l in &on {
10294 for c in &self.lanes[l].clips {
10295 if c.end() > at && c.start < at + len && !(c.start <= at && c.end() >= at + len)
10296 {
10297 return Err(format!(
10298 "the {} clip at frame {} covers only part of the silence at [{at}, {}): \
10299 speeding it up would pull the lanes apart -- trim it first, or cut the \
10300 silences out instead",
10301 labels[l].label(),
10302 c.start,
10303 at + len
10304 )
10305 .into());
10306 }
10307 }
10308 }
10309 }
10310 // The rest is checked as it is built: a split's own arithmetic is what
10311 // says whether a rate can address an edge. So the snapshot is taken
10312 // first and *rolled back* on a refusal -- one undo either way, and a
10313 // refusal still costs no step (`roll_back_snapshot` takes back the one just pushed).
10314 self.snapshot();
10315 for &(at, len) in regions.iter().rev() {
10316 self.write_split(at, false, &on);
10317 self.write_split(at + len, false, &on);
10318 let mut room: Option<(Lane, u32)> = None;
10319 let mut refused = None;
10320 for &l in &on {
10321 let clips = &self.lanes[l].clips;
10322 for c in clips.iter().filter(|c| c.end() > at && c.start < at + len) {
10323 if (c.start, c.end()) != (at, at + len) {
10324 // *Which* edge did not come off: a rate that cannot
10325 // address the end of the silence is not a rate that
10326 // cannot address its start, and naming the wrong frame
10327 // sends the user looking in the wrong place.
10328 let edge = match c.start == at {
10329 true => at + len,
10330 false => at,
10331 };
10332 refused = Some(format!(
10333 "the {} clip at frame {} plays at {} and cannot be cut at frame {edge}: \
10334 detach it, or put it back to 1.00x first",
10335 labels[l].label(),
10336 c.start,
10337 c.speed
10338 ));
10339 continue;
10340 }
10341 let after = speed.frames(c.len());
10342 match room {
10343 None => room = Some((labels[l], after)),
10344 Some((first, n)) if n != after => {
10345 refused = Some(format!(
10346 "at {speed} the {} half of the silence at frame {at} would cover \
10347 {after} frames and the {} half {n}: they are one take and a take \
10348 is one span -- detach them first",
10349 labels[l].label(),
10350 first.label()
10351 ));
10352 }
10353 Some(_) => {}
10354 }
10355 }
10356 }
10357 let shrunk = match (refused, room) {
10358 (Some(e), _) => {
10359 self.roll_back_snapshot();
10360 return Err(e.into());
10361 }
10362 // A gap on every lane: nothing to re-rate, and nothing to close.
10363 (None, None) => continue,
10364 (None, Some((_, after))) => after,
10365 };
10366 // The region's new length, on every scoped lane alike.
10367 let after = shrunk;
10368 let Some(delta) = len.checked_sub(shrunk) else {
10369 self.roll_back_snapshot();
10370 return Err(format!(
10371 "the silence at frame {at} already plays faster than {speed}: \
10372 at that rate it would be {shrunk} frames instead of {len}"
10373 )
10374 .into());
10375 };
10376 for &l in &on {
10377 for c in &mut self.lanes[l].clips {
10378 if c.start == at && c.end() == at + len {
10379 c.speed = speed;
10380 } else if c.start >= at + len {
10381 c.start -= delta;
10382 }
10383 }
10384 debug_assert!(sorted_disjoint(&self.lanes[l].clips));
10385 // The captions on a scoped lane travel with the region's time:
10386 // a piece inside it plays in `after` frames instead of `len`
10387 // -- same words on less timeline, its window untouched, for
10388 // [`write_speed`]'s reason -- and everything behind the region
10389 // slides up by what the region gave back.
10390 //
10391 // The pieces inside re-time by their *boundaries*, not each
10392 // on its own: rounding one piece's start and its neighbour's
10393 // start apart can land both on the same frame (two one-frame
10394 // cues of a thirty-frame region at 2x both want frame 15), so
10395 // the mapped boundaries are walked in order and forced apart
10396 // -- each piece at least one frame, none past the region's own
10397 // new end, where the first follower lands exactly. A rounding
10398 // artifact is clamped, not refused: nothing about the words
10399 // asked for an overlap.
10400 let share = f64::from(after) / f64::from(len).max(1.);
10401 let map = |bound: u32| at + (f64::from(bound - at) * share).round() as u32;
10402 let mut prev = at;
10403 let subs = &mut self.lanes[l].subs;
10404 for sub in subs.iter_mut() {
10405 let s = *sub;
10406 if s.start >= at + len {
10407 sub.start = s.start - delta;
10408 } else if s.start >= at && s.end() <= at + len {
10409 let mut start = map(s.start).max(prev);
10410 let end = map(s.end()).max(start + 1).min(at + after);
10411 start = start.min(end - 1);
10412 sub.start = start;
10413 sub.frames = end - start;
10414 prev = end;
10415 }
10416 }
10417 debug_assert!(subs_sorted_disjoint(&self.lanes[l].subs));
10418 }
10419 }
10420 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10421 self.settle();
10422 Ok(())
10423 }
10424
10425 /// Remove the `V1` clip at `idx` and everything under it, closing the gap
10426 /// -- the whole-group delete a single-lane front-end means. `false` for a
10427 /// bad index. Changes the mapping: the caller must reseek.
10428 pub fn delete(&mut self, idx: usize) -> bool {
10429 self.delete_in(Lane::V1, idx)
10430 }
10431
10432 /// [`delete`](Project::delete) for the lane the clip was picked on. A clip
10433 /// in no group (or a group of one, which is the same thing to a delete) is
10434 /// what it always was: its own span cut out of *every* lane, so the
10435 /// timeline closes up under it. A clip in a group takes the group with it,
10436 /// each member by its **own** span and on its **own** lane -- the members
10437 /// keep their offsets, so their spans may disagree, and the lanes may end
10438 /// up out of step with each other, which is inherent to a hand-built group
10439 /// and one undo away. Every member -- clips and captions alike -- goes by
10440 /// the same law: its own span out of its own lane, hole closed; a caption
10441 /// in no group keeps the lift that leaves a gap, which is its own door's
10442 /// law ([`delete_sub_in`](Project::delete_sub_in)). One snapshot for the
10443 /// whole group, so one [`Project::undo`] puts it back. `false` for a bad
10444 /// index, and for a lane that is not there. Changes the mapping: the
10445 /// caller must reseek.
10446 pub fn delete_in(&mut self, lane: Lane, idx: usize) -> bool {
10447 let Some(members) = self.group_of(lane, idx) else {
10448 return false;
10449 };
10450 if !members.alone() {
10451 return self.delete_members(&members);
10452 }
10453 let Some(clip) = self.lane(lane).get(idx).cloned() else {
10454 return false;
10455 };
10456 self.ripple_delete(clip.start, clip.frames())
10457 }
10458
10459 /// [`delete_in`](Project::delete_in) for the caption the pick named: a
10460 /// caption in no group lifts, exactly as its own key always made it
10461 /// ([`Project::lift_sub`]), and a caption in a group takes the group with
10462 /// it by [`delete_in`](Project::delete_in)'s rule -- every member's own
10463 /// span out of its own lane, hole closed, captions and clips alike.
10464 /// `false` for a bad index.
10465 pub fn delete_sub_in(&mut self, lane: Lane, idx: usize) -> bool {
10466 let Some(members) = self.group_of(lane, idx) else {
10467 return false;
10468 };
10469 if !members.alone() {
10470 return self.delete_members(&members);
10471 }
10472 self.lift_sub(lane, idx)
10473 }
10474
10475 /// The one whole-group delete both doors land in: every member's own span
10476 /// cut out of its own lane and the hole closed there -- clips and
10477 /// captions by the same law -- and nothing else on another lane moves,
10478 /// which is what keeps one member's ripple from dragging another
10479 /// member's lane out from under it. One snapshot, one undo step.
10480 fn delete_members(&mut self, members: &Members) -> bool {
10481 self.snapshot();
10482 for &(l, i) in &members.clips {
10483 let c = self.lanes[l].clips[i].clone();
10484 ripple(&mut self.lanes, &[l], c.start, c.frames());
10485 }
10486 // The captions go by the same law their clip siblings do -- the span
10487 // out of its own lane, the hole closed -- and not by the lift a
10488 // *lone* caption's delete is: deleted with its group, the words after
10489 // it slide up with everything else, or the lane the group emptied is
10490 // the one lane the delete left a hole in. `ripple` is the one
10491 // mechanism (it clears the span and shifts the rest, clips and
10492 // captions alike); a sub lane holds no clips, so its other list is
10493 // untouched.
10494 for &(l, i) in &members.subs {
10495 let s = self.lanes[l].subs[i];
10496 ripple(&mut self.lanes, &[l], s.start, s.frames);
10497 }
10498 debug_assert!(links_are_consistent(&self.lanes).is_ok());
10499 true
10500 }
10501
10502 /// The clips a lane holds, for the sweep's order law: `lane`'s own list.
10503 #[cfg(test)]
10504 pub(crate) fn lane_clips_pub(&self, lane: Lane) -> &[Clip] {
10505 self.lane(lane)
10506 }
10507
10508 /// The mark an action takes before it runs, for [`Project::name_step`]: the count
10509 /// of every step pushed so far. Settles a no-op first, so the mark is exact.
10510 pub(crate) fn step_mark(&mut self) -> u64 {
10511 self.settle();
10512 self.pushes
10513 }
10514
10515 /// Names the newest undo step, but only when the action that took `mark` pushed one:
10516 /// an action that changed nothing, or only undid, names nothing. The name is what
10517 /// Undo and Redo say about this step ([`Project::undo_label`]) and it leaves with
10518 /// the step, so a settled no-op or a capped-out step takes its name with it.
10519 pub(crate) fn name_step(&mut self, mark: u64, label: &str) {
10520 self.settle();
10521 if self.pushes > mark
10522 && let Some(top) = self.history.last_mut()
10523 {
10524 top.label = Some(label.to_string());
10525 }
10526 }
10527
10528 /// The name of the step [`Project::undo`] would take back; `None` when that step
10529 /// was never named, or when there is nothing to undo.
10530 pub fn undo_label(&self) -> Option<&str> {
10531 let top = match self.settling_no_op() {
10532 // The no-op is the newest step; settling it leaves the one under it on top.
10533 Some(_) => self.history.len().checked_sub(2).and_then(|i| self.history.get(i)),
10534 None => self.history.last(),
10535 };
10536 top.and_then(|s| s.label.as_deref())
10537 }
10538
10539 /// The name of the step [`Project::redo`] would walk forward to; `None` when that
10540 /// step was never named, or when there is nothing to redo.
10541 pub fn redo_label(&self) -> Option<&str> {
10542 let stack = match self.settling_no_op() {
10543 Some(pending) => &pending.redo,
10544 None => &self.redo,
10545 };
10546 stack.last().and_then(|s| s.label.as_deref())
10547 }
10548
10549 /// How many undo steps are stacked: what the sweep asks so "one op, one
10550 /// snapshot" is a count and not a guess.
10551 /// The name of every step [`Project::undo`] can take back, oldest first; `None` for a step
10552 /// nobody named. The last one is the step the project is on.
10553 pub fn undo_labels(&self) -> Vec<Option<String>> {
10554 let n = self.history_len();
10555 self.history.iter().take(n).map(|s| s.label.clone()).collect()
10556 }
10557
10558 /// The name of every step [`Project::redo`] can walk forward to, the next one last (the
10559 /// mirror of [`undo_labels`](Project::undo_labels)).
10560 pub fn redo_labels(&self) -> Vec<Option<String>> {
10561 let stack = match self.settling_no_op() {
10562 Some(pending) => &pending.redo,
10563 None => &self.redo,
10564 };
10565 stack.iter().map(|s| s.label.clone()).collect()
10566 }
10567
10568 pub(crate) fn history_len(&self) -> usize {
10569 match self.settling_no_op() {
10570 // The no-op's step goes, and the one it evicted comes back.
10571 Some(pending) => self.history.len() - 1 + usize::from(pending.evicted.is_some()),
10572 None => self.history.len(),
10573 }
10574 }
10575
10576 /// Every snapshot pushed so far, including those the cap has since dropped.
10577 pub(crate) fn history_pushes(&self) -> u64 {
10578 match self.settling_no_op() {
10579 Some(_) => self.pushes.saturating_sub(1),
10580 None => self.pushes,
10581 }
10582 }
10583
10584 /// Which state the project is in: a fresh id after every edit, and the id the
10585 /// state had before it after an undo, so equal revisions mean the same
10586 /// timeline. Never reused, so a revision names one state for good.
10587 pub fn revision(&self) -> u64 {
10588 match (self.settling_no_op(), self.history.last()) {
10589 (Some(_), Some(top)) => top.revision,
10590 _ => self.revision,
10591 }
10592 }
10593
10594 /// Drops the redo stack without a step: for a caller whose own trial edits
10595 /// were rolled back, which left their undone states here to redo.
10596 pub(crate) fn clear_redo(&mut self) {
10597 self.settle();
10598 self.redo.clear();
10599 }
10600
10601 /// Moves the redo stack out, leaving it empty, for a caller whose trial edits
10602 /// are about to run and may be rolled back. [`Project::restore_redo`] puts it
10603 /// back exactly, replacing whatever the trial's own undo steps left on it.
10604 pub(crate) fn take_redo(&mut self) -> RedoCheckpoint {
10605 self.settle();
10606 RedoCheckpoint(std::mem::take(&mut self.redo))
10607 }
10608
10609 /// Puts back a stack [`Project::take_redo`] took out.
10610 pub(crate) fn restore_redo(&mut self, cp: RedoCheckpoint) {
10611 self.settle();
10612 self.redo = cp.0;
10613 }
10614
10615 /// Lets the undo history run past [`HISTORY_CAP`] while a trial batch is open,
10616 /// so the trial's pushes evict nothing; closing it (`false`) trims the history
10617 /// back to the cap, dropping the oldest steps as an edit would.
10618 pub(crate) fn hold_history(&mut self, hold: bool) {
10619 self.settle();
10620 self.hold_cap = hold;
10621 if !hold {
10622 let over = self.history.len().saturating_sub(HISTORY_CAP);
10623 self.history.drain(..over);
10624 }
10625 }
10626
10627 /// How many redo steps are stacked: what the sweep asks to check `undo`
10628 /// left a branch behind, and that a fresh edit clears it.
10629 pub(crate) fn redo_len(&self) -> usize {
10630 match self.settling_no_op() {
10631 Some(pending) => pending.redo.len(),
10632 None => self.redo.len(),
10633 }
10634 }
10635
10636 /// The project's own settings as they stand ([`ProjectSettings`]) -- what an
10637 /// undo entry holds beside the lanes, and what the session reads back after
10638 /// one is restored ([`crate::PlaybackSession::undo`]).
10639 pub(crate) fn settings_now(&self) -> ProjectSettings {
10640 self.settings.clone()
10641 }
10642
10643 /// One undo step for a change to the project's own settings: `from` is the
10644 /// state the change is from and `now` the one it leaves behind. The entry
10645 /// pushed holds `from`, while the copy kept here is `now` -- so the next
10646 /// lane edit's own entry carries the canvas and the rate really in force
10647 /// rather than the ones before the pick. The lanes the entry holds are the
10648 /// ones in place at the call: a settings door leaves them alone and may
10649 /// take this step after its change, and one that moves them
10650 /// ([`Project::retime`] on a rate change) takes it before, with `now` equal
10651 /// to `from`, mirroring the new state afterwards
10652 /// ([`Project::mirror_settings`]).
10653 pub(crate) fn push_settings_step(&mut self, from: ProjectSettings, now: ProjectSettings) {
10654 self.settle();
10655 self.settings = from;
10656 self.snapshot();
10657 self.settings = now;
10658 }
10659
10660 /// Keeps `now` as this project's copy of its own settings, without a step:
10661 /// the second half of a settings door that had to take its step before the
10662 /// change.
10663 pub(crate) fn mirror_settings(&mut self, now: ProjectSettings) {
10664 self.settle();
10665 self.settings = now;
10666 }
10667
10668 /// Every part of the project that an edit can change, as comparable
10669 /// values: what the sweep's undo round-trip asks "byte identical?" of.
10670 #[cfg(test)]
10671 pub(crate) fn parts(&self) -> SweepParts {
10672 SweepParts(
10673 self.sources.len(),
10674 self.lanes
10675 .iter()
10676 .map(|l| (l.kind, l.clips.clone()))
10677 .collect(),
10678 self.lanes.iter().map(|l| l.subs.clone()).collect(),
10679 self.subtitles.clone(),
10680 self.settings.clone(),
10681 )
10682 }
10683
10684 /// Restore everything from before the last successful edit -- the lanes,
10685 /// the subtitle palette, the project's own settings and the sources (a
10686 /// relink is undone by the old path coming back). `false` when there
10687 /// is nothing left to undo. Pushes what was just left onto the redo stack,
10688 /// so [`Project::redo`] can walk forward again.
10689 pub fn undo(&mut self) -> bool {
10690 self.settle();
10691 match self.history.pop() {
10692 Some(prev) => {
10693 self.batch_snapped = false;
10694 self.pending = None;
10695 let displaced = self.swap_state(prev);
10696 self.redo.push(displaced);
10697 true
10698 }
10699 None => false,
10700 }
10701 }
10702
10703 /// Restore everything from before the last [`Project::undo`] -- the
10704 /// mirror of `undo`, walking the redo stack it fills. `false` when there
10705 /// is nothing left to redo, which is also true after any fresh edit: a
10706 /// new [`Project::snapshot`] clears the branch `undo` left behind.
10707 pub fn redo(&mut self) -> bool {
10708 self.settle();
10709 match self.redo.pop() {
10710 Some(next) => {
10711 self.batch_snapped = false;
10712 self.pending = None;
10713 let displaced = self.swap_state(next);
10714 self.history.push(displaced);
10715 true
10716 }
10717 None => false,
10718 }
10719 }
10720
10721 /// Puts `to` back as the project's state and returns the state it replaced,
10722 /// as the snapshot an undo or redo of that replacement restores.
10723 fn swap_state(&mut self, to: Snapshot) -> Snapshot {
10724 let sources = restored_sources(to.sources, &self.sources);
10725 let displaced = Snapshot {
10726 revision: std::mem::replace(&mut self.revision, to.revision),
10727 label: to.label.clone(),
10728 lanes: std::mem::replace(&mut self.lanes, to.lanes),
10729 subtitles: self.subtitles.clone(),
10730 cue_edits: self.cue_edits.clone(),
10731 cue_adds: self.cue_adds.clone(),
10732 titles: self.titles.clone(),
10733 chapters: self.chapters.clone(),
10734 markers: self.markers.clone(),
10735 settings: self.settings.clone(),
10736 sources: std::mem::replace(&mut self.sources, sources),
10737 bins: std::mem::replace(&mut self.bins, to.bins),
10738 seq: std::mem::replace(&mut self.seq, to.seq),
10739 };
10740 self.flat.clear();
10741 self.subtitles = to.subtitles;
10742 self.cue_edits = to.cue_edits;
10743 self.cue_adds = to.cue_adds;
10744 self.titles = to.titles;
10745 self.chapters = to.chapters;
10746 self.markers = to.markers;
10747 self.settings = to.settings;
10748 displaced
10749 }
10750
10751 /// Half-open `(source, start, end)` segments in *source* seconds, from
10752 /// `timeline_frame` to the end of the timeline -- the play list for the
10753 /// audio worker, read off **`A1`**. A `None` source is a gap: the
10754 /// worker synthesises that many seconds of silence, which is what keeps the
10755 /// audio master clock counting across a hole instead of stalling on it.
10756 /// The first entry is partial when the position is mid-clip. Empty when the
10757 /// position is past the end or `fps` is not usable.
10758 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
10759 self.lane_segments_from(Lane::A1, timeline_frame, fps)
10760 }
10761
10762 /// [`segments_from`](Project::segments_from) for a named lane.
10763 pub fn lane_segments_from(
10764 &self,
10765 lane: Lane,
10766 timeline_frame: u32,
10767 fps: f64,
10768 ) -> Vec<(Option<usize>, f64, f64)> {
10769 if !(fps.is_finite() && fps > 0.0) {
10770 return Vec::new();
10771 }
10772 self.spans_from(lane, timeline_frame)
10773 .iter()
10774 .map(|span| match span.from {
10775 // A clip's window is in *source* seconds: where in the file it
10776 // reads from, which a delete before it never shifts. How many
10777 // source frames that is, is the span's own arithmetic -- at a
10778 // speed it is not the timeline length ([`Span::source_len`]).
10779 Some(_) => {
10780 let (source, lo, hi) = span.source_window().expect("a clip's span");
10781 (Some(source), f64::from(lo) / fps, f64::from(hi) / fps)
10782 }
10783 // A gap has no file, so all it can say is how long it is.
10784 None => (None, 0.0, f64::from(span.len) / fps),
10785 })
10786 .collect()
10787 }
10788
10789 /// One play list per audio lane that *holds* something, in display order --
10790 /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
10791 /// what an export asks how many lanes it would have to mix.
10792 ///
10793 /// Never empty: a timeline whose audio lanes are all empty (or which has no
10794 /// audio lane at all) still yields one all-gap list, so it plays silence
10795 /// against a master clock exactly as it did before there were lanes to
10796 /// count. Lanes with nothing on them are left out rather than mixed in as
10797 /// silence: they would cost a decode thread each and add zero.
10798 pub fn audio_segments_from(
10799 &self,
10800 timeline_frame: u32,
10801 fps: f64,
10802 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
10803 self.audio_lanes()
10804 .into_iter()
10805 .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
10806 .collect()
10807 }
10808
10809 /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
10810 /// builds a play list for, in the same order. Public because everything
10811 /// asked per audio lane -- which clip a segment's equalizer belongs to,
10812 /// which lane an mp4 export would copy -- has to read the very list the
10813 /// sound comes off, or the two answers drift apart (which is exactly how an
10814 /// `A2`-only project once exported silently, ledger).
10815 pub fn audio_lanes(&self) -> Vec<Lane> {
10816 let lanes: Vec<Lane> = self
10817 .lanes()
10818 .into_iter()
10819 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
10820 .collect();
10821 match lanes.is_empty() {
10822 // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
10823 // no sound still plays silence against the master clock.
10824 true => vec![Lane::A1],
10825 false => lanes,
10826 }
10827 }
10828
10829 /// The rate each of [`audio_segments_from`](Project::audio_segments_from)'s
10830 /// segments plays at, and how long the timeline gives it: the same lanes in
10831 /// the same order, one entry per segment, `None` for a segment at real time
10832 /// -- which is every segment of a project nobody has speeded, and the path
10833 /// the audio worker leaves bit-identical.
10834 ///
10835 /// A parallel list for [`audio_eqs_from`](Project::audio_eqs_from)'s reason:
10836 /// the segment tuple is what every opener and a dozen tests speak, and a
10837 /// rate is not part of *which samples* a segment names.
10838 ///
10839 /// The seconds are what makes a resample exact: a segment's own window
10840 /// resolves to whole source frames, and dividing that by the rate would
10841 /// leave each clip a fraction of a frame short or long -- a drift that grows
10842 /// clip by clip. Told how much timeline it owes, the worker pads or trims
10843 /// the last few samples of each segment instead, so the sound stays locked
10844 /// to the picture however many speeded cuts it walks through.
10845 pub fn audio_speeds_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Stretch>>> {
10846 self.audio_lanes()
10847 .into_iter()
10848 .map(|lane| self.lane_speeds_from(lane, timeline_frame, fps))
10849 .collect()
10850 }
10851
10852 /// [`audio_speeds_from`](Project::audio_speeds_from) for one lane, matching
10853 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
10854 /// same walk, same `fps` refusal.
10855 pub fn lane_speeds_from(
10856 &self,
10857 lane: Lane,
10858 timeline_frame: u32,
10859 fps: f64,
10860 ) -> Vec<Option<Stretch>> {
10861 if !(fps.is_finite() && fps > 0.0) {
10862 return Vec::new();
10863 }
10864 self.spans_from(lane, timeline_frame)
10865 .iter()
10866 .map(|span| {
10867 // A ramp's `step` is its mean rate over the span (the source it reads
10868 // over the timeline it fills), the fallback; the stretch follows the
10869 // ramp itself through `ramp`.
10870 let ramped = span.ramp.is_some();
10871 let step = match span.ramp {
10872 Some(_) => f64::from(span.source_len()) / f64::from(span.len),
10873 None => span.speed.as_f64(),
10874 };
10875 (ramped || !span.speed.is_normal() || span.reverse || span.pitch != 0).then(|| Stretch {
10876 step,
10877 timeline_secs: f64::from(span.len) / fps,
10878 reverse: span.reverse,
10879 ramp: span.ramp,
10880 fps,
10881 pitch: span.pitch,
10882 })
10883 })
10884 .collect()
10885 }
10886
10887 /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
10888 /// segments plays through: the same lanes in the same order, one entry per
10889 /// segment, `None` where the segment is a gap or its clip plays flat.
10890 ///
10891 /// A parallel list rather than a fourth element of the segment tuple: that
10892 /// tuple is what every opener, the packet-copy path and a dozen tests speak,
10893 /// and an effect is not part of *which samples* a segment names. A short
10894 /// list therefore means "flat from here on" rather than a length mismatch --
10895 /// see [`crate::AudioSession::open_mixed_streams_eq`].
10896 pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
10897 self.audio_lanes()
10898 .into_iter()
10899 .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
10900 .collect()
10901 }
10902
10903 /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
10904 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
10905 /// same walk, same `fps` refusal, so the two lists cannot come out different
10906 /// lengths.
10907 pub fn lane_eqs_from(
10908 &self,
10909 lane: Lane,
10910 timeline_frame: u32,
10911 fps: f64,
10912 ) -> Vec<Option<EqParams>> {
10913 if !(fps.is_finite() && fps > 0.0) {
10914 return Vec::new();
10915 }
10916 self.spans_from(lane, timeline_frame)
10917 .iter()
10918 // A span off a clip covers that clip's frames and no others, so its
10919 // own start names the clip -- the index a [`Span`] does not carry.
10920 .map(|span| {
10921 self.map(lane, span.start)
10922 .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
10923 })
10924 .collect()
10925 }
10926
10927 /// The fade envelope each of [`audio_segments_from`](Project::audio_segments_from)'s
10928 /// segments plays through: the same lanes in the same order, one entry per
10929 /// segment, `None` where the segment is a gap or its clip has neither a
10930 /// [`Clip::fade_in`] nor a [`Clip::fade_out`]. Parallel list for
10931 /// [`audio_eqs_from`](Project::audio_eqs_from)'s reason.
10932 pub fn audio_fades_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<Fade>>> {
10933 self.audio_lanes()
10934 .into_iter()
10935 .map(|lane| self.lane_fades_from(lane, timeline_frame, fps))
10936 .collect()
10937 }
10938
10939 /// [`audio_fades_from`](Project::audio_fades_from) for one lane, matching
10940 /// [`lane_segments_from`](Project::lane_segments_from) entry for entry.
10941 pub fn lane_fades_from(&self, lane: Lane, timeline_frame: u32, fps: f64) -> Vec<Option<Fade>> {
10942 if !(fps.is_finite() && fps > 0.0) {
10943 return Vec::new();
10944 }
10945 let lane_pan = self.lane_pan(lane);
10946 self.spans_from(lane, timeline_frame)
10947 .iter()
10948 .map(|span| {
10949 let (idx, _) = self.map(lane, span.start)?;
10950 let clip = self.lane(lane).get(idx)?;
10951 (clip.fade_in > 0
10952 || clip.fade_out > 0
10953 || clip.gain_db != 0.0
10954 || clip.pan != 0
10955 || lane_pan != 0.0
10956 || !clip.gain_keys.is_empty())
10957 .then(|| Fade {
10958 // `span.len` is the clip's own remaining frames from
10959 // `span.start` on -- shorter than `clip.frames()` only
10960 // when this is the first span of a seek mid-clip.
10961 elapsed: clip.frames().saturating_sub(span.len),
10962 fade_in: clip.fade_in,
10963 fade_out: clip.fade_out,
10964 total: clip.frames(),
10965 gain: db_to_linear(clip.gain_db),
10966 pan: pan_gains(clip.pan_value(), lane_pan),
10967 curve: clip_curve(clip),
10968 })
10969 })
10970 .collect()
10971 }
10972
10973 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
10974 /// it has decided it will succeed -- a refusal must not cost an undo step.
10975 /// Clears the redo stack: a fresh edit branches off from here, so whatever
10976 /// `undo` had left to redo is no longer where this edit leads back to.
10977 fn snapshot(&mut self) {
10978 self.flat.clear();
10979 if self.batching && self.batch_snapped {
10980 // The open batch already holds its one step, taken before its first edit.
10981 self.redo.clear();
10982 self.revision = next_revision();
10983 return;
10984 }
10985 // A no-op left on top is dropped first, so it never stacks as a step of its own,
10986 // evicts one, or clears a redo branch it did not displace.
10987 self.settle();
10988 let evicted = match !self.hold_cap && self.history.len() == HISTORY_CAP {
10989 true => Some(self.history.remove(0)),
10990 false => None,
10991 };
10992 let redo = std::mem::take(&mut self.redo);
10993 self.pending = Some(PendingStep { redo, evicted });
10994 self.pushes += 1;
10995 self.history.push(Snapshot {
10996 revision: self.revision,
10997 label: None,
10998 lanes: self.lanes.clone(),
10999 subtitles: self.subtitles.clone(),
11000 cue_edits: self.cue_edits.clone(),
11001 cue_adds: self.cue_adds.clone(),
11002 titles: self.titles.clone(),
11003 chapters: self.chapters.clone(),
11004 markers: self.markers.clone(),
11005 settings: self.settings.clone(),
11006 sources: self.sources.clone(),
11007 bins: self.bins.clone(),
11008 seq: self.seq.clone(),
11009 });
11010 self.batch_snapped = self.batching;
11011 self.revision = next_revision();
11012 }
11013
11014 /// Whether the project is exactly the state the newest undo step restores.
11015 /// Every field a step holds is compared, the sources in full (their own `==`
11016 /// ignores the library's star and bin, which an edit may change).
11017 fn matches_newest_step(&self) -> bool {
11018 let Some(top) = self.history.last() else {
11019 return false;
11020 };
11021 let same_sources = top.sources.len() == self.sources.len()
11022 && top.sources.iter().zip(&self.sources).all(|(a, b)| {
11023 a == b && a.fav == b.fav && a.bin == b.bin
11024 });
11025 top.lanes == self.lanes
11026 && top.subtitles == self.subtitles
11027 && top.cue_edits == self.cue_edits
11028 && top.cue_adds == self.cue_adds
11029 && top.titles == self.titles
11030 && top.chapters == self.chapters
11031 && top.markers == self.markers
11032 && top.settings == self.settings
11033 && same_sources
11034 && top.bins == self.bins
11035 && top.seq == self.seq
11036 }
11037
11038 /// Takes back the step this method's own [`Project::snapshot`] pushed, when
11039 /// the method refuses after it has already changed things. Unlike
11040 /// [`Project::undo`] it does not settle first: a refused edit that changed
11041 /// nothing must still take back its own step, not an earlier real one. The
11042 /// redo branch the snapshot displaced comes back exactly as it was.
11043 fn roll_back_snapshot(&mut self) {
11044 let Some(pending) = self.pending.take() else {
11045 self.undo();
11046 return;
11047 };
11048 let Some(prev) = self.history.pop() else {
11049 return;
11050 };
11051 self.swap_state(prev);
11052 self.redo = pending.redo;
11053 if let Some(old) = pending.evicted {
11054 self.history.insert(0, old);
11055 }
11056 self.pushes = self.pushes.saturating_sub(1);
11057 self.batch_snapped = false;
11058 }
11059
11060 /// The pending step, when it is a no-op that [`Project::settle`] would drop.
11061 /// Every reader looks through it, so a no-op never shows as a step, a new
11062 /// revision or a cleared redo branch, whether or not anything has settled it yet.
11063 fn settling_no_op(&self) -> Option<&PendingStep> {
11064 self.pending.as_ref().filter(|_| self.matches_newest_step())
11065 }
11066
11067 /// Takes back the step the last edit pushed when that edit left the project
11068 /// as it was: no undo step, the revision it started from, and the redo branch
11069 /// it displaced put back. Nothing is dropped unless the step is the newest
11070 /// one this project pushed and the state matches it exactly. Outside a batch
11071 /// the step is then settled, so a later edit cannot pick it up. Every snapshot,
11072 /// undo and redo settles first, so a no-op is gone before anything builds on it.
11073 pub(crate) fn settle(&mut self) {
11074 if self.pending.is_some() && self.matches_newest_step() {
11075 let (Some(prev), Some(pending)) = (self.history.pop(), self.pending.take()) else {
11076 return;
11077 };
11078 self.revision = prev.revision;
11079 self.redo = pending.redo;
11080 if let Some(old) = pending.evicted {
11081 self.history.insert(0, old);
11082 }
11083 self.pushes = self.pushes.saturating_sub(1);
11084 self.batch_snapped = false;
11085 self.flat.clear();
11086 }
11087 if !self.batching {
11088 self.pending = None;
11089 }
11090 }
11091
11092 /// Starts a batch: until [`Project::end_batch`], every edit shares one undo
11093 /// step, the snapshot taken before the batch's first edit. Idempotent while open.
11094 pub fn begin_batch(&mut self) {
11095 if !self.batching {
11096 self.batching = true;
11097 self.batch_snapped = false;
11098 }
11099 }
11100
11101 /// Ends the batch [`Project::begin_batch`] opened. The next edit takes its own step.
11102 pub fn end_batch(&mut self) {
11103 if self.batching {
11104 self.settle();
11105 }
11106 self.batching = false;
11107 self.batch_snapped = false;
11108 self.pending = None;
11109 }
11110
11111 fn new_link(&mut self) -> u32 {
11112 let id = self.next_link;
11113 self.next_link = self.next_link.saturating_add(1);
11114 id
11115 }
11116}
11117
11118/// The handle of every lane, in storage order -- the one definition of what
11119/// [`Lane::ord`] counts.
11120fn handles(lanes: &[LaneData]) -> Vec<Lane> {
11121 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
11122 lanes
11123 .iter()
11124 .map(|l| match l.kind {
11125 LaneKind::Video => {
11126 video += 1;
11127 Lane::new(LaneKind::Video, video - 1)
11128 }
11129 LaneKind::Audio => {
11130 audio += 1;
11131 Lane::new(LaneKind::Audio, audio - 1)
11132 }
11133 LaneKind::Subtitle => {
11134 subtitle += 1;
11135 Lane::new(LaneKind::Subtitle, subtitle - 1)
11136 }
11137 })
11138 .collect()
11139}
11140
11141/// The one law a caption re-time scales by: frame `f` moves about the held
11142/// clip's own start by the held clip's old-to-new rate ratio. [`write_speed`]
11143/// commits it, [`Project::speeded_playhead`] previews it -- both build their
11144/// [`TimelineMap`] piece from this single answer so the two cannot drift
11145/// apart by a frame the way they once did.
11146fn scaled_caption_frame(held_start: u32, held_old: f64, new: f64, f: u32) -> u32 {
11147 (f64::from(held_start) + (f64::from(f) - f64::from(held_start)) * held_old / new)
11148 .round()
11149 .clamp(0., f64::from(u32::MAX)) as u32
11150}
11151
11152/// Where in the source a clip's `clip_frame`th timeline frame plays, fractional:
11153/// its in-point plus the speed's integral up to that frame. The one place the two
11154/// frame spaces meet, so a speed cannot be applied twice or forgotten in one of
11155/// them. At a constant speed the position is whole (the floored
11156/// [`Speed::source_at`]), so `floor` of it is that path's frame exactly; with a
11157/// ramp ([`Clip::speed_keys`]) it is the continuous integral and the frame is its
11158/// floor.
11159pub fn source_pos(clip: &Clip, clip_frame: u32) -> f64 {
11160 let offset = if clip.speed_keys.is_empty() {
11161 f64::from(clip.speed.source_at(clip_frame))
11162 } else {
11163 ramp_source_at(&clip.speed_keys, f64::from(clip_frame))
11164 };
11165 match clip.reversed {
11166 // Walked from the window's last frame down. The whole frames travelled are
11167 // what is mirrored (`out - 1 - floor`), so a ramp's fraction cannot lift the
11168 // floor of the frame shown, and the first frame is the last one of the window.
11169 true => f64::from(clip.out_frame - 1) - offset.floor() + offset.fract(),
11170 false => f64::from(clip.in_frame) + offset,
11171 }
11172}
11173
11174/// Where the source-keyed things of a clip (its placement and volume keys) are read
11175/// at `timeline_frame`: the playing source position, fractional. At a constant
11176/// speed this is its own expression, so an unramped, unreversed clip is bit-identical
11177/// to what it was before there were ramps.
11178/// The source position a key is sampled at: [`key_pos`] rounded to a whole frame,
11179/// the frame [`Project::key_source_frame`] writes a key at. A key is read back
11180/// exactly where it was written; sampling the fraction would blend it with its
11181/// neighbour (a typed 40% on a 1.5x clip reads 41%).
11182pub(crate) fn key_sample_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11183 key_pos(clip, timeline_frame).round()
11184}
11185
11186fn key_pos(clip: &Clip, timeline_frame: u32) -> f64 {
11187 let offset = timeline_frame.saturating_sub(clip.start);
11188 match (clip.speed_keys.is_empty(), clip.reversed) {
11189 (true, false) => f64::from(clip.in_frame) + f64::from(offset) * clip.speed.as_f64(),
11190 (true, true) => f64::from(clip.out_frame - 1) - f64::from(offset) * clip.speed.as_f64(),
11191 (false, false) => source_pos(clip, offset),
11192 // Continuous, unlike [`source_pos`]'s floor-exact walk: a key is interpolated,
11193 // and a saw-toothed position would make it jump.
11194 (false, true) => {
11195 f64::from(clip.out_frame - 1) - ramp_source_at(&clip.speed_keys, f64::from(offset))
11196 }
11197 }
11198}
11199
11200/// Which source frame a clip plays at `timeline_frame` -- [`source_pos`] floored.
11201/// Clamped inside the clip's own range: rounding at a slow rate can put the last
11202/// timeline frame of a clip a frame past its out-point, and a source frame outside
11203/// the range is one the next clip owns.
11204fn source_frame(c: &Clip, timeline_frame: u32) -> u32 {
11205 (source_pos(c, timeline_frame - c.start).floor() as u32).clamp(c.in_frame, c.out_frame - 1)
11206}
11207
11208/// The span a clip contributes from `timeline_frame` on: its speed field, and its ramp
11209/// when it has one, based at the span's own start.
11210pub(crate) fn span_speed_of(c: &Clip, timeline_frame: u32) -> (Speed, Option<SpeedRamp>) {
11211 if c.speed_keys.is_empty() {
11212 (c.speed, None)
11213 } else {
11214 let base = timeline_frame - c.start;
11215 (Speed::NORMAL, Some(SpeedRamp::new(&c.speed_keys, base)))
11216 }
11217}
11218
11219/// The tiny interface `Clip` and `SubClip` share for gap maths. Keeping the gap
11220/// finder generic makes the subtitle path use the same bounded-hole rules as
11221/// media lanes without teaching the media-specific take logic about captions.
11222trait GapPlacement {
11223 fn start_frame(&self) -> u32;
11224 fn end_frame(&self) -> u32;
11225}
11226
11227impl GapPlacement for Clip {
11228 fn start_frame(&self) -> u32 {
11229 self.start
11230 }
11231
11232 fn end_frame(&self) -> u32 {
11233 self.end()
11234 }
11235}
11236
11237impl GapPlacement for SubClip {
11238 fn start_frame(&self) -> u32 {
11239 self.start
11240 }
11241
11242 fn end_frame(&self) -> u32 {
11243 self.end()
11244 }
11245}
11246
11247/// Index of the placement covering `frame`, or `None` for a gap or past the
11248/// end. Binary search: the sorted-disjoint invariant is what makes it legal.
11249fn at<T: GapPlacement>(items: &[T], frame: u32) -> Option<usize> {
11250 let idx = items
11251 .partition_point(|item| item.start_frame() <= frame)
11252 .checked_sub(1)?;
11253 (frame < items[idx].end_frame()).then_some(idx)
11254}
11255
11256/// The empty stretch of `items` covering `frame`, as `(start, len)` -- `None`
11257/// when `frame` is inside a placement, or past the last one. Sorted-disjoint
11258/// invariant like [`at`]: the first placement whose start is past `frame` is
11259/// the far wall, and the last one that ends at or before `frame` (or the
11260/// timeline's own head, `0`, when there is none) is the near one.
11261fn gap<T: GapPlacement>(items: &[T], frame: u32) -> Option<(u32, u32)> {
11262 if at(items, frame).is_some() {
11263 return None;
11264 }
11265 let idx = items.partition_point(|item| item.start_frame() <= frame);
11266 let next = items.get(idx)?;
11267 let start = idx.checked_sub(1).map_or(0, |i| items[i].end_frame());
11268 Some((start, next.start_frame() - start))
11269}
11270
11271/// Every bounded hole in `items`, left to right. The tail after the last
11272/// placement is deliberately absent: there is no later placement for a ripple
11273/// to bring back.
11274fn gaps<T: GapPlacement>(items: &[T]) -> Vec<(u32, u32)> {
11275 let mut out = Vec::new();
11276 let mut next = 0;
11277 for item in items {
11278 if item.start_frame() > next {
11279 out.push((next, item.start_frame() - next));
11280 }
11281 next = item.end_frame();
11282 }
11283 out
11284}
11285
11286/// The clip's gain envelope in clip-relative timeline frames, or `None` when it
11287/// has no points. Source frame `s` is reached `(s - in_frame) / speed` timeline
11288/// frames in, which is exact because a speed is one linear rate.
11289fn clip_curve(clip: &Clip) -> Option<std::sync::Arc<[(f64, f32, KeyEase)]>> {
11290 if clip.gain_keys.is_empty() {
11291 return None;
11292 }
11293 let step = clip.speed.as_f64();
11294 let base = f64::from(clip.in_frame);
11295 let mut curve: Vec<(f64, f32, KeyEase)> = match clip.reversed {
11296 // The far end of the window is the clip's head, so the points are walked from
11297 // there and come out in time order the other way about.
11298 true => {
11299 let top = f64::from(clip.out_frame - 1);
11300 clip.gain_keys
11301 .iter()
11302 .enumerate()
11303 .rev()
11304 .map(|(n, k)| {
11305 // The segment that arrived at a point is the one that now leaves it.
11306 let ease = if n > 0 { clip.gain_keys[n - 1].ease } else { k.ease };
11307 ((top - f64::from(k.at)) / step, k.db, ease)
11308 })
11309 .collect()
11310 }
11311 false => clip
11312 .gain_keys
11313 .iter()
11314 .map(|k| ((f64::from(k.at) - base) / step, k.db, k.ease))
11315 .collect(),
11316 };
11317 curve.shrink_to_fit();
11318 Some(curve.into())
11319}
11320
11321/// `keys` walked from the far end of a window whose last frame is `top`, in the
11322/// order a reversed clip plays them: each point at source frame `p` moves to
11323/// `top - p`, and each segment keeps the easing it had, now leaving the point at
11324/// its other end. A point the mirror would put before frame 0 is dropped -- it lay
11325/// far outside the window, where nothing reads it.
11326fn mirrored<K: Clone>(
11327 keys: &[K],
11328 top: i64,
11329 at: impl Fn(&K) -> u32,
11330 ease: impl Fn(&K) -> KeyEase,
11331 with: impl Fn(&K, u32, KeyEase) -> K,
11332) -> Vec<K> {
11333 keys.iter()
11334 .enumerate()
11335 .rev()
11336 .filter_map(|(n, k)| {
11337 // The segment that arrived at this point is the one that now leaves it.
11338 let e = if n > 0 { ease(&keys[n - 1]) } else { ease(k) };
11339 Some(with(k, u32::try_from(top - i64::from(at(k))).ok()?, e))
11340 })
11341 .collect()
11342}
11343
11344/// Re-keys `c`'s source-keyed animation after its direction flipped: each point at
11345/// source frame `p` moves to `in + out - 1 - p`, the same footage frame seen from the
11346/// other end of the window, so the point stays on the timeline frame it was on.
11347fn mirror_keys(c: &mut Clip) {
11348 let top = i64::from(c.in_frame) + i64::from(c.out_frame) - 1;
11349 c.gain_keys = mirrored(&c.gain_keys, top, |k| k.at, |k| k.ease, |k, at, ease| GainKey { at, ease, ..*k });
11350 c.transform_keys =
11351 mirrored(&c.transform_keys, top, |k| k.at, |k| k.ease, |k, at, ease| TransformKey { at, ease, ..*k });
11352 c.opacity_keys = mirrored(&c.opacity_keys, top, |k| k.at, |k| k.ease, |k, at, ease| OpacityKey { at, ease, ..*k });
11353 c.color_keys = mirrored(&c.color_keys, top, |k| k.at, |k| k.ease, |k, at, ease| ColorKey { at, ease, ..*k });
11354 for e in &mut c.effects {
11355 e.keys = mirrored(&e.keys, top, |k| k.at, |k| k.ease, |k, at, ease| crate::effects::MaskKey { at, ease, ..*k });
11356 }
11357}
11358
11359/// Index of the clip `frame` falls *strictly inside*, i.e. the one a split
11360/// there would cut in two. A placement's own first frame is not inside it.
11361fn splittable(clips: &[Clip], frame: u32) -> Option<usize> {
11362 let idx = at(clips, frame)?;
11363 // ...and, on a speeded clip, one its rate can actually address
11364 // ([`Speed::split_at`]): a cut between two showings of one source frame
11365 // would leave halves that no longer add up to the clip that was cut.
11366 (frame > clips[idx].start)
11367 .then_some(idx)
11368 .filter(|&idx| split_source(&clips[idx], frame).is_some())
11369}
11370
11371/// Where in the source a split of `c` at `frame` cuts, or `None` when the clip's
11372/// rate cannot address that frame.
11373fn split_source(c: &Clip, frame: u32) -> Option<u32> {
11374 if !c.speed_keys.is_empty() {
11375 // A reversed ramp is not cut yet: its far end would need the ramp mirrored.
11376 if c.reversed {
11377 return None;
11378 }
11379 return ramp_split(&c.speed_keys, c.len(), frame - c.start).map(|(src, _, _)| c.in_frame + src);
11380 }
11381 c.speed.split_at(c.len(), frame - c.start).map(|src| match c.reversed {
11382 // The head of a reversed clip is the window's far end, so the cut is that
11383 // far down from the out-point.
11384 true => c.out_frame - src,
11385 false => c.in_frame + src,
11386 })
11387}
11388
11389/// The speed keys each half of `c` keeps when it is cut at `frame`. Both empty for a
11390/// constant rate, which keeps its own [`Speed`] on both halves.
11391fn split_keys(c: &Clip, frame: u32) -> (Vec<SpeedKey>, Vec<SpeedKey>) {
11392 if c.speed_keys.is_empty() {
11393 return (Vec::new(), Vec::new());
11394 }
11395 match ramp_split(&c.speed_keys, c.len(), frame - c.start) {
11396 Some((_, head, tail)) => (head, tail),
11397 None => (Vec::new(), Vec::new()),
11398 }
11399}
11400
11401/// Where a ramped clip of `src_len` source frames can be cut at its clip-relative timeline
11402/// frame `off`, and the keys each half keeps. The source frame the tail starts at is
11403/// relative to the clip's in-point. `None` where the cut would not add up in whole frames
11404/// on both halves -- the ramp's own version of what [`Speed::split_at`] asks of a constant
11405/// rate. Reads at which the ramp lands near a frame boundary answer; the others do not.
11406pub fn ramp_split(keys: &[SpeedKey], src_len: u32, off: u32) -> Option<(u32, Vec<SpeedKey>, Vec<SpeedKey>)> {
11407 let len = ramp_frames(keys, src_len);
11408 if off == 0 || off >= len {
11409 return None;
11410 }
11411 let src = ramp_source_at(keys, f64::from(off)).round();
11412 if src < 1. || src >= f64::from(src_len) {
11413 return None;
11414 }
11415 let src = src as u32;
11416 let head = ramp_keys_until(keys, off);
11417 let tail = ramp_keys_from(keys, off);
11418 let whole = valid_speed_keys(&head)
11419 && valid_speed_keys(&tail)
11420 && ramp_frames(&head, src) == off
11421 && ramp_frames(&tail, src_len - src) == len - off;
11422 whole.then_some((src, head, tail))
11423}
11424
11425/// The keys of the part of a ramped clip up to clip-relative frame `cut`: the keys before
11426/// it, and the speed there as the last one when the ramp goes on past it. The ramp is held
11427/// to `cut` exactly as the whole ramp plays there, so the head's length comes back as `cut`.
11428pub fn ramp_keys_until(keys: &[SpeedKey], cut: u32) -> Vec<SpeedKey> {
11429 let mut out: Vec<SpeedKey> = keys.iter().copied().filter(|k| k.at < cut).collect();
11430 if keys.iter().any(|k| k.at > cut) {
11431 out.push(SpeedKey { at: cut, speed: ramp_speed_at(keys, cut) });
11432 }
11433 out
11434}
11435
11436/// Index of the first of the two clips a [`Project::regroup`] at `frame` would
11437/// rejoin: they must touch there, and be consecutive frames of one source.
11438fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
11439 let idx = clips.iter().position(|c| c.end() == frame)?;
11440 let next = clips.get(idx + 1)?;
11441 let joined = clips[idx].len() + next.len();
11442 (next.start == frame
11443 && next.source == clips[idx].source
11444 && next.reversed == clips[idx].reversed
11445 && match clips[idx].reversed {
11446 // The halves of a reversed cut swap sides: the head holds the window's
11447 // upper part.
11448 true => clips[idx].in_frame == next.out_frame,
11449 false => next.in_frame == clips[idx].out_frame,
11450 }
11451 // ...at one rate, and one that puts the rejoined clip back in exactly
11452 // the room the two took up: what a split could have produced, which is
11453 // all this undoes.
11454 && next.speed == clips[idx].speed
11455 && clips[idx].speed.frames(joined) == clips[idx].frames() + next.frames())
11456 .then_some(idx)
11457}
11458
11459/// The lane invariant: sorted by `start`, no two placements overlapping, no
11460/// empty placement. Checked at every constructor and asserted after every
11461/// mutation -- the offset model is only tractable while it holds.
11462/// The one thing an equalizer setting may not be: a value the text format
11463/// cannot write and read back as itself. Checked wherever params come in, so
11464/// what an edit produces is always what a save writes and a load reads.
11465fn finite(params: &EqParams) -> bool {
11466 params
11467 .bands
11468 .iter()
11469 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
11470}
11471
11472/// The same for a colour grade: [`crate::color`] itself falls back to identity
11473/// on a non-finite value, but a value that cannot be written and read back as
11474/// itself has no business reaching the model.
11475fn color_finite(p: &ColorParams) -> bool {
11476 let w = &p.look.wheels;
11477 w.lift.iter().chain(&w.gamma).chain(&w.gain).all(|v| v.is_finite())
11478 && p.look.lut_mix.is_finite()
11479 && p.brightness.is_finite()
11480 && p.contrast.is_finite()
11481 && p.saturation.is_finite()
11482 && p.tint.is_finite()
11483}
11484
11485/// The same for a transform: [`crate::scale`] clamps a non-finite value to
11486/// identity at read time, but a value that cannot round-trip has no business
11487/// reaching the model.
11488fn transform_finite(p: &TransformParams) -> bool {
11489 p.pos_x.is_finite()
11490 && p.pos_y.is_finite()
11491 && p.scale.is_finite()
11492 && p.rotate.is_finite()
11493 && p.crop_l.is_finite()
11494 && p.crop_r.is_finite()
11495 && p.crop_t.is_finite()
11496 && p.crop_b.is_finite()
11497 && (0.0..=1.0).contains(&p.opacity)
11498}
11499
11500fn sorted_disjoint(clips: &[Clip]) -> bool {
11501 clips.iter().all(|c| c.out_frame > c.in_frame)
11502 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
11503}
11504
11505/// The very same invariant on a subtitle lane, in that lane's own two units:
11506/// sorted by `start`, no two placements overlapping, no empty placement at
11507/// either end. Asserted after every mutation, exactly as its twin is.
11508fn subs_sorted_disjoint(subs: &[SubClip]) -> bool {
11509 subs.iter()
11510 .all(|s| s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0)
11511 && subs.windows(2).all(|w| w[0].end() <= w[1].start)
11512}
11513
11514/// What `frames` timeline frames are worth in microseconds at `fps`, signed --
11515/// the one conversion between a lane's clock and a cue's, and `0` for a rate
11516/// that is not one (every caller of this has already refused such a rate).
11517fn us_of(frames: i64, fps: f64) -> i64 {
11518 match fps.is_finite() && fps > 0.0 {
11519 true => ((frames as f64) / fps * 1e6).round() as i64,
11520 false => 0,
11521 }
11522}
11523
11524/// **The one function in this file that writes a caption's window.** Every
11525/// composer -- a trim, a split, a ripple, a group follow, a rejoin -- routes
11526/// through it, and the invariant it holds is total:
11527///
11528/// ```text
11529/// 0 <= in_us and in_us < out_us and out_us - in_us <= MAX_WINDOW_US
11530/// ```
11531///
11532/// which is the never-empty invariant plus the width ceiling, restated as one
11533/// shape both ends of it come from. Note that the ceiling bounds a
11534/// **difference**, which is why a per-arm check is not enough and this is:
11535///
11536/// - Growing `out_us` (a tail trim) makes the width larger, so the *upper*
11537/// wall bites.
11538/// - Falling `in_us` (a head trim) makes the width larger too, from the other
11539/// side -- so bounding `in_us` alone, which is what a head trim's own clamp
11540/// (`in_us <= out_us - 1`) does, says nothing at all about the ceiling.
11541/// - A rejoin takes the left half's `in_us` and the right half's `out_us`, and
11542/// the two halves are consecutive in the *source* (that is what
11543/// [`sub_joinable`] requires), so the joined width is the **sum** of two
11544/// legal widths. Each half passes its own door; the whole does not.
11545///
11546/// Three rounds of review each found one more composer this way, so the
11547/// function is the fix rather than any single call site: clamping a new
11548/// caller into shape is a two-line change, and forgetting one is silent.
11549/// `every_window_write_goes_through_set_window` (in the tests below) is the
11550/// other half of that promise -- it scans the file and fails if a write
11551/// appears anywhere else.
11552///
11553/// **Why it clamps where the doors refuse.** The doors -- the parser,
11554/// [`Project::with_subs`], [`Project::place_sub`] -- see a value on the way
11555/// IN, from a file or a foreign caller, where nobody was mid-gesture, so a
11556/// value that wide is named and refused rather than quietly changed. Every
11557/// composer below is an edit a person is watching happen, so the same value is
11558/// clamped to the end of the window: a drag that stops, exactly like the frame
11559/// walls these trims already apply.
11560fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {
11561 let in_us = in_us.max(0);
11562 // The `+ 1` is the never-empty invariant: the window is open, always, so a
11563 // composer that would otherwise clamp it shut lands on one microsecond.
11564 let out_us = out_us.clamp(in_us + 1, in_us.saturating_add(MAX_WINDOW_US));
11565 s.in_us = in_us;
11566 s.out_us = out_us;
11567 debug_assert!(
11568 s.in_us >= 0 && s.out_us > s.in_us && s.out_us - s.in_us <= MAX_WINDOW_US,
11569 "set_window left an illegal window: {:?}",
11570 (s.in_us, s.out_us)
11571 );
11572}
11573
11574/// The two pieces a cue becomes when a window edge at `t_us` falls inside it:
11575/// `(start, end, text)` for the piece before the edge and the one after, the
11576/// words shared between them at the word boundary nearest the point that is the
11577/// same fraction of the words as `t_us` is of the time. A piece with no words is
11578/// left out. A cue with one word has no boundary to divide at, so that word
11579/// stays on the longer side of the edge (ties: the piece before it) and the
11580/// other side is left out too. `None` for a cue with no words at all.
11581fn split_words(c: &crate::subtitle::Cue, t_us: i64) -> Option<Vec<(i64, i64, String)>> {
11582 let text = c.text.as_str();
11583 let mut starts: Vec<usize> = Vec::new();
11584 let mut prev_space = true;
11585 for (i, ch) in text.char_indices() {
11586 let space = ch.is_whitespace();
11587 if !space && prev_space {
11588 starts.push(i);
11589 }
11590 prev_space = space;
11591 }
11592 let n = starts.len();
11593 if n == 0 {
11594 return None;
11595 }
11596 if n == 1 {
11597 let word = text.trim().to_string();
11598 let before = t_us - c.start_us;
11599 let after = c.end_us - t_us;
11600 return Some(if before >= after {
11601 vec![(c.start_us, t_us, word)]
11602 } else {
11603 vec![(t_us, c.end_us, word)]
11604 });
11605 }
11606 let p = (t_us - c.start_us) as f64 / (c.end_us - c.start_us) as f64;
11607 let k = ((p * n as f64).round() as usize).min(n);
11608 let mut out = Vec::with_capacity(2);
11609 if k >= 1 {
11610 let end = if k < n { starts[k] } else { text.len() };
11611 out.push((c.start_us, t_us, text[..end].trim_end().to_string()));
11612 }
11613 if k < n {
11614 out.push((t_us, c.end_us, text[starts[k]..].to_string()));
11615 }
11616 Some(out)
11617}
11618
11619/// [`split_words`] for one edge of a cut. With `both_sides` a one-word cue is
11620/// kept whole on both sides of the point, so the side the cut leaves in its
11621/// window survives: which side that is, only the ripple knows, and
11622/// [`Project::drop_unplaced`] drops the other. Every other cue is
11623/// [`split_words`]' division.
11624fn cut_pieces(c: &crate::subtitle::Cue, t_us: i64, both_sides: bool) -> Option<Vec<(i64, i64, String)>> {
11625 if both_sides && c.text.split_whitespace().count() == 1 {
11626 let word = c.text.trim().to_string();
11627 return Some(vec![(c.start_us, t_us, word.clone()), (t_us, c.end_us, word)]);
11628 }
11629 split_words(c, t_us)
11630}
11631
11632/// [`clear`] for a subtitle lane: removes the timeline frames `[start, end)`,
11633/// dropping what is inside the hole, splitting what straddles it and trimming
11634/// what overlaps an edge. The windows follow the cut by proportion
11635/// ([`SubClip::window_at`]), so what is left says exactly the words it said.
11636fn sub_clear(subs: &mut Vec<SubClip>, start: u32, end: u32) {
11637 sub_clear_with(subs, start, end, &mut |_| (None, None));
11638}
11639
11640/// [`sub_clear`] with the (head, tail) links its pieces carry, as [`clear_with`] has for clips.
11641fn sub_clear_with(subs: &mut Vec<SubClip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
11642 let mut out = Vec::with_capacity(subs.len() + 1);
11643 for s in subs.drain(..) {
11644 if s.end() <= start || s.start >= end {
11645 out.push(s);
11646 continue;
11647 }
11648 if s.start < start {
11649 let cut = s.window_at(start);
11650 let (head_link, _) = links(s.link);
11651 let mut head = SubClip {
11652 frames: start - s.start,
11653 link: head_link,
11654 ..s
11655 };
11656 // `window_at` already answers inside the window, and `set_window`
11657 // is the shape that says so once, for every composer, rather than
11658 // leaving each of them to re-derive it.
11659 set_window(&mut head, s.in_us, cut);
11660 out.push(head);
11661 }
11662 if s.end() > end {
11663 let cut = s.window_at(end);
11664 let (_, tail_link) = links(s.link);
11665 let mut tail = SubClip {
11666 start: end,
11667 frames: s.end() - end,
11668 link: tail_link,
11669 ..s
11670 };
11671 set_window(&mut tail, cut, s.out_us);
11672 out.push(tail);
11673 }
11674 }
11675 *subs = out;
11676}
11677
11678/// [`open_room`] for a subtitle lane: slides everything from `at` on later by
11679/// `len`, splitting a placement that straddles `at` so the two halves end up on
11680/// either side of the hole. A `len` of 0 is that split alone, which is what a
11681/// [`Project::split`] over a subtitle lane is.
11682fn sub_open_room(subs: &mut Vec<SubClip>, at: u32, len: u32) {
11683 if let Some(idx) = subs.iter().position(|s| s.start < at && at < s.end()) {
11684 let s = subs[idx];
11685 let cut = s.window_at(at);
11686 let mut head = SubClip {
11687 frames: at - s.start,
11688 link: None,
11689 ..s
11690 };
11691 set_window(&mut head, s.in_us, cut);
11692 subs[idx] = head;
11693 let mut tail = SubClip {
11694 start: at,
11695 frames: s.end() - at,
11696 link: None,
11697 ..s
11698 };
11699 set_window(&mut tail, cut, s.out_us);
11700 subs.insert(idx + 1, tail);
11701 }
11702 for s in subs.iter_mut().filter(|s| s.start >= at) {
11703 s.start += len;
11704 }
11705}
11706
11707/// [`joinable`] for a subtitle lane: the first of the two placements a
11708/// [`Project::regroup`] at `frame` would rejoin. What a split could have
11709/// produced and nothing else -- they touch on the timeline, they read the same
11710/// track, and the second one's window carries on where the first's stopped.
11711fn sub_joinable(subs: &[SubClip], frame: u32) -> Option<usize> {
11712 let idx = subs.iter().position(|s| s.end() == frame)?;
11713 let next = subs.get(idx + 1)?;
11714 (next.start == frame && next.track == subs[idx].track && next.in_us == subs[idx].out_us)
11715 .then_some(idx)
11716}
11717
11718/// How far one `edge` of the caption at `idx` may travel against its own lane's
11719/// walls alone: the frame arithmetic of [`Project::trim_sub_room`] without the
11720/// rate, which a caption *following* a group's trim does not have to be exact
11721/// about -- its own walls, its own one surviving frame, and nothing that needs
11722/// a clock.
11723fn sub_edge_room(subs: &[SubClip], idx: usize, edge: Edge) -> (u32, u32) {
11724 let s = &subs[idx];
11725 match edge {
11726 Edge::Start => (idx.checked_sub(1).map_or(0, |p| subs[p].end()), s.end() - 1),
11727 Edge::End => (s.start + 1, subs.get(idx + 1).map_or(u32::MAX, |n| n.start)),
11728 }
11729}
11730
11731/// Move one `edge` of `s` to timeline frame `to`, its window following by the
11732/// placement's own proportion -- [`SubClip::window_at`]'s arithmetic, run
11733/// forwards and backwards. The caption a group's trim is carrying has no rate
11734/// of its own and needs none: what one frame of it is worth in microseconds is
11735/// the window it already shows over the frames it already takes.
11736fn write_sub_edge(s: &mut SubClip, edge: Edge, to: u32) {
11737 let per_frame = s.window_us() / i64::from(s.frames.max(1));
11738 // The `saturating_mul` keeps a `SubClip` that reached here without a door
11739 // behind it from wrapping the window negative; `set_window` is what keeps
11740 // the result legal rather than merely finite. This is the group-follow twin
11741 // of [`Project::trim_sub`], and it reaches the same field from both edges --
11742 // so a fix that only walled the primary trim's End arm left the head (and
11743 // the whole group path) open.
11744 let by = |from: u32, to: u32| per_frame.saturating_mul(i64::from(to) - i64::from(from));
11745 match edge {
11746 Edge::Start => {
11747 set_window(s, s.in_us.saturating_add(by(s.start, to)), s.out_us);
11748 s.frames = s.end() - to;
11749 s.start = to;
11750 }
11751 Edge::End => {
11752 set_window(s, s.in_us, s.out_us.saturating_add(by(s.end(), to)));
11753 s.frames = to - s.start;
11754 }
11755 }
11756 debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);
11757}
11758
11759/// The grouping invariant, checked in release at [`Project::from_parts`] and
11760/// asserted by the tests after every edit: a link id names **at most one**
11761/// placement per lane -- a clip on a media lane or a caption on a subtitle
11762/// one, whichever carries it. That is all "these move together" can mean now
11763/// that a group is assembled by hand: the members keep their own spans and
11764/// their own offsets, and what binds them is the id alone.
11765///
11766/// Deliberately *not* a pairing of two lanes, and never a span rule: with N
11767/// lanes a group may run on `V1`, `A1` and a subtitle lane at once, and two
11768/// placements of one group may cover different frames -- the offset-preserving
11769/// group a hand builds with [`Project::group_all`], which a drag moves by one
11770/// delta rather than by one span.
11771///
11772/// A link no other lane carries is legal and is not an error: lifting one half
11773/// of a group ([`Project::lift`]) leaves exactly that, and a save of that
11774/// timeline has to load again.
11775/// [`links_are_consistent`](self::links_are_consistent) for a whole project,
11776/// asked by the sweep suite's universal law.
11777#[cfg(test)]
11778pub(crate) fn links_are_consistent_pub(p: &Project) -> crate::Result<()> {
11779 links_are_consistent(&p.lanes)
11780}
11781
11782/// What a take is, for [`Project::ungroup`]: the halves of one take read the
11783/// same source over the same frames, so they share these four numbers.
11784type TakeKey = (usize, u32, u32, u32);
11785
11786fn take_key(c: &Clip) -> TakeKey {
11787 (c.source, c.start, c.in_frame, c.out_frame)
11788}
11789
11790fn links_are_consistent(lanes: &[LaneData]) -> crate::Result<()> {
11791 let handles = handles(lanes);
11792 for (data, lane) in lanes.iter().zip(&handles) {
11793 for (i, c) in data.clips.iter().enumerate() {
11794 let Some(id) = c.link else { continue };
11795 if data.clips[..i].iter().any(|prev| prev.link == Some(id)) {
11796 return Err(
11797 format!("link {id} names two clips in the {} lane", lane.label()).into(),
11798 );
11799 }
11800 }
11801 // ...and the same for the captions, in their own list on the same lane:
11802 // a subtitle lane holds no `Clip`, so this is the only list a caption's
11803 // id could be doubled on.
11804 for (i, s) in data.subs.iter().enumerate() {
11805 let Some(id) = s.link else { continue };
11806 if data.subs[..i].iter().any(|prev| prev.link == Some(id)) {
11807 return Err(
11808 format!("link {id} names two captions in the {} lane", lane.label()).into(),
11809 );
11810 }
11811 }
11812 }
11813 Ok(())
11814}
11815
11816/// Removes the timeline frames `[start, end)` from `clips`: placements inside
11817/// it go, one straddling it is split in two, one overlapping an edge is
11818/// trimmed. Source frames follow the trim, so what is left plays what it always
11819/// played. Leaves the lane sorted and disjoint.
11820///
11821/// A piece the hole cut is no longer the take its group id names -- and both
11822/// halves of a straddled placement carrying that id would be the same id twice
11823/// in one lane -- so what is cut loses its link (see [`links_are_consistent`]).
11824fn clear(clips: &mut Vec<Clip>, start: u32, end: u32) {
11825 clear_with(clips, start, end, &mut |_| (None, None));
11826}
11827
11828/// [`clear`] with the links the pieces it leaves carry: `links` gives the (head, tail) ids of a clip
11829/// that straddles the hole. `clear` itself gives both none, the detach rule of a delete.
11830fn clear_with(clips: &mut Vec<Clip>, start: u32, end: u32, links: &mut dyn FnMut(Option<u32>) -> (Option<u32>, Option<u32>)) {
11831 let mut out = Vec::with_capacity(clips.len() + 1);
11832 for c in clips.drain(..) {
11833 // Disjoint from the hole: untouched.
11834 if c.end() <= start || c.start >= end {
11835 out.push(c);
11836 continue;
11837 }
11838 // The head that survives in front of the hole -- as much source as fits
11839 // in the room in front of it at this clip's own rate ([`Speed::fit`]),
11840 // which at real time is that room itself. Never *more*: a head that
11841 // outgrew its room would reach into the hole it is being cut out of,
11842 // which is exactly the overlap a slow clip punched at a frame its rate
11843 // cannot address used to leave (at 0.25x a single source frame is four
11844 // timeline frames, and three frames of room hold none of it). `None`
11845 // there means no remainder at all, and the piece simply goes.
11846 if let Some(keep) = c.fit_source(start.saturating_sub(c.start))
11847 && c.start < start
11848 {
11849 let (head, _) = links(c.link);
11850 let mut piece = Clip {
11851 fade_in: 0,
11852 fade_out: 0,
11853 transition_out: 0,
11854 transition_kind: Default::default(),
11855 link: head,
11856 ..c.clone()
11857 };
11858 // What survives in front plays the window's far end when it is reversed.
11859 match c.reversed {
11860 true => piece.in_frame = c.out_frame - keep.min(c.len()),
11861 false => piece.out_frame = c.in_frame + keep.min(c.len()),
11862 }
11863 out.push(piece);
11864 }
11865 // ...and the tail behind it, which keeps reading up to where it would
11866 // have: measured from its out-point for the head's reason, so what it
11867 // occupies still ends where the whole clip did -- and dropped whole on
11868 // the same `None`.
11869 // A ramp's tail restarts at `end`, so its keys are rebased to that frame
11870 // ([`ramp_keys_from`]) and its room is measured with them.
11871 let tail_keys = if c.speed_keys.is_empty() {
11872 Vec::new()
11873 } else {
11874 ramp_keys_from(&c.speed_keys, end.saturating_sub(c.start))
11875 };
11876 let tail_probe = Clip { speed_keys: tail_keys.clone(), ..c.clone() };
11877 if let Some(keep) = tail_probe.fit_source(c.end().saturating_sub(end))
11878 && c.end() > end
11879 {
11880 let (_, tail) = links(c.link);
11881 let mut piece = Clip {
11882 fade_in: 0,
11883 fade_out: 0,
11884 transition_out: 0,
11885 transition_kind: Default::default(),
11886 start: end,
11887 link: tail,
11888 speed_keys: tail_keys,
11889 ..c.clone()
11890 };
11891 match c.reversed {
11892 true => piece.out_frame = c.in_frame + keep.min(c.len()),
11893 false => piece.in_frame = c.out_frame - keep.min(c.len()),
11894 }
11895 out.push(piece);
11896 }
11897 }
11898 *clips = out;
11899}
11900
11901/// Cuts `[at, at + len)` out of the lanes at indices `on` and slides what is
11902/// behind it back -- the body of [`Project::ripple_delete`] (which passes every
11903/// lane) and of every cut a batch ([`Project::cut_regions`]) makes on the lanes
11904/// it was scoped to. No snapshot of its own: whose undo step this is belongs to
11905/// the caller.
11906fn ripple(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32) {
11907 for &i in on {
11908 let clips = &mut lanes[i].clips;
11909 clear(clips, at, at + len);
11910 for c in clips.iter_mut().filter(|c| c.start >= at) {
11911 c.start -= len;
11912 }
11913 debug_assert!(sorted_disjoint(clips));
11914 // The subtitle lanes close the hole with everything else: a caption
11915 // left standing where the picture it belongs to was cut out is the
11916 // desync a lane model exists to make impossible.
11917 let subs = &mut lanes[i].subs;
11918 sub_clear(subs, at, at + len);
11919 for s in subs.iter_mut().filter(|s| s.start >= at) {
11920 s.start -= len;
11921 }
11922 debug_assert!(subs_sorted_disjoint(subs));
11923 }
11924}
11925
11926/// Moves every clip and caption on `lane` that starts at or after `from` by `delta` frames: the
11927/// second half of a ripple trim ([`Project::ripple_trim`]), which closes or opens the hole an edge
11928/// left. No snapshot of its own.
11929fn shift_behind(lane: &mut LaneData, from: u32, delta: i64) {
11930 let step = |s: u32| (i64::from(s) + delta) as u32;
11931 for c in lane.clips.iter_mut().filter(|c| c.start >= from) {
11932 c.start = step(c.start);
11933 }
11934 debug_assert!(sorted_disjoint(&lane.clips));
11935 for s in lane.subs.iter_mut().filter(|s| s.start >= from) {
11936 s.start = step(s.start);
11937 }
11938 debug_assert!(subs_sorted_disjoint(&lane.subs));
11939}
11940
11941/// [`ripple`] for a cut that keeps its takes together: every take it splits keeps its id on the
11942/// piece before the cut, and the pieces after it share one fresh id per take, as the razor's
11943/// split does ([`Project::split_on`]). Only [`Project::cut_regions`] calls it, and that refuses
11944/// any scope that would take one half of a take with it, so every take it splits is whole in scope.
11945fn ripple_keeping_takes(lanes: &mut [LaneData], on: &[usize], at: u32, len: u32, next_link: &mut u32) {
11946 let mut tails: Vec<(u32, u32)> = Vec::new();
11947 let mut links = |old: Option<u32>| -> (Option<u32>, Option<u32>) {
11948 let Some(id) = old else { return (None, None) };
11949 let tail = match tails.iter().find(|(o, _)| *o == id) {
11950 Some(&(_, t)) => t,
11951 None => {
11952 let t = *next_link;
11953 *next_link = next_link.saturating_add(1);
11954 tails.push((id, t));
11955 t
11956 }
11957 };
11958 (Some(id), Some(tail))
11959 };
11960 for &i in on {
11961 let clips = &mut lanes[i].clips;
11962 clear_with(clips, at, at + len, &mut links);
11963 for c in clips.iter_mut().filter(|c| c.start >= at) {
11964 c.start -= len;
11965 }
11966 debug_assert!(sorted_disjoint(clips));
11967 let subs = &mut lanes[i].subs;
11968 sub_clear_with(subs, at, at + len, &mut links);
11969 for s in subs.iter_mut().filter(|s| s.start >= at) {
11970 s.start -= len;
11971 }
11972 debug_assert!(subs_sorted_disjoint(subs));
11973 }
11974}
11975
11976/// Every lane, as the index list the two above take: what "the whole timeline"
11977/// is spelled as, and the scope [`Project::ripple_delete`] and
11978/// [`Project::split`] have always had.
11979fn all_lanes(lanes: &[LaneData]) -> Vec<usize> {
11980 (0..lanes.len()).collect()
11981}
11982
11983/// A caller's region list as a batch may use it: sorted by start, empty entries
11984/// dropped, and touching or overlapping entries merged into one.
11985///
11986/// Overlapping regions are the one thing a batch cannot take -- cutting the
11987/// second would cut frames the first already moved -- and a detector handing
11988/// back two that touch means one silence, not two cuts. Merged rather than
11989/// refused: this is arithmetic on a preview, not a user's mistake.
11990fn tidy(regions: &[(u32, u32)]) -> Vec<(u32, u32)> {
11991 let mut sorted: Vec<(u32, u32)> = regions.iter().copied().filter(|&(_, l)| l > 0).collect();
11992 sorted.sort_by_key(|&(at, _)| at);
11993 let mut out: Vec<(u32, u32)> = Vec::new();
11994 for (at, len) in sorted {
11995 let end = at.saturating_add(len);
11996 match out.last_mut() {
11997 Some(last) if at <= last.0 + last.1 => last.1 = end.saturating_sub(last.0).max(last.1),
11998 _ => out.push((at, len)),
11999 }
12000 }
12001 out
12002}
12003
12004/// Slides everything from `at` on later by `len`, splitting a placement that
12005/// straddles `at` so the two halves end up on either side of the hole. The
12006/// insert half of a rippling paste. The two halves lose the group id for the
12007/// reason [`clear`] gives.
12008fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) {
12009 if let Some(idx) = splittable(clips, at) {
12010 let mut tail = clips[idx].clone();
12011 // The cut in *source* frames, at the clip's own rate. `splittable` has
12012 // already refused a frame the rate cannot address, which is why
12013 // [`Project::paste`] refuses one too rather than opening room inside a
12014 // clip that cannot be cut there.
12015 let cut_at = split_source(&tail, at).expect("splittable said so");
12016 let (head_speed, tail_speed) = split_keys(&tail, at);
12017 tail.speed_keys = tail_speed;
12018 clips[idx].speed_keys = head_speed;
12019 match tail.reversed {
12020 true => {
12021 tail.out_frame = cut_at;
12022 clips[idx].in_frame = cut_at;
12023 }
12024 false => {
12025 tail.in_frame = cut_at;
12026 clips[idx].out_frame = cut_at;
12027 }
12028 }
12029 tail.start = at;
12030 tail.link = None;
12031 clips[idx].link = None;
12032 clips.insert(idx + 1, tail);
12033 }
12034 for c in clips.iter_mut().filter(|c| c.start >= at) {
12035 c.start += len;
12036 }
12037}
12038
12039/// Absolute, symlink-resolved when the file is reachable; the path as given
12040/// when it is not -- an unreadable path still deserves an index, it simply
12041/// dedups by spelling.
12042pub(crate) fn canonical(path: &Path) -> PathBuf {
12043 std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
12044}
12045
12046#[cfg(test)]
12047mod tests {
12048 use super::*;
12049
12050 const FPS: f64 = 30.0;
12051
12052 /// A caption track that ends between two frames places with a window of
12053 /// whole frames: 4.750 s at 30 fps is 143 frames, and its cues keep their
12054 /// times (0.5 s is frame 15, 4.5 s is frame 135) instead of being stretched
12055 /// by 143 / 142.5 as they were when the window was the track's own length.
12056 #[test]
12057 fn a_whole_track_drop_is_not_stretched_by_its_last_frame() {
12058 let sub = SubClip::whole_track(2, 4_750_000, FPS);
12059 assert_eq!((sub.track, sub.start, sub.in_us), (2, 0, 0));
12060 assert_eq!(sub.frames, 143, "the fewest frames that hold the last cue");
12061 assert_eq!(sub.out_us, 4_766_667, "the window is the frames' own length");
12062 let frame_of = |us: i64| f64::from(sub.frames) * us as f64 / sub.window_us() as f64;
12063 for (us, want) in [(500_000i64, 15.0), (750_000, 22.5), (4_500_000, 135.0)] {
12064 assert!((frame_of(us) - want).abs() < 1e-3, "cue at {us} us lands on frame {}", frame_of(us));
12065 }
12066 // The old window (the track's length) put 4.5 s on 135.47 frames.
12067 assert!((4_500_000f64 * 143.0 / 4_750_000.0 - 135.0).abs() > 0.4);
12068 // A track that ends on a frame is that many frames, with no extra one.
12069 let exact = SubClip::whole_track(0, 1_000_000, FPS);
12070 assert_eq!((exact.frames, exact.out_us), (30, 1_000_000));
12071 }
12072 /// Never opened -- `Project` is pure data, so a path that does not exist is
12073 /// simply a path that dedups by spelling.
12074 const FILE: &str = "/nonexistent/a.mp4";
12075 const FILE2: &str = "/nonexistent/b.mp4";
12076
12077 /// A batch is one undo step however many edits it makes, far past the cap; undo takes
12078 /// back the whole batch, and an edit after `end_batch` takes its own step.
12079 #[test]
12080 fn a_batch_is_one_undo_step_past_the_cap() {
12081 let mut p = Project::single(FILE, 1);
12082 let v = p.add_lane(LaneKind::Video);
12083 let base = p.history_len();
12084 p.begin_batch();
12085 for k in 0..150u32 {
12086 assert!(p.place(v, k * 3, clip(k * 3, 0, 3, 0)));
12087 }
12088 p.end_batch();
12089 assert_eq!(p.history_len(), base + 1, "the batch is one step");
12090 assert_eq!(p.lane_clips_pub(v).len(), 150);
12091
12092 assert!(p.undo());
12093 assert!(p.lane_clips_pub(v).is_empty(), "undo takes the whole batch back");
12094 assert_eq!(p.history_len(), base);
12095
12096 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12097 assert_eq!(p.history_len(), base + 1, "an edit outside a batch is its own step");
12098 }
12099
12100 /// Undo inside a batch starts a fresh step for what follows it, so the edits after it
12101 /// are not lost from the history.
12102 #[test]
12103 fn an_undo_inside_a_batch_opens_a_new_step() {
12104 let mut p = Project::single(FILE, 1);
12105 let v = p.add_lane(LaneKind::Video);
12106 let base = p.history_len();
12107 p.begin_batch();
12108 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
12109 assert!(p.undo());
12110 assert!(p.place(v, 0, clip(0, 0, 4, 0)));
12111 p.end_batch();
12112 assert_eq!(p.history_len(), base + 1);
12113 assert!(p.undo());
12114 assert!(p.lane_clips_pub(v).is_empty());
12115 }
12116
12117 /// A contiguous placement, group id ignored: what most assertions compare.
12118 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize) -> Clip {
12119 Clip {
12120 speed_keys: Vec::new(),
12121 reversed: false,
12122 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
12123 angle: Default::default(),
12124 fade_in: 0,
12125 fade_out: 0,
12126 transition_out: 0,
12127 transition_kind: Default::default(),
12128 visualizer: 0,
12129 viz_paint: 0,
12130 gain_db: 0.0,
12131 gain_keys: Vec::new(),
12132 pan: 0,
12133 pitch: 0,
12134 transform_keys: Vec::new(),
12135 opacity_keys: Vec::new(),
12136 color_keys: Vec::new(),
12137 effects: Vec::new(),
12138 start,
12139 in_frame,
12140 out_frame,
12141 source,
12142 link: None,
12143 eq: None,
12144 color: None,
12145 transform: None,
12146 fit: FitPolicy::default(),
12147 speed: Speed::NORMAL,
12148 }
12149 }
12150
12151 /// A reversed clip's timeline head is its source out side: a split gives the
12152 /// head the late footage and the tail the early, a trim of the head eats the
12153 /// source's end, and joining the halves gives the one clip back.
12154 #[test]
12155 fn a_reversed_clip_splits_trims_and_joins_from_its_out_side() {
12156 let mut p = Project::single(FILE, 100);
12157 let v = p.add_lane(LaneKind::Video);
12158 let mut c = clip(0, 0, 100, 0);
12159 c.reversed = true;
12160 assert!(p.place(v, 0, c.clone()));
12161 assert!(p.split(30));
12162 let halves = p.lane_clips_pub(v).to_vec();
12163 assert_eq!((halves[0].start, halves[0].in_frame, halves[0].out_frame), (0, 70, 100));
12164 assert_eq!((halves[1].start, halves[1].in_frame, halves[1].out_frame), (30, 0, 70));
12165 assert!(halves.iter().all(|h| h.reversed));
12166 assert!(p.regroup(30), "the halves are one reversed run again");
12167 let one = &p.lane_clips_pub(v)[0];
12168 assert_eq!((one.in_frame, one.out_frame, one.reversed), (0, 100, true));
12169 // Trimming the head by 10 frames drops the source's last 10.
12170 assert!(p.trim(v, 0, Edge::Start, 10, &[100]));
12171 let t = &p.lane_clips_pub(v)[0];
12172 assert_eq!((t.start, t.in_frame, t.out_frame), (10, 0, 90));
12173 }
12174
12175 /// Toggling is one undo step, mirrors a key anchored to the footage so the
12176 /// timeline behaviour does not change, and refuses a still.
12177 #[test]
12178 fn set_reverse_is_one_undoable_step_and_mirrors_footage_keys() {
12179 let mut p = Project::single(FILE, 100);
12180 let v = p.add_lane(LaneKind::Video);
12181 assert!(p.place(v, 0, clip(0, 0, 100, 0)));
12182 let steps = p.history_len();
12183 p.set_reverse(v, 0, true).expect("reverse");
12184 assert_eq!(p.history_len(), steps + 1);
12185 assert!(p.reversed_of(v, 0));
12186 p.set_reverse(v, 0, true).expect("already so is a no-op");
12187 assert_eq!(p.history_len(), steps + 1, "no second step");
12188 assert_eq!(source_pos(&p.lane_clips_pub(v)[0], 0).floor() as u32, 99, "the first timeline frame shows the last footage");
12189 assert!(p.undo());
12190 assert!(!p.reversed_of(v, 0));
12191 assert!(p.set_reverse(v, 7, true).is_err(), "no such clip");
12192 }
12193
12194 /// The shape `captions_place` makes: one placement covering a three-cue
12195 /// track, where cue 1 ("second") is exactly frames 93..176 at 30 fps.
12196 fn three_cue_captions() -> (Project, Lane) {
12197 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12198 start_us,
12199 end_us,
12200 text: text.into(),
12201 image: None,
12202 words: Vec::new(),
12203 karaoke: Vec::new(),
12204 };
12205 let mut words = subtitle_track();
12206 words.cues = vec![
12207 cue(0, 3_100_000, "first"),
12208 cue(3_100_000, 5_866_667, "second"),
12209 cue(5_866_667, 9_000_000, "third"),
12210 ];
12211 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12212 let s1 = p.add_lane(LaneKind::Subtitle);
12213 let sub = SubClip {
12214 start: 0,
12215 frames: 270,
12216 track: 0,
12217 in_us: 0,
12218 out_us: 9_000_000,
12219 link: None,
12220 };
12221 p.place_sub(s1, 0, sub).expect("placed");
12222 (p, s1)
12223 }
12224
12225 /// A cut over a span nothing lies in changes nothing: it costs no undo step,
12226 /// keeps the revision, and pushes nothing the batch counter would count.
12227 #[test]
12228 fn a_cut_over_an_empty_span_costs_no_step_and_keeps_the_revision() {
12229 let mut p = Project::single(FILE, 270);
12230 let empty = p.add_lane(LaneKind::Audio);
12231 let (depth, pushes, rev) = (p.history_len(), p.history_pushes(), p.revision());
12232 p.cut_regions(&[(10, 20)], &[empty]).expect("an empty lane is a legal scope");
12233 assert_eq!(p.history_len(), depth, "no undo step");
12234 assert_eq!(p.history_pushes(), pushes, "no snapshot counted");
12235 assert_eq!(p.revision(), rev, "same state, same revision");
12236 p.cut_regions(&[(400, 20)], &[Lane::V1, Lane::A1]).expect("a span past the last clip");
12237 assert_eq!(p.history_len(), depth, "still no undo step");
12238 assert_eq!(p.revision(), rev, "still the same revision");
12239 }
12240
12241 /// A cut that removes something still costs exactly one undo step and a new revision.
12242 #[test]
12243 fn a_real_cut_still_adds_one_step() {
12244 let mut p = Project::single(FILE, 270);
12245 let (depth, rev) = (p.history_len(), p.revision());
12246 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12247 assert_eq!(p.history_len(), depth + 1, "one undo step");
12248 assert_ne!(p.revision(), rev, "a new state");
12249 }
12250
12251 /// A no-op after the save leaves the saved revision in place, and undoing the
12252 /// real edit back to that save reads as the saved state again.
12253 #[test]
12254 fn undo_back_to_the_saved_point_clears_the_dot_after_a_no_op() {
12255 let mut p = Project::single(FILE, 270);
12256 let empty = p.add_lane(LaneKind::Audio);
12257 p.cut_regions(&[(30, 30)], &[Lane::V1, Lane::A1]).expect("cut");
12258 let saved = p.revision();
12259 p.cut_regions(&[(10, 20)], &[empty]).expect("empty span");
12260 assert_eq!(p.revision(), saved, "a no-op after the save leaves the dot clear");
12261 p.cut_regions(&[(100, 10)], &[Lane::V1, Lane::A1]).expect("a real cut");
12262 assert_ne!(p.revision(), saved, "the real cut moves off the saved state");
12263 assert!(p.undo());
12264 assert_eq!(p.revision(), saved, "undo back to the saved point clears the dot");
12265 }
12266
12267 /// The undo bookkeeping a no-op must leave exactly as it found it.
12268 fn undo_state(p: &Project) -> (usize, u64, usize, u64) {
12269 (p.history_len(), p.revision(), p.redo_len(), p.history_pushes())
12270 }
12271
12272 /// Mutators given arguments that change nothing (the value a setting already
12273 /// holds, an empty list, a move by 0) take no undo step, move no revision and
12274 /// keep the redo branch an edit would have cleared.
12275 #[test]
12276 fn no_op_mutators_leave_the_undo_state_alone() {
12277 let mut p = Project::single(FILE, 270);
12278 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12279 assert!(p.set_enabled(Lane::V1, 0, false));
12280 assert!(p.set_label(Lane::V1, 0, 2));
12281 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12282 assert!(p.undo());
12283 let before = undo_state(&p);
12284 assert_eq!(before.2, 1, "the undone gain waits on the redo stack");
12285
12286 // Each call below sets a value the project already holds (or nothing).
12287 p.set_lane_gain_db(Lane::A1, -3.0);
12288 assert_eq!(undo_state(&p), before, "set_lane_gain_db");
12289 p.set_enabled(Lane::V1, 0, false);
12290 assert_eq!(undo_state(&p), before, "set_enabled");
12291 p.set_label(Lane::V1, 0, 2);
12292 assert_eq!(undo_state(&p), before, "set_label");
12293 p.set_clip_gain(Lane::A1, 0, 0.0);
12294 assert_eq!(undo_state(&p), before, "set_clip_gain");
12295 p.set_fade_in(Lane::V1, 0, 0);
12296 assert_eq!(undo_state(&p), before, "set_fade_in");
12297 p.set_fade_out(Lane::V1, 0, 0);
12298 assert_eq!(undo_state(&p), before, "set_fade_out");
12299 let _ = p.set_reverse(Lane::V1, 0, false);
12300 assert_eq!(undo_state(&p), before, "set_reverse");
12301 assert_eq!(p.slip(Lane::V1, 0, 0, SourceWalls::same(&[270])), Some(0));
12302 assert_eq!(undo_state(&p), before, "slip by 0");
12303 p.set_eq(Lane::A1, 0, None);
12304 assert_eq!(undo_state(&p), before, "set_eq");
12305 p.set_color_keys(Lane::V1, 0, Vec::new());
12306 assert_eq!(undo_state(&p), before, "set_color_keys");
12307 p.set_gain_keys(Lane::A1, 0, Vec::new());
12308 assert_eq!(undo_state(&p), before, "set_gain_keys");
12309 p.set_opacity_keys(Lane::V1, 0, Vec::new());
12310 assert_eq!(undo_state(&p), before, "set_opacity_keys");
12311 let _ = p.set_lane_name(Lane::A1, "");
12312 assert_eq!(undo_state(&p), before, "set_lane_name");
12313 p.clear_lane_duck(Lane::A1, 0);
12314 assert_eq!(undo_state(&p), before, "clear_lane_duck");
12315 p.remap_chapters(|f| f);
12316 assert_eq!(undo_state(&p), before, "remap_chapters");
12317 p.remap_markers(|f| f);
12318 assert_eq!(undo_state(&p), before, "remap_markers");
12319 p.add_subtitles_all(&[]);
12320 assert_eq!(undo_state(&p), before, "add_subtitles_all");
12321 p.relink_sources(&[]);
12322 assert_eq!(undo_state(&p), before, "relink_sources");
12323 let _ = p.cut_regions(&[(10, 0)], &[Lane::V1]);
12324 assert_eq!(undo_state(&p), before, "cut_regions of nothing");
12325
12326 // And the redo branch is still there to walk forward.
12327 let depth = p.history_len();
12328 assert!(p.redo(), "the gain comes back");
12329 assert_eq!(p.history_len(), depth + 1, "redo is one step forward");
12330 }
12331
12332 /// Real edits still cost exactly one undo step each, also right after a no-op.
12333 #[test]
12334 fn real_edits_still_add_exactly_one_step_after_no_ops() {
12335 let mut p = Project::single(FILE, 270);
12336 assert!(!p.set_enabled(Lane::V1, 0, true), "already on: nothing to do");
12337 let steps = p.history_len();
12338 let rev = p.revision();
12339 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12340 assert_eq!(p.history_len(), steps + 1, "one step for the gain");
12341 assert_ne!(p.revision(), rev, "a new state");
12342 assert!(p.set_enabled(Lane::V1, 0, false));
12343 assert_eq!(p.history_len(), steps + 2, "one step for the switch");
12344 assert!(p.set_label(Lane::V1, 0, 2));
12345 assert_eq!(p.history_len(), steps + 3, "one step for the label");
12346 assert!(p.set_clip_gain(Lane::A1, 0, -6.0));
12347 assert_eq!(p.history_len(), steps + 4, "one step for the clip gain");
12348 }
12349
12350 /// A no-op right after a real edit does not hide that edit from undo: one undo
12351 /// takes back the real edit, and nothing is left behind to undo next.
12352 #[test]
12353 fn undo_right_after_a_no_op_takes_back_the_real_edit() {
12354 let mut p = Project::single(FILE, 270);
12355 let start = p.revision();
12356 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12357 let edited = p.revision();
12358 p.set_lane_gain_db(Lane::A1, -3.0);
12359 assert_eq!(p.revision(), edited, "the no-op leaves the edited state's revision");
12360 assert!(p.undo());
12361 assert_eq!(p.revision(), start, "undo lands on the state before the edit");
12362 assert_eq!(p.history_len(), 0, "and no phantom step is left");
12363 assert!(!p.undo());
12364 }
12365
12366 /// A no-op between two edits leaves no step behind for the second to stack on.
12367 #[test]
12368 fn a_no_op_between_two_edits_is_not_a_step() {
12369 let mut p = Project::single(FILE, 270);
12370 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12371 p.set_lane_gain_db(Lane::A1, -3.0);
12372 assert!(p.set_enabled(Lane::V1, 0, false));
12373 assert_eq!(p.history_len(), 2, "the two edits, and no more");
12374 assert!(p.undo());
12375 assert!(p.undo());
12376 assert!(!p.undo(), "the no-op is gone for good");
12377 }
12378
12379 /// A no-op never destroys a redo branch: after an undo, a no-op keeps it, and
12380 /// redo still walks forward to the edit that was undone.
12381 #[test]
12382 fn a_no_op_after_undo_keeps_the_redo_branch() {
12383 let mut p = Project::single(FILE, 270);
12384 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12385 let edited = p.revision();
12386 assert!(p.undo());
12387 p.set_lane_gain_db(Lane::A1, 0.0);
12388 assert_eq!(p.redo_len(), 1, "the undone edit is still on the branch");
12389 assert!(p.redo());
12390 assert_eq!(p.revision(), edited, "redo walks back to the same state");
12391 }
12392
12393 /// Inside a batch a no-op adds no step, and a batch with a real edit and no-ops
12394 /// in it is one step.
12395 #[test]
12396 fn no_ops_inside_a_batch_add_no_step() {
12397 let mut p = Project::single(FILE, 270);
12398 let before = undo_state(&p);
12399 p.begin_batch();
12400 p.set_lane_gain_db(Lane::A1, 0.0);
12401 p.set_enabled(Lane::V1, 0, true);
12402 p.end_batch();
12403 assert_eq!(undo_state(&p), before, "an all-no-op batch is no step");
12404
12405 p.begin_batch();
12406 p.set_lane_gain_db(Lane::A1, 0.0);
12407 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
12408 p.set_lane_gain_db(Lane::A1, -3.0);
12409 assert!(p.set_enabled(Lane::V1, 0, false));
12410 p.end_batch();
12411 assert_eq!(p.history_len(), before.0 + 1, "the batch is one step");
12412 assert!(p.undo());
12413 assert_eq!(p.revision(), before.1, "undo takes the whole batch back");
12414 assert!(!p.undo());
12415 }
12416
12417 /// At the cap a no-op neither evicts the oldest step nor loses it: the next real
12418 /// edit evicts it as it would have, and every step but that one can be undone.
12419 #[test]
12420 fn a_no_op_at_the_cap_keeps_every_step_it_should() {
12421 let mut p = Project::single(FILE, 400);
12422 for frame in 1..=HISTORY_CAP as u32 {
12423 assert!(p.split(frame));
12424 }
12425 let before = undo_state(&p);
12426 assert_eq!(before.0, HISTORY_CAP);
12427 p.set_enabled(Lane::V1, 0, true);
12428 assert_eq!(undo_state(&p), before, "a no-op at the cap");
12429 assert!(p.split(HISTORY_CAP as u32 + 1));
12430 assert_eq!(p.history_len(), HISTORY_CAP);
12431 let mut steps = 0;
12432 while p.undo() {
12433 steps += 1;
12434 }
12435 assert_eq!(steps, HISTORY_CAP, "every step but the evicted oldest one");
12436 }
12437
12438 /// The cues `s1` shows, as `(text, start_us, end_us)` in timeline order.
12439 fn shown_cues(p: &Project, s1: Lane) -> Vec<(String, i64, i64)> {
12440 p.sub_lane_cue_refs(s1, 30.0)
12441 .into_iter()
12442 .map(|(a, b, t, c)| (p.subtitles()[t].cues[c].text.clone(), a, b))
12443 .collect()
12444 }
12445
12446 /// A cut that covers a whole cue removes it: no zero-length copy, no
12447 /// duplicate, and the cues after it slide back. A cut that covers part of
12448 /// a cue trims it, and a cut spanning two cues trims both.
12449 #[test]
12450 fn a_cut_removes_or_trims_the_cues_it_covers() {
12451 let (mut p, s1) = three_cue_captions();
12452 p.cut_regions(&[(93, 83)], &[s1]).expect("cut the second sentence");
12453 let shown = shown_cues(&p, s1);
12454 assert_eq!(
12455 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12456 ["first", "third"],
12457 "the covered cue is gone, once: {shown:?}"
12458 );
12459 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12460 assert!((shown[1].1 - 3_100_000).abs() <= 3, "the third cue slides back to the cut: {shown:?}");
12461 assert!((shown[1].2 - shown[1].1 - 3_133_333).abs() <= 3, "third keeps its length: {shown:?}");
12462
12463 // Part of the second cue (frames 100..150) is cut out of the middle.
12464 let (mut p, s1) = three_cue_captions();
12465 p.cut_regions(&[(100, 50)], &[s1]).expect("cut inside the second cue");
12466 let shown = shown_cues(&p, s1);
12467 let total = |text: &str| -> i64 {
12468 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12469 };
12470 // "second" is one word: it keeps the longer side the cut leaves (5.0 s to 5.87 s, 0.87 s), once.
12471 assert!((total("second") - 866_667).abs() <= 3, "second keeps its longer side, once: {shown:?}");
12472 assert_eq!(shown.iter().filter(|c| c.0 == "second").count(), 1, "{shown:?}");
12473 assert!((total("first") - 3_100_000).abs() <= 3, "first is untouched: {shown:?}");
12474 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12475
12476 // A cut from inside the first cue to inside the second.
12477 let (mut p, s1) = three_cue_captions();
12478 p.cut_regions(&[(60, 60)], &[s1]).expect("cut across two cues");
12479 let shown = shown_cues(&p, s1);
12480 let total = |text: &str| -> i64 {
12481 shown.iter().filter(|c| c.0 == text).map(|c| c.2 - c.1).sum()
12482 };
12483 assert!((total("first") - 2_000_000).abs() <= 3, "first keeps its first two seconds: {shown:?}");
12484 assert!((total("second") - 1_866_667).abs() <= 3, "second keeps its last 1.87 s: {shown:?}");
12485 assert!((total("third") - 3_133_333).abs() <= 3, "third is untouched: {shown:?}");
12486 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12487 }
12488
12489 /// A sentence over one placement, nine seconds at 30 fps.
12490 fn sentence_captions() -> (Project, Lane) {
12491 let mut words = subtitle_track();
12492 words.cues = vec![crate::subtitle::Cue {
12493 start_us: 0,
12494 end_us: 9_000_000,
12495 text: "alpha beta gamma delta".into(),
12496 image: None,
12497 words: Vec::new(),
12498 karaoke: Vec::new(),
12499 }];
12500 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12501 let s1 = p.add_lane(LaneKind::Subtitle);
12502 let sub = SubClip { start: 0, frames: 270, track: 0, in_us: 0, out_us: 9_000_000, link: None };
12503 p.place_sub(s1, 0, sub).expect("placed");
12504 (p, s1)
12505 }
12506
12507 /// Cutting the middle of a sentence keeps the words either side of the cut
12508 /// and drops the ones inside it: "beta gamma" lies in frames 90..180 (3 s
12509 /// to 6 s), so only "alpha" and "delta" are left to show. Undo brings the
12510 /// one sentence back as it was.
12511 #[test]
12512 fn a_cut_through_a_sentence_drops_the_words_inside_it() {
12513 let (mut p, s1) = sentence_captions();
12514 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12515 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12516 assert_eq!(shown, ["alpha", "delta"], "the cut words are gone and the rest stays");
12517
12518 assert!(p.undo(), "the cut is one undo step");
12519 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the one cue");
12520 assert_eq!(p.subtitles()[0].cues[0].text, "alpha beta gamma delta");
12521 }
12522
12523 /// A ripple delete over the same span splits the same way, and so does a
12524 /// split at a point inside a sentence, which divides the words once.
12525 #[test]
12526 fn a_ripple_delete_and_a_split_divide_the_words_too() {
12527 let (mut p, s1) = sentence_captions();
12528 assert!(p.ripple_delete(90, 90));
12529 let shown: Vec<String> = shown_cues(&p, s1).into_iter().map(|c| c.0).collect();
12530 assert_eq!(shown, ["alpha", "delta"], "{shown:?}");
12531
12532 let (mut p, _) = sentence_captions();
12533 assert!(p.split(150), "a frame inside the sentence splits it");
12534 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12535 assert_eq!(texts, ["alpha beta", "gamma delta"], "a split at the half divides the words");
12536 }
12537
12538 /// `split_cues_at` divides the cue at the word boundary nearest the point,
12539 /// keeps every piece's time inside the cue, and is one undo step. Where no
12540 /// cue straddles the point it changes nothing and takes no step.
12541 #[test]
12542 fn split_cues_at_divides_the_words_and_is_one_undo_step() {
12543 let (mut p, _) = sentence_captions();
12544 assert!(!p.split_cues_at(0, 0), "a point at the cue's start splits nothing");
12545 assert!(p.split_cues_at(0, 2_250_000));
12546 let cues: Vec<(String, i64, i64)> =
12547 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12548 assert_eq!(
12549 cues,
12550 [("alpha".to_string(), 0, 2_250_000), ("beta gamma delta".to_string(), 2_250_000, 9_000_000)],
12551 "the pieces meet at the point and keep the words either side"
12552 );
12553 assert!(p.undo());
12554 assert_eq!(p.subtitles()[0].cues.len(), 1, "undo restores the sentence");
12555
12556 // "second" is one word: it stays whole on the longer side of 4 s (the tail, 4 s to 5.87 s).
12557 let (mut p, _) = three_cue_captions();
12558 assert!(p.split_cues_at(0, 4_000_000));
12559 let cues: Vec<(String, i64, i64)> =
12560 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12561 assert_eq!(cues.len(), 3, "a one-word cue is not duplicated: {cues:?}");
12562 assert_eq!(cues[1], ("second".to_string(), 4_000_000, 5_866_667));
12563 }
12564
12565 /// A cue with one word cut by an edge keeps its text on the longer piece only
12566 /// (ties: the piece before the edge), so the word is never shown twice.
12567 #[test]
12568 fn a_one_word_cue_cut_by_an_edge_keeps_its_text_on_one_piece() {
12569 let cue = |start_us: i64, end_us: i64| crate::subtitle::Cue { start_us, end_us, text: "Onewordcue".into(), image: None, words: Vec::new(), karaoke: Vec::new() };
12570 let before = cue(0, 4_000_000);
12571 assert_eq!(
12572 split_words(&before, 3_000_000),
12573 Some(vec![(0, 3_000_000, "Onewordcue".to_string())]),
12574 "the longer piece before the edge keeps the word"
12575 );
12576 assert_eq!(
12577 split_words(&cue(0, 4_000_000), 1_000_000),
12578 Some(vec![(1_000_000, 4_000_000, "Onewordcue".to_string())]),
12579 "the longer piece after the edge keeps the word"
12580 );
12581 assert_eq!(
12582 split_words(&cue(0, 4_000_000), 2_000_000),
12583 Some(vec![(0, 2_000_000, "Onewordcue".to_string())]),
12584 "a tie keeps the word on the piece before"
12585 );
12586 assert_eq!(split_words(&crate::subtitle::Cue { start_us: 0, end_us: 1, text: " ".into(), image: None, words: Vec::new(), karaoke: Vec::new() }, 0), None);
12587 }
12588
12589 /// A cut through a one-word caption ("first", 0 to 3.1 s) at 2 s keeps the
12590 /// word on the longer piece before the cut, and no piece after it shows it.
12591 #[test]
12592 fn a_cut_through_a_one_word_caption_shows_it_once() {
12593 let (mut p, _) = three_cue_captions();
12594 assert!(p.split_cues_at(0, 2_000_000));
12595 let cues: Vec<(String, i64, i64)> =
12596 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12597 assert_eq!(cues[0], ("first".to_string(), 0, 2_000_000), "{cues:?}");
12598 assert_eq!(cues.iter().filter(|c| c.0 == "first").count(), 1, "one copy of the word: {cues:?}");
12599 }
12600
12601 /// Divided cues are written by a save as cue edits and cue adds, so a reopen
12602 /// of the saved project shows the same words, not the sentence it began as.
12603 #[test]
12604 fn divided_cues_survive_a_save_and_reopen() {
12605 let (mut p, s1) = sentence_captions();
12606 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12607 let edits = p.cue_edits().to_vec();
12608 let adds = p.cue_adds().to_vec();
12609 let mut words = subtitle_track();
12610 words.cues = vec![crate::subtitle::Cue {
12611 start_us: 0,
12612 end_us: 9_000_000,
12613 text: "alpha beta gamma delta".into(),
12614 image: None,
12615 words: Vec::new(),
12616 karaoke: Vec::new(),
12617 }];
12618 let reopened = Project::single(FILE, 270)
12619 .with_subtitles(vec![words])
12620 .with_cue_edits(&edits)
12621 .with_cue_adds(&adds);
12622 let texts = |p: &Project| -> Vec<(String, i64, i64)> {
12623 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect()
12624 };
12625 assert_eq!(texts(&reopened), texts(&p), "the reopened cues are the divided ones");
12626 }
12627
12628 /// The rippling delete is the same cut on every lane, so it must leave the
12629 /// same captions as the scoped one: no covered cue survives it either.
12630 #[test]
12631 fn a_ripple_delete_over_a_cue_leaves_no_copy_of_it() {
12632 let (mut p, s1) = three_cue_captions();
12633 assert!(p.ripple_delete(93, 83));
12634 let shown = shown_cues(&p, s1);
12635 assert_eq!(
12636 shown.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
12637 ["first", "third"],
12638 "{shown:?}"
12639 );
12640 assert!(shown.iter().all(|c| c.2 > c.1), "no zero-length cue: {shown:?}");
12641 }
12642
12643 /// How many of track `track`'s cues some placement window overlaps: a cue no
12644 /// window overlaps is an orphan, one nothing on the timeline can show.
12645 fn placed_cues_of(p: &Project, track: usize) -> usize {
12646 let windows: Vec<(i64, i64)> = p
12647 .lanes
12648 .iter()
12649 .flat_map(|l| l.subs.iter())
12650 .filter(|s| s.track == track)
12651 .map(|s| (s.in_us, s.out_us))
12652 .collect();
12653 p.subtitles()[track]
12654 .cues
12655 .iter()
12656 .filter(|c| windows.iter().any(|&(a, b)| c.start_us < b && a < c.end_us))
12657 .count()
12658 }
12659
12660 /// A cut through a sentence leaves no orphan. "beta gamma" lies in the cut,
12661 /// so it is removed with its words: the track keeps only "alpha" and
12662 /// "delta", and each is under the placement window that is left.
12663 #[test]
12664 fn a_cut_through_a_sentence_leaves_no_orphan_piece() {
12665 let (mut p, s1) = sentence_captions();
12666 p.cut_regions(&[(90, 90)], &[s1]).expect("cut the middle");
12667 let texts: Vec<String> = p.subtitles()[0].cues.iter().map(|c| c.text.clone()).collect();
12668 assert_eq!(texts, ["alpha", "delta"], "the removed middle is not a cue: {texts:?}");
12669 assert_eq!(placed_cues_of(&p, 0), 2, "every cue is under a window");
12670 }
12671
12672 /// A cut that ends inside a one-word cue keeps the part the timeline still
12673 /// shows. "Over" runs 1.0 s to 1.7 s; cutting frames 1.0 s to 1.5 s leaves
12674 /// 1.5 s to 1.7 s on the timeline, so that is the cue that stays, with its
12675 /// word. The removed 1.0 s to 1.5 s piece is dropped.
12676 #[test]
12677 fn a_cut_ending_in_a_one_word_cue_keeps_the_visible_part() {
12678 let mut words = subtitle_track();
12679 words.cues = vec![crate::subtitle::Cue { start_us: 1_000_000, end_us: 1_700_000, text: "Over".into(), image: None, words: Vec::new(), karaoke: Vec::new() }];
12680 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12681 let s1 = p.add_lane(LaneKind::Subtitle);
12682 // The file's 1 s to 4 s, played from timeline frame 30 (1.0 s) for 90 frames.
12683 let sub = SubClip { start: 30, frames: 90, track: 0, in_us: 1_000_000, out_us: 4_000_000, link: None };
12684 p.place_sub(s1, 30, sub).expect("placed");
12685 p.cut_regions(&[(30, 15)], &[s1]).expect("cut 1.0 s to 1.5 s");
12686 let cues: Vec<(String, i64, i64)> =
12687 p.subtitles()[0].cues.iter().map(|c| (c.text.clone(), c.start_us, c.end_us)).collect();
12688 assert_eq!(cues, [("Over".to_string(), 1_500_000, 1_700_000)], "{cues:?}");
12689 let shown = shown_cues(&p, s1);
12690 assert_eq!(shown.len(), 1, "{shown:?}");
12691 assert_eq!(shown[0].0, "Over");
12692 assert!((shown[0].1 - 1_000_000).abs() <= 3, "the word now starts where the cut ended: {shown:?}");
12693 assert!((shown[0].2 - 1_200_000).abs() <= 3, "and keeps its 0.2 s: {shown:?}");
12694 }
12695
12696 /// Three cuts in a row over a captioned timeline keep the track to the cues
12697 /// the placement shows: after each one every cue is under a window, so the
12698 /// cue count is the placed count.
12699 #[test]
12700 fn three_cuts_keep_the_cue_count_at_the_placed_count() {
12701 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue { start_us, end_us, text: text.into(), image: None, words: Vec::new(), karaoke: Vec::new() };
12702 let mut words = subtitle_track();
12703 words.cues = vec![
12704 cue(0, 1_900_000, "a b"),
12705 cue(1_900_000, 4_200_000, "c d e"),
12706 cue(4_200_000, 6_000_000, "f g"),
12707 cue(6_000_000, 8_100_000, "h i j"),
12708 cue(8_100_000, 10_000_000, "k l"),
12709 cue(10_000_000, 12_000_000, "m n"),
12710 ];
12711 let mut p = Project::single(FILE, 360).with_subtitles(vec![words]);
12712 let s1 = p.add_lane(LaneKind::Subtitle);
12713 let sub = SubClip { start: 0, frames: 360, track: 0, in_us: 0, out_us: 12_000_000, link: None };
12714 p.place_sub(s1, 0, sub).expect("placed");
12715 assert_eq!(placed_cues_of(&p, 0), 6);
12716 for (at, len) in [(45, 20), (100, 30), (200, 25)] {
12717 p.cut_regions(&[(at, len)], &[s1]).expect("cut");
12718 let total = p.subtitles()[0].cues.len();
12719 assert_eq!(placed_cues_of(&p, 0), total, "every cue is under a window after a cut: {total} cues");
12720 }
12721 }
12722
12723 /// A cue no placement ever covered is not the cut's to remove. A caption
12724 /// placed over the first part of its track leaves the rest of the cues in
12725 /// the track, so a cut through the placed part keeps them for later.
12726 #[test]
12727 fn a_cue_no_placement_covers_survives_a_cut() {
12728 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue { start_us, end_us, text: text.into(), image: None, words: Vec::new(), karaoke: Vec::new() };
12729 let mut words = subtitle_track();
12730 words.cues = vec![cue(0, 2_000_000, "x y"), cue(5_000_000, 7_000_000, "z w")];
12731 let mut p = Project::single(FILE, 270).with_subtitles(vec![words]);
12732 let s1 = p.add_lane(LaneKind::Subtitle);
12733 // Only the first two seconds are placed.
12734 let sub = SubClip { start: 0, frames: 60, track: 0, in_us: 0, out_us: 2_000_000, link: None };
12735 p.place_sub(s1, 0, sub).expect("placed");
12736 p.cut_regions(&[(30, 15)], &[s1]).expect("cut inside the placed part");
12737 let kept = p.subtitles()[0]
12738 .cues
12739 .iter()
12740 .filter(|c| c.text == "z w" && c.start_us == 5_000_000 && c.end_us == 7_000_000)
12741 .count();
12742 assert_eq!(kept, 1, "the unplaced cue stays in the track: {:?}", p.subtitles()[0].cues);
12743 }
12744
12745 /// A caption placement for pure timeline tests: the track window is the
12746 /// same duration as the placement, so assertions can stay in frames.
12747 fn caption(start: u32, frames: u32) -> SubClip {
12748 SubClip {
12749 start,
12750 frames,
12751 track: 0,
12752 in_us: 0,
12753 out_us: i64::from(frames) * 1_000_000,
12754 link: None,
12755 }
12756 }
12757
12758 /// A language retype is one undo step, refused (with no step) for a track
12759 /// that is not there or that already reads it, and a load puts a saved
12760 /// language back over the file's own.
12761 #[test]
12762 fn a_subtitle_language_is_one_undo_step_and_a_load_puts_it_back() {
12763 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track()]);
12764 assert!(p.set_subtitle_language(0, "fra"));
12765 assert_eq!(p.subtitles()[0].language, "fra");
12766 assert!(!p.set_subtitle_language(0, "fra"), "it already reads that: no step");
12767 assert!(!p.set_subtitle_language(5, "fra"), "no such track");
12768 assert!(p.undo());
12769 assert_eq!(p.subtitles()[0].language, "eng", "one step takes it back");
12770
12771 let back = Project::single(FILE, 300)
12772 .with_subtitles(vec![subtitle_track()])
12773 .with_sub_langs(&[(0, "deu".to_string()), (9, "xxx".to_string())]);
12774 assert_eq!(back.subtitles()[0].language, "deu");
12775 }
12776
12777 /// A subtitle palette row for tests that place captions on lanes.
12778 fn subtitle_track() -> SubtitleTrack {
12779 SubtitleTrack {
12780 path: FILE.into(),
12781 track: None,
12782 language: "eng".into(),
12783 name: String::new(),
12784 label: "eng".into(),
12785 cues: Vec::new(),
12786 bitmap: false,
12787 refused: None,
12788 }
12789 }
12790
12791 /// A retyped cue is the track's words, so every placement of that track
12792 /// shows it; a retype that changes nothing, or names no cue, costs no undo
12793 /// step; one undo takes the words and the save list back together; and a
12794 /// removed row's overrides go with it while the others keep their place.
12795 #[test]
12796 fn a_cue_is_trimmed_moved_and_merged_inside_its_neighbours_one_undo_step_each() {
12797 let (mut p, s1) = three_cue_captions();
12798 let times = |p: &Project| -> Vec<(i64, i64)> {
12799 p.subtitles()[0].cues.iter().map(|c| (c.start_us, c.end_us)).collect()
12800 };
12801 assert_eq!(p.cue_room(0, 1), Some((3_100_000, 5_866_667)));
12802 assert!(p.set_cue_times(0, 1, 3_100_000, 5_866_667).is_ok_and(|changed| !changed), "same times, no edit");
12803 assert!(p.set_cue_times(0, 1, 3_000_000, 5_000_000).is_err(), "into the cue before");
12804 assert!(p.set_cue_times(0, 1, 3_100_000, 6_000_000).is_err(), "into the cue after");
12805 assert!(p.set_cue_times(0, 1, 3_100_000, 3_150_000).is_err(), "too short");
12806 assert!(matches!(p.set_cue_times(0, 1, 3_500_000, 5_000_000), Ok(true)));
12807 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
12808 assert_eq!(p.subtitles()[0].cues[1].text, "second");
12809 assert_eq!(
12810 shown_cues(&p, s1)[1],
12811 ("second".to_string(), 3_500_000, 5_000_000),
12812 "the timeline shows the moved cue"
12813 );
12814 // The file cue leaves and its new times are an added cue: a save keeps both.
12815 assert_eq!(p.cue_adds().len(), 1);
12816 assert!(p.cue_edits().iter().any(|(_, _, t)| t.is_empty()));
12817 // A second trim of the same (now added) cue stays one added entry.
12818 assert!(matches!(p.set_cue_times(0, 1, 3_400_000, 5_000_000), Ok(true)));
12819 assert_eq!(p.cue_adds().len(), 1);
12820 assert_eq!(p.cue_adds()[0].start_us, 3_400_000);
12821
12822 assert_eq!(p.cue_track_us_at(s1, 0, 1, 4_000_000, 30.0), Some(4_000_000));
12823
12824 assert!(p.merge_cue_next(2, 0).is_err(), "no such track");
12825 assert!(p.merge_cue_next(0, 2).is_err(), "nothing after the last");
12826 assert!(p.merge_cue_next(0, 0).is_ok());
12827 assert_eq!(p.subtitles()[0].cues.len(), 2);
12828 assert_eq!(p.subtitles()[0].cues[0].text, "first second");
12829 assert_eq!(times(&p)[0], (0, 5_000_000));
12830
12831 assert!(p.undo(), "the merge goes");
12832 assert_eq!(p.subtitles()[0].cues.len(), 3);
12833 assert!(p.undo(), "the second trim goes");
12834 assert_eq!(times(&p)[1], (3_500_000, 5_000_000));
12835 assert!(p.undo(), "the first trim goes");
12836 assert_eq!(times(&p)[1], (3_100_000, 5_866_667));
12837 assert!(p.cue_adds().is_empty() && p.cue_edits().is_empty());
12838 }
12839
12840 #[test]
12841 fn a_retyped_cue_is_the_tracks_words_and_one_undo_step() {
12842 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12843 start_us,
12844 end_us,
12845 text: text.into(),
12846 image: None,
12847 words: Vec::new(),
12848 karaoke: Vec::new(),
12849 };
12850 let mut words = subtitle_track();
12851 words.cues = vec![cue(0, 1_000_000, "one"), cue(2_000_000, 3_000_000, "two")];
12852 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
12853 let s1 = p.add_lane(LaneKind::Subtitle);
12854 // A window of the track's first three seconds, played over three: one
12855 // timeline second is one of the file's, so the cues land where they are.
12856 for at in [0, 100] {
12857 let sub = SubClip {
12858 start: at,
12859 frames: 90,
12860 track: 1,
12861 in_us: 0,
12862 out_us: 3_000_000,
12863 link: None,
12864 };
12865 p.place_sub(s1, at, sub).expect("placed");
12866 }
12867 let texts = |p: &Project| -> Vec<String> {
12868 p.sub_lane_cues(s1, 30.0)
12869 .into_iter()
12870 .map(|c| c.text)
12871 .collect()
12872 };
12873 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
12874
12875 assert!(!p.set_cue_text(1, 0, "one"), "the same words are no edit");
12876 assert!(!p.set_cue_text(1, 9, "x"), "a cue that is not there");
12877 assert!(!p.set_cue_text(7, 0, "x"), "a track that is not there");
12878 assert!(p.set_cue_text(1, 1, "TWO\nlines"));
12879 assert_eq!(
12880 texts(&p),
12881 ["one", "TWO\nlines", "one", "TWO\nlines"],
12882 "both placements show the retyped words"
12883 );
12884 assert_eq!(p.cue_edits(), [(1, 1, "TWO\nlines".to_string())]);
12885
12886 let refs = p.sub_lane_cue_refs(s1, 30.0);
12887 let drawn = p.sub_lane_cues(s1, 30.0);
12888 assert_eq!(refs.len(), drawn.len(), "one ref for each cue drawn");
12889 for (&(start, end, track, cue_idx), c) in refs.iter().zip(&drawn) {
12890 assert_eq!((start, end), (c.start_us, c.end_us));
12891 assert_eq!(p.subtitles()[track].cues[cue_idx].text, c.text);
12892 }
12893
12894 assert!(p.undo(), "one step back");
12895 assert_eq!(texts(&p), ["one", "two", "one", "two"]);
12896 assert!(
12897 p.cue_edits().is_empty(),
12898 "the save list goes back with the words"
12899 );
12900 assert!(p.redo());
12901 assert_eq!(texts(&p)[1], "TWO\nlines");
12902
12903 // The row above the edited one comes off: the edit moves down with its
12904 // track, and still names the cue it changed.
12905 p.remove_subtitles(0).expect("nothing is placed on it");
12906 assert_eq!(p.cue_edits(), [(0, 1, "TWO\nlines".to_string())]);
12907 assert_eq!(texts(&p)[1], "TWO\nlines");
12908 }
12909
12910 /// A deleted cue is gone from every placement of its track, and no placement
12911 /// moves. Deleting cue 1 and then cue 0 (by the indices a listing shows
12912 /// after each) leaves the file's third cue; a retype after the deletes lands
12913 /// on that cue's file index; and a reload of the same file, with the saved
12914 /// overrides put back, shows exactly what the session showed.
12915 #[test]
12916 fn a_deleted_cue_leaves_the_track_and_survives_a_reload() {
12917 let file_words = || {
12918 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12919 start_us,
12920 end_us,
12921 text: text.into(),
12922 image: None,
12923 words: Vec::new(),
12924 karaoke: Vec::new(),
12925 };
12926 let mut words = subtitle_track();
12927 words.cues = vec![
12928 cue(0, 1_000_000, "one"),
12929 cue(2_000_000, 3_000_000, "two"),
12930 cue(4_000_000, 5_000_000, "three"),
12931 ];
12932 words
12933 };
12934 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]);
12935 let s1 = p.add_lane(LaneKind::Subtitle);
12936 let sub = SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None };
12937 p.place_sub(s1, 0, sub).expect("placed");
12938 let texts = |p: &Project| -> Vec<String> {
12939 p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect()
12940 };
12941 assert_eq!(texts(&p), ["one", "two", "three"]);
12942
12943 assert!(p.delete_cue(1, 1), "cue 1 (\"two\") goes");
12944 assert!(!p.delete_cue(1, 9), "a cue that is not there");
12945 assert_eq!(texts(&p), ["one", "three"]);
12946 assert_eq!((p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].frames), (0, 150), "nothing moves");
12947 assert_eq!(p.cue_edits(), [(1, 1, String::new())]);
12948
12949 // Cue 1 is now "three"; its file index is 2, which the save names.
12950 assert!(p.set_cue_text(1, 1, "THREE"));
12951 assert_eq!(texts(&p), ["one", "THREE"]);
12952 assert_eq!(p.cue_edits(), [(1, 1, String::new()), (1, 2, "THREE".to_string())]);
12953
12954 // Empty text is a removal, not a blank cue: "one" goes.
12955 assert!(p.set_cue_text(1, 0, ""));
12956 assert_eq!(texts(&p), ["THREE"]);
12957 assert_eq!(
12958 p.cue_edits(),
12959 [(1, 1, String::new()), (1, 2, "THREE".to_string()), (1, 0, String::new())]
12960 );
12961
12962 // A reload: the file's three cues, the saved overrides put back.
12963 let saved = p.cue_edits().to_vec();
12964 let mut reopened =
12965 Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), file_words()]).with_cue_edits(&saved);
12966 let s1r = reopened.add_lane(LaneKind::Subtitle);
12967 reopened.place_sub(s1r, 0, SubClip { start: 0, frames: 150, track: 1, in_us: 0, out_us: 5_000_000, link: None }).expect("placed");
12968 let got: Vec<String> = reopened.sub_lane_cues(s1r, 30.0).into_iter().map(|c| c.text).collect();
12969 assert_eq!(got, ["THREE"], "the reload shows what the session did");
12970 assert_eq!(reopened.cue_edits(), saved.as_slice(), "and saves the same list");
12971
12972 // Undo takes back the last removal, then the retype, then the first removal.
12973 assert!(p.undo());
12974 assert_eq!(texts(&p), ["one", "THREE"]);
12975 assert!(p.undo());
12976 assert_eq!(texts(&p), ["one", "three"]);
12977 assert!(p.undo());
12978 assert_eq!(texts(&p), ["one", "two", "three"]);
12979 }
12980
12981 /// A cue a window edge shortened to under [`CUT_SLIVER_FRAMES`] is no cue;
12982 /// a cue that was short in the file, and whole, stays one.
12983 #[test]
12984 fn a_cut_sliver_under_four_frames_is_dropped_and_a_short_cue_is_not() {
12985 let cue = |start_us: i64, end_us: i64, text: &str| crate::subtitle::Cue {
12986 start_us,
12987 end_us,
12988 text: text.into(),
12989 image: None,
12990 words: Vec::new(),
12991 karaoke: Vec::new(),
12992 };
12993 let mut words = subtitle_track();
12994 words.cues = vec![
12995 cue(0, 1_000_000, "whole"),
12996 // Shortened by the window's end at 1.1 s: 0.1 s, three frames.
12997 cue(1_000_000, 2_000_000, "edge"),
12998 // Two frames long in the file itself, inside the window.
12999 cue(1_000_000, 1_066_667, "born"),
13000 ];
13001 let mut p = Project::single(FILE, 300).with_subtitles(vec![subtitle_track(), words]);
13002 let s1 = p.add_lane(LaneKind::Subtitle);
13003 let sub = SubClip { start: 0, frames: 33, track: 1, in_us: 0, out_us: 1_100_000, link: None };
13004 p.place_sub(s1, 0, sub).expect("placed");
13005 let shown: Vec<String> = p.sub_lane_cues(s1, 30.0).into_iter().map(|c| c.text).collect();
13006 assert_eq!(shown, ["whole", "born"], "the three-frame edge is no cue: {shown:?}");
13007 }
13008
13009 /// A recognisable equalizer setting: one peak band, `n` telling two of them
13010 /// apart -- which is what makes the table's dedup and its prune visible.
13011 fn band_at(n: u32) -> EqParams {
13012 EqParams {
13013 bands: vec![crate::eq::Band {
13014 freq_hz: 1000.0,
13015 gain_db: f64::from(n) as f32 * 1.5,
13016 q: 0.707,
13017 kind: crate::eq::BandKind::Peak,
13018 }],
13019 }
13020 }
13021
13022 /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
13023 /// for the colour table.
13024 fn grade_at(n: u32) -> ColorParams {
13025 ColorParams {
13026 brightness: f64::from(n) as f32 * 0.05,
13027 ..Default::default()
13028 }
13029 }
13030
13031 /// A recognisable placement, `n` telling two of them apart -- [`grade_at`]'s
13032 /// twin for the transform table.
13033 fn transform_at(n: u32) -> TransformParams {
13034 TransformParams {
13035 pos_x: f64::from(n) as f32 * 0.05,
13036 ..Default::default()
13037 }
13038 }
13039
13040 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
13041 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
13042 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
13043 }
13044
13045 /// Every lane with its group ids blanked, for comparing shape.
13046 fn shape(p: &Project) -> Vec<Vec<Clip>> {
13047 p.lanes()
13048 .into_iter()
13049 .map(|l| {
13050 p.lane(l)
13051 .iter()
13052 .map(|c| Clip {
13053 link: None,
13054 ..c.clone()
13055 })
13056 .collect()
13057 })
13058 .collect()
13059 }
13060
13061 /// The *source frame* every timeline frame reads, per lane -- the traversal
13062 /// a player performs. Deliberately not the clip index: a split changes which
13063 /// clip a frame belongs to, and nothing else.
13064 fn traversal(p: &Project) -> Vec<Vec<Option<u32>>> {
13065 (0..p.timeline_frames() + 2)
13066 .map(|f| {
13067 p.lanes()
13068 .into_iter()
13069 .map(|l| p.map(l, f).map(|(_, source)| source))
13070 .collect()
13071 })
13072 .collect()
13073 }
13074
13075 /// Source clips [0,3) [3,5) [5,9) on both lanes -- the ledger's off-by-one
13076 /// fixture. Built through `split` so the constructor path is exercised too.
13077 fn three() -> Project {
13078 let mut p = Project::single(FILE, 9);
13079 assert!(p.split(3));
13080 assert!(p.split(5));
13081 assert_eq!(
13082 shape(&p),
13083 [
13084 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13085 vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0), clip(5, 5, 9, 0)],
13086 ]
13087 );
13088 p
13089 }
13090
13091 #[test]
13092 fn single_is_the_whole_file_on_both_lanes() {
13093 let p = Project::single(FILE, 150);
13094 assert_eq!(p.clips().len(), 1);
13095 assert_eq!(p.lane(Lane::A1).len(), 1);
13096 assert_eq!(p.timeline_frames(), 150);
13097 assert_eq!(p.clip_spans(), vec![(0, 150)]);
13098 // grouped: video and audio carry the same link
13099 assert_eq!(p.clips()[0].link, p.lane(Lane::A1)[0].link);
13100 assert!(p.clips()[0].link.is_some());
13101 // degenerate mapping: timeline == source
13102 assert_eq!(p.map_timeline(0), Some((0, 0)));
13103 assert_eq!(p.map_timeline(149), Some((0, 149)));
13104 assert_eq!(p.map_timeline(150), None);
13105 // never-empty invariant survives a bogus frame count
13106 assert_eq!(Project::single(FILE, 0).timeline_frames(), 1);
13107 }
13108
13109 #[test]
13110 fn split_cuts_every_lane_and_regroups_it_back() {
13111 let mut p = Project::single(FILE, 9);
13112 let before = traversal(&p);
13113 let before_shape = shape(&p);
13114
13115 assert!(p.split(4));
13116 for l in p.lanes() {
13117 assert_eq!(p.lane(l).len(), 2, "{} split", l.label());
13118 }
13119 // The two sides are two groups, one per side, matching across the lanes.
13120 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
13121 assert_eq!(v[0].link, a[0].link);
13122 assert_eq!(v[1].link, a[1].link);
13123 assert_ne!(v[0].link, v[1].link, "the halves are no longer one take");
13124 // A split changes no mapping, in either lane.
13125 assert_eq!(traversal(&p), before, "a split moves nothing");
13126
13127 assert!(p.regroup(4), "the inverse rejoins them");
13128 assert_eq!(shape(&p), before_shape, "bit-exact back to one clip");
13129 assert_eq!(traversal(&p), before);
13130 assert_eq!(
13131 p.lane(Lane::V1)[0].link,
13132 p.lane(Lane::A1)[0].link,
13133 "and the rejoined clip is one group again"
13134 );
13135 }
13136
13137 /// [`Fade::gain_at`]'s curve at the edges and in the middle: silence at
13138 /// the very first frame of a fade-in, unity at its last, equal-power
13139 /// (`sin(pi/4)`) at its midpoint, and unity anywhere neither ramp reaches
13140 /// at all.
13141 #[test]
13142 fn clip_gain_set_clamps_refuses_and_undoes() {
13143 let mut p = Project::single(FILE, 150);
13144 let a1 = Lane::new(LaneKind::Audio, 0);
13145 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13146 assert!(p.set_clip_gain(a1, 0, -6.0));
13147 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13148 assert!(p.set_clip_gain(a1, 0, -100.0));
13149 assert_eq!(p.clip_gain(a1, 0), Some(-60.0), "clamped to the floor");
13150 assert!(!p.set_clip_gain(a1, 0, -60.0), "the same value is no step");
13151 assert!(!p.set_clip_gain(a1, 0, f32::NAN), "not finite");
13152 assert!(
13153 !p.set_clip_gain(Lane::V1, 0, -3.0),
13154 "a video clip takes no gain"
13155 );
13156 assert!(!p.set_clip_gain(a1, 5, -3.0), "no clip there");
13157 assert!(p.set_clip_gain(a1, 0, 30.0));
13158 assert_eq!(p.clip_gain(a1, 0), Some(24.0), "clamped to the ceiling");
13159 assert!(p.undo());
13160 assert_eq!(p.clip_gain(a1, 0), Some(-60.0));
13161 assert!(p.undo());
13162 assert_eq!(p.clip_gain(a1, 0), Some(-6.0));
13163 assert!(p.undo());
13164 assert_eq!(p.clip_gain(a1, 0), Some(0.0));
13165 }
13166
13167 #[test]
13168 fn gain_rides_the_envelope_and_a_split_carries_it_to_both_halves() {
13169 let mut p = Project::single(FILE, 150);
13170 let a1 = Lane::new(LaneKind::Audio, 0);
13171 assert!(p.set_clip_gain(a1, 0, -6.0));
13172 let fade = p.audio_fades_from(0, 30.0)[0][0]
13173 .clone()
13174 .expect("a gained clip has an envelope");
13175 assert!((fade.gain - 0.5012).abs() < 1e-3, "-6 dB is a linear 0.501");
13176 assert!(
13177 (fade.gain_at(75) - fade.gain).abs() < 1e-6,
13178 "no ramps: the gain alone"
13179 );
13180 assert!(p.split(60));
13181 assert_eq!(p.lane(a1).len(), 2);
13182 for c in p.lane(a1) {
13183 assert_eq!(c.gain_db, -6.0, "both halves keep the gain");
13184 }
13185 }
13186
13187 #[test]
13188 fn gain_envelope_is_linear_in_db_and_holds_at_both_ends() {
13189 let keys = [GainKey::new(10, -12.0), GainKey::new(20, 0.0)];
13190 assert_eq!(
13191 gain_keys_db_at(&keys, 15.0),
13192 -6.0,
13193 "the midpoint is the midpoint of the dB"
13194 );
13195 assert_eq!(gain_keys_db_at(&keys, 10.0), -12.0, "exact at a point");
13196 assert_eq!(gain_keys_db_at(&keys, 20.0), 0.0, "exact at the last point");
13197 assert_eq!(
13198 gain_keys_db_at(&keys, 0.0),
13199 -12.0,
13200 "held before the first point"
13201 );
13202 assert_eq!(
13203 gain_keys_db_at(&keys, 99.0),
13204 0.0,
13205 "held after the last point"
13206 );
13207 assert_eq!(gain_keys_db_at(&[], 5.0), 0.0, "no points is unity");
13208 let three = [
13209 GainKey::new(0, 0.0),
13210 GainKey::new(10, -20.0),
13211 GainKey::new(30, -20.0),
13212 ];
13213 assert_eq!(gain_keys_db_at(&three, 5.0), -10.0);
13214 assert_eq!(
13215 gain_keys_db_at(&three, 20.0),
13216 -20.0,
13217 "a flat run stays flat"
13218 );
13219 }
13220
13221 #[test]
13222 fn gain_keys_are_sorted_clamped_capped_and_refused_where_they_must_be() {
13223 let mut p = Project::single(FILE, 150);
13224 let a1 = Lane::new(LaneKind::Audio, 0);
13225 assert!(p.set_gain_keys(
13226 a1,
13227 0,
13228 vec![GainKey::new(30, -20.0), GainKey::new(0, 0.0)]
13229 ));
13230 assert_eq!(
13231 p.gain_keys_of(a1, 0),
13232 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13233 "sorted by source frame"
13234 );
13235 assert!(
13236 !p.set_gain_keys(
13237 a1,
13238 0,
13239 vec![GainKey::new(5, 1.0), GainKey::new(5, 2.0)]
13240 ),
13241 "two points at one source frame are refused"
13242 );
13243 assert!(
13244 !p.set_gain_keys(Lane::V1, 0, vec![GainKey::new(0, 0.0)]),
13245 "a video clip takes no envelope"
13246 );
13247 assert!(!p.set_gain_keys(a1, 9, Vec::new()), "no such clip");
13248 assert!(p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]));
13249 assert_eq!(p.gain_keys_of(a1, 0)[0].db, MAX_CLIP_GAIN_DB, "clamped");
13250 assert!(
13251 !p.set_gain_keys(a1, 0, vec![GainKey::new(0, 100.0)]),
13252 "an envelope already exactly so changes nothing, and costs no undo"
13253 );
13254 assert!(!p.set_gain_keys(
13255 a1,
13256 0,
13257 vec![GainKey::new(0, f32::NAN)]
13258 ));
13259 let over: Vec<GainKey> = (0..=MAX_GAIN_KEYS as u32)
13260 .map(|at| GainKey::new(at, 0.0))
13261 .collect();
13262 assert!(!p.set_gain_keys(a1, 0, over), "257 points is over the cap");
13263 let full: Vec<GainKey> = (0..MAX_GAIN_KEYS as u32)
13264 .map(|at| GainKey::new(at, 0.0))
13265 .collect();
13266 assert!(p.set_gain_keys(a1, 0, full), "256 is the cap itself");
13267 let extra = GainKey::new(9_999, 0.0);
13268 assert!(
13269 !p.add_gain_key(a1, 0, extra),
13270 "a 257th point through add is refused"
13271 );
13272 assert!(
13273 p.add_gain_key(a1, 0, GainKey::new(3, -3.0)),
13274 "a replacement still fits"
13275 );
13276 }
13277
13278 #[test]
13279 fn gain_keys_add_replace_remove_and_undo_each_take_one_step() {
13280 let mut p = Project::single(FILE, 150);
13281 let a1 = Lane::new(LaneKind::Audio, 0);
13282 assert!(p.add_gain_key(a1, 0, GainKey::new(0, 0.0)));
13283 assert!(p.add_gain_key(a1, 0, GainKey::new(30, -20.0)));
13284 assert!(
13285 p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13286 "same frame replaces"
13287 );
13288 assert_eq!(
13289 p.gain_keys_of(a1, 0),
13290 &[GainKey::new(0, 0.0), GainKey::new(30, -3.0)]
13291 );
13292 assert!(
13293 !p.add_gain_key(a1, 0, GainKey::new(30, -3.0)),
13294 "the point already there changes nothing"
13295 );
13296 assert!(p.remove_gain_key(a1, 0, 0));
13297 assert!(!p.remove_gain_key(a1, 0, 0), "no point left at 0");
13298 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(30, -3.0)]);
13299 assert!(p.undo());
13300 assert_eq!(p.gain_keys_of(a1, 0).len(), 2, "the removal undone");
13301 assert!(p.undo());
13302 assert_eq!(
13303 p.gain_keys_of(a1, 0),
13304 &[GainKey::new(0, 0.0), GainKey::new(30, -20.0)],
13305 "the replacement undone"
13306 );
13307 assert!(p.undo());
13308 assert_eq!(p.gain_keys_of(a1, 0), &[GainKey::new(0, 0.0)]);
13309 assert!(p.undo());
13310 assert!(p.gain_keys_of(a1, 0).is_empty(), "back to flat");
13311 assert!(!p.undo(), "and no step is left to take");
13312 }
13313
13314 #[test]
13315 fn gain_db_at_maps_timeline_to_source_through_in_point_and_speed() {
13316 let mut p = Project::single(FILE, 150);
13317 let a1 = Lane::new(LaneKind::Audio, 0);
13318 assert!(p.set_gain_keys(
13319 a1,
13320 0,
13321 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13322 ));
13323 assert!((p.gain_db_at(a1, 0, 50).unwrap() + 10.0).abs() < 1e-4);
13324 assert_eq!(
13325 p.gain_db_at(Lane::V1, 0, 50),
13326 None,
13327 "a video lane has no envelope"
13328 );
13329 assert_eq!(p.gain_db_at(a1, 3, 50), None, "no such clip");
13330 assert!(p.set_speed(a1, 0, Speed::from_permille(2000)).is_ok());
13331 assert!(
13332 (p.gain_db_at(a1, 0, 20).unwrap() + 8.0).abs() < 1e-3,
13333 "at 2x, timeline frame 20 plays source 40"
13334 );
13335 assert!(p.set_clip_gain(a1, 0, -6.0));
13336 assert!(
13337 (p.gain_db_at(a1, 0, 20).unwrap() + 14.0).abs() < 1e-3,
13338 "clip gain adds"
13339 );
13340 }
13341
13342 #[test]
13343 fn split_keeps_the_gain_curve_on_both_halves() {
13344 let mut p = Project::single(FILE, 150);
13345 let a1 = Lane::new(LaneKind::Audio, 0);
13346 assert!(p.set_gain_keys(
13347 a1,
13348 0,
13349 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)]
13350 ));
13351 let before: Vec<f32> = (0..150).map(|t| p.gain_db_at(a1, 0, t).unwrap()).collect();
13352 assert!(p.split(60));
13353 assert_eq!(p.lane(a1).len(), 2);
13354 for c in p.lane(a1) {
13355 assert_eq!(
13356 c.gain_keys,
13357 vec![GainKey::new(0, 0.0), GainKey::new(100, -20.0)],
13358 "both halves keep every point"
13359 );
13360 }
13361 let after: Vec<f32> = (0..150)
13362 .map(|t| p.gain_db_at(a1, usize::from(t >= 60), t).unwrap())
13363 .collect();
13364 assert_eq!(before, after, "the curve is unchanged by the cut");
13365 }
13366
13367 #[test]
13368 fn gain_envelope_rides_the_fade_in_timeline_frames_and_scales_to_audio() {
13369 let mut p = Project::single(FILE, 150);
13370 let a1 = Lane::new(LaneKind::Audio, 0);
13371 assert!(p.set_gain_keys(
13372 a1,
13373 0,
13374 vec![GainKey::new(0, 0.0), GainKey::new(30, -20.0)]
13375 ));
13376 let fade = p.lane_fades_from(a1, 0, 30.0)[0]
13377 .clone()
13378 .expect("an enveloped clip has a fade");
13379 let minus_ten = 10f32.powf(-10.0 / 20.0);
13380 assert!(
13381 (fade.gain_at(15) - minus_ten).abs() < 1e-4,
13382 "frame 15 is -10 dB, which is {}",
13383 fade.gain_at(15)
13384 );
13385 assert!(
13386 (fade.gain_at(45) - 0.1).abs() < 1e-4,
13387 "held at -20 dB past the last point"
13388 );
13389 let scaled = fade.clone().scaled(1000.0);
13390 assert!(
13391 (scaled.gain_at(15_000) - fade.gain_at(15)).abs() < 1e-4,
13392 "audio frames"
13393 );
13394 }
13395
13396 #[test]
13397 fn gain_at_is_silent_at_a_fades_edge_and_unity_in_the_body() {
13398 let f = Fade {
13399 elapsed: 0,
13400 fade_in: 10,
13401 fade_out: 10,
13402 total: 40,
13403 gain: 1.0,
13404 pan: (1.0, 1.0),
13405 curve: None,
13406 };
13407 assert_eq!(f.gain_at(0), 0.0, "silence at the very first frame");
13408 assert_eq!(f.gain_at(10), 1.0, "unity the frame the ramp ends");
13409 let midpoint = std::f32::consts::FRAC_PI_2 * 0.5;
13410 assert!(
13411 (f.gain_at(5) - midpoint.sin()).abs() < 1e-6,
13412 "equal-power midpoint is sin(pi/4)"
13413 );
13414 assert_eq!(
13415 f.gain_at(20),
13416 1.0,
13417 "unchanged in the body, past either ramp"
13418 );
13419 // The fade-out is the same curve, mirrored, counting down from the
13420 // clip's end: unity at the frame the ramp starts, the same
13421 // equal-power midpoint, and -- since `total` itself is one past the
13422 // clip's last valid frame -- the very last frame is one step short of
13423 // the silence a fade-in's own frame `0` lands on exactly.
13424 assert_eq!(f.gain_at(30), 1.0, "unity the frame the fade-out starts");
13425 assert!(
13426 (f.gain_at(35) - midpoint.sin()).abs() < 1e-6,
13427 "the fade-out's own equal-power midpoint"
13428 );
13429 assert!(
13430 (f.gain_at(39) - (std::f32::consts::FRAC_PI_2 * 0.1).sin()).abs() < 1e-6,
13431 "one step short of silence at the clip's last playable frame"
13432 );
13433 }
13434
13435 /// [`Project::crossfade`] refuses a non-audio lane and two clips that are
13436 /// not adjacent, and otherwise sets the shared edge's fades and nothing
13437 /// else.
13438 #[test]
13439 fn crossfade_only_joins_adjacent_audio_clips() {
13440 let mut p = Project::single(FILE, 20);
13441 assert!(p.split(10));
13442 assert!(!p.crossfade(Lane::V1, 0, 5), "video is not an audio lane");
13443 assert!(!p.crossfade(Lane::A1, 1, 5), "there is no clip after idx 1");
13444 assert!(p.crossfade(Lane::A1, 0, 5), "the two halves are adjacent");
13445 let a = p.lane(Lane::A1);
13446 assert_eq!(a[0].fade_out, 5);
13447 assert_eq!(a[1].fade_in, 5);
13448 assert_eq!(a[0].fade_in, 0);
13449 assert_eq!(a[1].fade_out, 0);
13450
13451 // A gap between two clips is not adjacency, even on an audio lane.
13452 let mut p2 = Project::single(FILE, 1);
13453 let a2 = p2.add_lane(LaneKind::Audio);
13454 assert!(p2.place(a2, 0, clip(0, 0, 3, 0)));
13455 assert!(p2.place(a2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13456 assert!(!p2.crossfade(a2, 0, 5), "a gap is not adjacent");
13457 }
13458
13459 /// The rule [`Project::write_split`] follows for the edge the razor makes:
13460 /// the left half keeps its old [`Clip::fade_in`] (clamped to its new,
13461 /// shorter length) and loses its [`Clip::fade_out`]; the right half is the
13462 /// mirror image.
13463 #[test]
13464 fn a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge() {
13465 let mut p = Project::single(FILE, 20);
13466 assert!(p.set_fade_in(Lane::V1, 0, 15));
13467 assert!(p.set_fade_out(Lane::V1, 0, 15));
13468 assert!(p.split(5));
13469 let v = p.lane(Lane::V1);
13470 assert_eq!(
13471 v[0].fade_in, 5,
13472 "the left half's kept fade-in, clamped to 5 frames"
13473 );
13474 assert_eq!(v[0].fade_out, 0, "the cut edge it made starts flat");
13475 assert_eq!(v[1].fade_in, 0, "the cut edge it made starts flat");
13476 assert_eq!(
13477 v[1].fade_out, 15,
13478 "the right half's kept fade-out, unclamped: 15 frames fit in 15"
13479 );
13480 }
13481
13482 /// [`Project::set_transition_out`] refuses a non-video lane, a clip with
13483 /// no successor, and two clips that do not touch, and otherwise clamps
13484 /// the dissolve to the shorter of the two clips it spans.
13485 #[test]
13486 fn set_transition_out_only_dissolves_adjacent_video_clips() {
13487 let mut p = Project::single(FILE, 20);
13488 assert!(p.split(15), "a short 5-frame tail to clamp against");
13489 assert!(
13490 !p.set_transition_out(Lane::A1, 0, 5),
13491 "audio is not a video lane"
13492 );
13493 assert!(
13494 !p.set_transition_out(Lane::V1, 1, 5),
13495 "there is no clip after idx 1"
13496 );
13497 assert!(
13498 p.set_transition_out(Lane::V1, 0, 100),
13499 "the two halves are adjacent"
13500 );
13501 assert_eq!(
13502 p.transition_out_of(Lane::V1, 0),
13503 5,
13504 "clamped to the shorter neighbour's 5 frames"
13505 );
13506
13507 // A gap between two clips is not adjacency, even on the video lane.
13508 let mut p2 = Project::single(FILE, 1);
13509 let v2 = p2.add_lane(LaneKind::Video);
13510 assert!(p2.place(v2, 0, clip(0, 0, 3, 0)));
13511 assert!(p2.place(v2, 5, clip(5, 3, 6, 0)), "a gap before this one");
13512 assert!(!p2.set_transition_out(v2, 0, 5), "a gap is not adjacent");
13513 }
13514
13515 /// The two transition doors' bool is the WEAK shape, stated here as
13516 /// behaviour rather than left as something a front-end has to know: both
13517 /// answer "these two clips are adjacent", and both snapshot and clamp --
13518 /// so a write that lands the value the join already carries is still
13519 /// reported as a write. The step it pushed changed nothing, so it is settled
13520 /// away and costs no undo step. The front-end's before/after comparison
13521 /// (`Player::transition_edges`) still decides what it shows.
13522 #[test]
13523 fn a_transition_door_says_yes_to_a_write_that_moved_nothing() {
13524 let mut p = Project::single(FILE, 20);
13525 assert!(p.split(10), "two halves to join");
13526 assert!(p.set_transition_out(Lane::V1, 0, 5), "the dissolve lands");
13527 assert!(p.crossfade(Lane::A1, 0, 5), "the crossfade lands");
13528 let history = p.history_len();
13529
13530 // The very same numbers again: nothing moved, and both doors report a
13531 // write anyway.
13532 assert!(
13533 p.set_transition_out(Lane::V1, 0, 5),
13534 "set_transition_out answers 'the clips are adjacent', not 'the \
13535 dissolve moved', so a no-op reads as a write"
13536 );
13537 assert!(
13538 p.crossfade(Lane::A1, 0, 5),
13539 "crossfade answers the same way for the same reason"
13540 );
13541 assert_eq!(
13542 p.history_len(),
13543 history,
13544 "and neither spent an undo step: a write that changed nothing is settled away"
13545 );
13546
13547 // What did not move -- the comparison the front-end makes: both edges
13548 // a crossfade writes, and the dissolve itself.
13549 let a = p.lane(Lane::A1);
13550 assert_eq!((a[0].fade_out, a[1].fade_in), (5, 5), "unchanged");
13551 assert_eq!(p.transition_out_of(Lane::V1, 0), 5, "unchanged");
13552
13553 // And a refusal still answers no, so the arm is not simply always on:
13554 // the last clip has no successor to dissolve into.
13555 assert!(
13556 !p.set_transition_out(Lane::V1, 1, 5),
13557 "no neighbour end to end"
13558 );
13559 }
13560
13561 /// The rule [`Project::write_split`] follows for [`Clip::transition_out`],
13562 /// same shape as [`a_split_clamps_the_kept_fade_and_zeroes_the_cut_edge`]:
13563 /// only the half that kept the clip's original *end* keeps the dissolve,
13564 /// re-clamped to its own now-shorter length; the head the cut just made
13565 /// has no successor to dissolve into and starts flat.
13566 #[test]
13567 fn a_split_clamps_the_tail_transition_and_zeroes_the_head() {
13568 let mut p = Project::single(FILE, 20);
13569 assert!(
13570 !p.set_transition_out(Lane::V1, 0, 0),
13571 "one clip on the lane, no successor to dissolve into yet"
13572 );
13573 // Give the clip a dissolve by hand, then cut it in two.
13574 p.lane_mut(Lane::V1).unwrap()[0].transition_out = 15;
13575 assert!(p.split(5));
13576 let v = p.lane(Lane::V1);
13577 assert_eq!(
13578 v[0].transition_out, 0,
13579 "the cut edge it made has no successor"
13580 );
13581 assert_eq!(
13582 v[1].transition_out, 15,
13583 "the tail's kept dissolve, unclamped: 15 frames fit in 15"
13584 );
13585 }
13586
13587 /// The music video's own path: the take comes apart into halves that carry
13588 /// ids of their own, one undo puts it back, and two clips over the same
13589 /// frames become one take again by hand.
13590 #[test]
13591 fn a_take_comes_apart_and_goes_back_together() {
13592 let mut p = Project::single(FILE, 9);
13593 let one = p.clips()[0].link.expect("a fresh project is one take");
13594 assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
13595
13596 // A third lane in the same group -- and the merge case with it: a
13597 // placement is in no group, and grouping it in leaves *one* group.
13598 let v2 = p.add_lane(LaneKind::Video);
13599 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
13600 assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
13601 p.group(Lane::V1, 0, v2, 0)
13602 .expect("the same frames, one lane over");
13603 let id = p.clips()[0].link.expect("still a group");
13604 assert!(
13605 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13606 "one id over the three, not two groups sharing a span"
13607 );
13608 links_are_consistent(&p.lanes).expect("one id, one span");
13609
13610 // Detached by the sound: every half of the group, not only the two.
13611 assert!(p.ungroup(Lane::A1, 0));
13612 let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
13613 assert!(
13614 ids.iter().all(Option::is_some),
13615 "a half keeps an id of its own"
13616 );
13617 assert!(
13618 ids.iter()
13619 .enumerate()
13620 .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
13621 "and no two halves are the same group any more: {ids:?}"
13622 );
13623 links_are_consistent(&p.lanes).expect("a lone id is legal");
13624
13625 // One snapshot for the whole detach.
13626 assert!(p.undo());
13627 assert!(
13628 p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
13629 "one undo puts the whole group back"
13630 );
13631
13632 // And back together by hand: the two the pointer named, and only them.
13633 assert!(p.ungroup(Lane::V1, 0));
13634 p.group(Lane::V1, 0, Lane::A1, 0)
13635 .expect("both cover [0, 9)");
13636 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
13637 assert_ne!(
13638 p.lane(v2)[0].link,
13639 p.lane(Lane::V1)[0].link,
13640 "the third half stayed detached"
13641 );
13642 links_are_consistent(&p.lanes).expect("one id, one span");
13643 }
13644
13645 /// What a group may not be, and what a detach has nothing to take apart --
13646 /// none of which may cost an undo step.
13647 #[test]
13648 fn a_group_is_one_span_and_one_clip_per_lane() {
13649 let mut p = three();
13650 let before = shape(&p);
13651 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
13652
13653 assert!(
13654 why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
13655 "two clips of one lane are never one take"
13656 );
13657 assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
13658 let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
13659 assert!(
13660 spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
13661 "{spans}"
13662 );
13663 assert!(
13664 spans.contains("trim them to matching bounds first"),
13665 "{spans}"
13666 );
13667 assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
13668
13669 // A half nothing else is grouped with is already detached, a placement
13670 // is in no group at all, and an index that is not there has nothing to
13671 // detach either.
13672 assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
13673 assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
13674 assert!(p.lift(Lane::A1, 0));
13675 assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
13676 assert!(!p.ungroup(Lane::V1, 9), "no clip there");
13677
13678 // Two undos, one per edit: not one of the refusals pushed a snapshot.
13679 assert!(p.undo());
13680 assert!(p.undo());
13681 assert_eq!(shape(&p), before);
13682 }
13683
13684 /// Where a re-rate puts a playhead: the scene under the cursor stays the
13685 /// scene under the cursor, measured the way a viewer would -- the source
13686 /// frame playing at the playhead is the same frame after the write, at
13687 /// every playhead position the re-rate can catch one.
13688 #[test]
13689 fn a_re_rate_keeps_the_frame_under_the_playhead() {
13690 let caption = |start: u32, frames: u32| SubClip {
13691 start,
13692 frames,
13693 track: 0,
13694 in_us: 0,
13695 out_us: i64::from(frames) * 1_000_000,
13696 link: None,
13697 };
13698 let track = || SubtitleTrack {
13699 path: FILE.into(),
13700 track: None,
13701 language: "eng".into(),
13702 name: String::new(),
13703 label: "eng".into(),
13704 cues: Vec::new(),
13705 bitmap: false,
13706 refused: None,
13707 };
13708 // A group of a 300-frame clip and a caption offset 30 frames into it.
13709 let mut p = Project::single(FILE, 300).with_subtitles(vec![track()]);
13710 let s1 = p.add_lane(LaneKind::Subtitle);
13711 p.place_sub(s1, 30, caption(30, 240)).expect("placed");
13712 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13713
13714 // The frame playing at `at`: which clip, and which source frame of it.
13715 let playing = |p: &Project, at: u32| -> Option<(usize, u32)> {
13716 p.span_at(Lane::V1, at).and_then(|s| s.from)
13717 };
13718
13719 // Inside the held clip: the source frame under the playhead is the
13720 // same one after the re-rate, at 2x and at half speed both.
13721 for (what, speed) in [("2x", 2000u16), ("half", 500)] {
13722 let at = 120;
13723 let before = playing(&p, at).expect("a clip under the playhead");
13724 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(speed), at);
13725 p.set_speed(Lane::V1, 0, Speed::from_permille(speed))
13726 .expect("room for it");
13727 let after = playing(&p, mapped.unwrap()).expect("still a clip there");
13728 assert_eq!(before, after, "{what}: the same source frame plays");
13729 // ...and the write itself is untouched by the question.
13730 assert!(p.undo(), "{what}: one step back");
13731 }
13732
13733 // Past the group -- the clip ends at 300 and the caption at 270, so
13734 // from 300 on nothing is re-timed under the playhead: unmoved.
13735 for at in [300u32, 301, 1_000] {
13736 assert_eq!(
13737 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at),
13738 Some(at),
13739 "at {at}: outside every member, unmoved"
13740 );
13741 }
13742 // The boundary is exact: the held clip's own last frame (299) maps
13743 // to its new one (149 -- the last frame inside [0, 150), where the
13744 // shrunken clip's last source frame plays), and its first stays put.
13745 assert_eq!(
13746 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 299),
13747 Some(149)
13748 );
13749 assert_eq!(
13750 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 0),
13751 Some(0)
13752 );
13753 // A spot the caption shares with the clip maps by the clip (it is
13754 // what is *playing* there): the held clip's own proportion, which on
13755 // this fixture is also its head.
13756 assert_eq!(
13757 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 90),
13758 Some(45),
13759 "the clip under the caption owns the spot"
13760 );
13761 }
13762
13763 /// A playhead inside another clip member of the group: that member keeps
13764 /// its own head, so the mapping is by its proportion and not the held
13765 /// clip's -- and the frame under the cursor is still the frame that was.
13766 #[test]
13767 fn a_re_rate_maps_a_second_clip_member_about_its_own_head() {
13768 let mut p = Project::single(FILE, 300);
13769 // A second clip, grouped with the first but starting 300 later: the
13770 // head the group shares and its own differ by exactly that.
13771 let v2 = p.add_lane(LaneKind::Video);
13772 assert!(p.lift(Lane::A1, 0), "the sound half stands aside");
13773 assert!(p.place(v2, 300, clip(300, 0, 300, 0)), "placed on v2");
13774 p.group_all(&[(Lane::V1, 0), (v2, 0)]).expect("grouped");
13775
13776 let at = 450; // inside the second member, 150 past its head
13777 let before = p.span_at(v2, at).and_then(|s| s.from);
13778 let mapped = p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), at);
13779 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
13780 .expect("room for it");
13781 let after = p.span_at(v2, mapped.unwrap()).and_then(|s| s.from);
13782 assert_eq!(before, after, "the second member's own frame plays");
13783 // ...and the mapping itself: 150 past its head halves, the head stays.
13784 assert_eq!(mapped, Some(375));
13785 }
13786
13787 /// The link counter a load seeds sits past every id the file names,
13788 /// captions included: a hand-grouped caption may carry the highest id there
13789 /// is, and a counter that read the clips alone would hand it to the next
13790 /// group that asked -- silently grouping the caption with clips it never
13791 /// met.
13792 #[test]
13793 fn the_link_counter_sits_past_a_caption_only_id() {
13794 let track = || SubtitleTrack {
13795 path: FILE.into(),
13796 track: None,
13797 language: "eng".into(),
13798 name: String::new(),
13799 label: "eng".into(),
13800 cues: Vec::new(),
13801 bitmap: false,
13802 refused: None,
13803 };
13804 let mut p = Project::single(FILE, 9);
13805 p.add_lane(LaneKind::Subtitle);
13806 let caption = SubClip {
13807 start: 0,
13808 frames: 6,
13809 track: 0,
13810 in_us: 0,
13811 out_us: 6_000_000,
13812 // The highest id in the file, and only a caption carries it.
13813 link: Some(1),
13814 };
13815 let mut p = p
13816 .with_subtitles(vec![track()])
13817 .with_subs(vec![Vec::new(), Vec::new(), vec![caption]])
13818 .expect("a caption may carry the file's highest id");
13819
13820 // A new group on lanes the caption is not on mints the next id -- which
13821 // must not be the caption's.
13822 let v2 = p.add_lane(LaneKind::Video);
13823 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
13824 p.group_all(&[(Lane::V1, 0), (v2, 0)])
13825 .expect("the clips group");
13826 let minted = p.lane(Lane::V1)[0].link.expect("grouped");
13827 assert_ne!(minted, 1, "the caption's id is not re-issued to clips");
13828 assert_eq!(
13829 p.sub_lane(Lane::new(LaneKind::Subtitle, 0))[0].link,
13830 Some(1),
13831 "the caption keeps its own group"
13832 );
13833 assert!(links_are_consistent(&p.lanes).is_ok());
13834 }
13835
13836 /// A rate re-times the caption members of the group by the ratio it gives
13837 /// the held clip: the span on the timeline compresses about the held clip's
13838 /// head, the words' own window untouched -- and one undo puts it back.
13839 #[test]
13840 fn a_rate_carries_the_group_caption_by_the_held_clips_ratio() {
13841 let caption = |start: u32, frames: u32| SubClip {
13842 start,
13843 frames,
13844 track: 0,
13845 in_us: 0,
13846 out_us: i64::from(frames) * 1_000_000,
13847 link: None,
13848 };
13849 let track = || SubtitleTrack {
13850 path: FILE.into(),
13851 track: None,
13852 language: "eng".into(),
13853 name: String::new(),
13854 label: "eng".into(),
13855 cues: Vec::new(),
13856 bitmap: false,
13857 refused: None,
13858 };
13859 let grouped = || {
13860 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
13861 let s1 = p.add_lane(LaneKind::Subtitle);
13862 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
13863 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13864 (p, s1)
13865 };
13866
13867 // An aligned take, doubled: the caption plays in half the frames.
13868 let (mut p, s1) = grouped();
13869 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
13870 .expect("room for it");
13871 assert_eq!(p.lane(Lane::V1)[0].frames(), 45);
13872 let s = p.sub_lane(s1)[0];
13873 assert_eq!(
13874 (s.start, s.frames),
13875 (0, 45),
13876 "same words, half the timeline"
13877 );
13878 assert_eq!(
13879 (s.in_us, s.out_us),
13880 (0, 90_000_000),
13881 "the window is untouched"
13882 );
13883 assert!(links_are_consistent(&p.lanes).is_ok());
13884 assert!(p.undo());
13885 assert_eq!(p.sub_lane(s1)[0].frames, 90, "one undo puts it back");
13886
13887 // An offset group, slowed to half: the caption's *offset from the held
13888 // clip's head* is what scales -- it sits 30 frames in at 1x, 60 at
13889 // 0.5x, and still ends where the clip does.
13890 let (mut p, s1) = grouped();
13891 p.lift_sub(s1, 0);
13892 p.place_sub(s1, 30, caption(30, 60)).expect("placed");
13893 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13894 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
13895 .expect("room for it");
13896 assert_eq!(p.lane(Lane::V1)[0].frames(), 180);
13897 let s = p.sub_lane(s1)[0];
13898 assert_eq!(
13899 (s.start, s.frames),
13900 (60, 120),
13901 "the offset doubles with the clip"
13902 );
13903 assert_eq!(
13904 s.end(),
13905 p.lane(Lane::V1)[0].end(),
13906 "still ends with the clip"
13907 );
13908
13909 // A stretch that runs the caption into its neighbour is refused, by
13910 // lane and frame, and costs no undo step.
13911 let (mut p, s1) = grouped();
13912 p.lift_sub(s1, 0);
13913 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
13914 p.place_sub(s1, 95, caption(95, 5)).expect("the neighbour");
13915 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
13916 let history = p.history.len();
13917 let err = p
13918 .set_speed(Lane::V1, 0, Speed::from_permille(500))
13919 .unwrap_err()
13920 .to_string();
13921 assert!(
13922 err.contains(
13923 "the S1 caption at frame 0 would run to frame 180 and the next starts at 95"
13924 ),
13925 "{err}"
13926 );
13927 assert_eq!(p.history.len(), history, "a refusal costs no undo step");
13928 }
13929
13930 /// The silence scan's speed-up re-times the captions on a scoped lane with
13931 /// everything else: the piece inside the region plays in the region's new
13932 /// frames, and what sits behind the region slides up with the clips.
13933 #[test]
13934 fn speeding_a_region_carries_the_captions_on_the_scoped_lanes() {
13935 let caption = |start: u32, frames: u32| SubClip {
13936 start,
13937 frames,
13938 track: 0,
13939 in_us: 0,
13940 out_us: i64::from(frames) * 1_000_000,
13941 link: None,
13942 };
13943 let track = || SubtitleTrack {
13944 path: FILE.into(),
13945 track: None,
13946 language: "eng".into(),
13947 name: String::new(),
13948 label: "eng".into(),
13949 cues: Vec::new(),
13950 bitmap: false,
13951 refused: None,
13952 };
13953 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
13954 let s1 = p.add_lane(LaneKind::Subtitle);
13955 // Words over the region [30, 60) and words behind it.
13956 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
13957 p.place_sub(s1, 60, caption(60, 30)).expect("placed");
13958
13959 // The region [30, 60) plays at 4x: 30 frames become 8, everything
13960 // behind slides up 22.
13961 // The scope is what the card's Take row says, caption lane included.
13962 p.speed_regions(
13963 &[(30, 30)],
13964 Speed::from_permille(4000),
13965 &[Lane::V1, Lane::A1, s1],
13966 )
13967 .expect("the region speeds up");
13968 let subs = p.sub_lane(s1);
13969 assert_eq!(
13970 (subs[0].start, subs[0].frames),
13971 (30, 8),
13972 "the piece inside plays in the region's new frames"
13973 );
13974 assert_eq!(
13975 (subs[1].start, subs[1].frames),
13976 (38, 30),
13977 "the piece behind slides up by what the region gave back"
13978 );
13979 assert!(subs_sorted_disjoint(&p.lanes[p.index(s1).unwrap()].subs));
13980 }
13981
13982 /// [`Project::speeded_playhead`]'s caption arm fires only when the
13983 /// playhead is inside a caption member and outside every clip member --
13984 /// a shape every other fixture avoids by keeping its caption inside the
13985 /// held clip. Here the caption overhangs the clip's tail, and the
13986 /// playhead standing in that overhang is answered by the caption's own
13987 /// piece: it scales about the held clip's head by the held clip's own
13988 /// proportion, same as [`write_speed`](Project::write_speed) re-times it.
13989 #[test]
13990 fn the_caption_arm_answers_a_playhead_in_the_overhang_past_its_clip() {
13991 let caption = |start: u32, frames: u32| SubClip {
13992 start,
13993 frames,
13994 track: 0,
13995 in_us: 0,
13996 out_us: i64::from(frames) * 1_000_000,
13997 link: None,
13998 };
13999 let track = || SubtitleTrack {
14000 path: FILE.into(),
14001 track: None,
14002 language: "eng".into(),
14003 name: String::new(),
14004 label: "eng".into(),
14005 cues: Vec::new(),
14006 bitmap: false,
14007 refused: None,
14008 };
14009 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14010 let s1 = p.add_lane(LaneKind::Subtitle);
14011 // The caption spans [80, 100) -- ten frames past the clip's own end
14012 // at 90 -- grouped with the clip so it re-times by the clip's ratio.
14013 p.place_sub(s1, 80, caption(80, 20)).expect("placed");
14014 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14015 // At 2x the clip halves to 45 frames; the overhang frame 95, which
14016 // no clip member's old span reaches, is the caption's own question:
14017 // half of 95 is 47.5, rounded to 48.
14018 assert_eq!(
14019 p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 95),
14020 Some(48),
14021 "the overhang frame answers through the caption's own piece"
14022 );
14023 }
14024
14025 /// `write_speed` and `speeded_playhead` are two questions of the SAME
14026 /// map ([`map`]'s architecture law): a caption's landed span comes from
14027 /// the map's own ends, and the playhead standing at the caption's own
14028 /// last frame before the write has to land exactly where the write put
14029 /// it -- across clip lengths and rates that round differently, and an
14030 /// odd-length caption straddling the clip's own tail edge, the corner
14031 /// where `write_speed` used to answer a frame short.
14032 #[test]
14033 fn write_speed_and_speeded_playhead_agree_at_a_captions_own_last_frame() {
14034 let caption = |start: u32, frames: u32| SubClip {
14035 start,
14036 frames,
14037 track: 0,
14038 in_us: 0,
14039 out_us: i64::from(frames) * 1_000_000,
14040 link: None,
14041 };
14042 let track = || SubtitleTrack {
14043 path: FILE.into(),
14044 track: None,
14045 language: "eng".into(),
14046 name: String::new(),
14047 label: "eng".into(),
14048 cues: Vec::new(),
14049 bitmap: false,
14050 refused: None,
14051 };
14052 for &len in &[90u32, 91, 177, 300, 301] {
14053 for &permille in &[500u16, 2000, 2500, 3000] {
14054 let mut p = Project::single(FILE, len).with_subtitles(vec![track()]);
14055 let s1 = p.add_lane(LaneKind::Subtitle);
14056 // An odd-length caption straddling the clip's tail edge: its
14057 // own last frame lands past the held clip.
14058 let c_start = len.saturating_sub(3);
14059 p.place_sub(s1, c_start, caption(c_start, 7))
14060 .expect("placed");
14061 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14062 let speed = Speed::from_permille(permille);
14063 let last = c_start + 7 - 1;
14064 let mapped = p
14065 .speeded_playhead(Lane::V1, 0, speed, last)
14066 .expect("the caption is there");
14067 if p.set_speed(Lane::V1, 0, speed).is_err() {
14068 continue; // a refusal changes nothing: not this law's cell
14069 }
14070 let landed = p.sub_lane(s1)[0];
14071 if permille >= 1000 {
14072 // A speed-up compresses the timeline: many old frames
14073 // share one new frame, so the caption's own last old
14074 // frame lands flush with the write's own boundary --
14075 // the exact law [`write_speed`]'s worked drift-fix case
14076 // is stated against.
14077 assert_eq!(
14078 mapped,
14079 landed.end() - 1,
14080 "len {len} permille {permille}: the playhead at the caption's own \
14081 last frame lands where the write actually put it"
14082 );
14083 } else {
14084 // A slow-down expands it: one old frame becomes several
14085 // new ones, and `apply` answers where that frame's own
14086 // block *starts*, not where the caption's last new
14087 // frame (the end of that same block) sits -- a
14088 // one-frame gap inherent to the piece's own semantics,
14089 // not a drift between the two callers. Both still have
14090 // to agree the answer sits inside the caption the write
14091 // actually landed.
14092 assert!(
14093 (landed.start..landed.end()).contains(&mapped),
14094 "len {len} permille {permille}: the playhead lands inside the \
14095 caption the write actually put ({landed:?}), got {mapped}"
14096 );
14097 }
14098 }
14099 }
14100 }
14101
14102 /// A grouped caption's cues re-time with its clip: the placement's window
14103 /// crossed the timeline at its own proportion before any rate, and a
14104 /// re-rate changes that proportion (the frames compress, the window does
14105 /// not). A cue eight seconds into a window played at 2x crosses the screen
14106 /// four seconds in -- and at unity every cue lands exactly where it always
14107 /// did, byte for byte.
14108 #[test]
14109 fn a_grouped_captions_cues_re_time_with_its_clip() {
14110 let track = SubtitleTrack {
14111 path: FILE.into(),
14112 track: None,
14113 language: "eng".into(),
14114 name: String::new(),
14115 label: "eng".into(),
14116 cues: vec![crate::subtitle::Cue {
14117 start_us: 8_000_000,
14118 end_us: 9_000_000,
14119 text: "late line".into(),
14120 image: None,
14121 words: Vec::new(),
14122 karaoke: Vec::new(),
14123 }],
14124 bitmap: false,
14125 refused: None,
14126 };
14127 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
14128 let s1 = p.add_lane(LaneKind::Subtitle);
14129 // Ten seconds of the track over ten seconds of timeline: unity.
14130 p.place_sub(
14131 s1,
14132 0,
14133 SubClip {
14134 start: 0,
14135 frames: 300,
14136 track: 0,
14137 in_us: 0,
14138 out_us: 10_000_000,
14139 link: None,
14140 },
14141 )
14142 .expect("placed");
14143
14144 // Unity: the cue sits at its own [8s, 9s), to the microsecond.
14145 let unity = p.sub_lane_cues(s1, FPS);
14146 assert_eq!(
14147 unity
14148 .iter()
14149 .map(|c| (c.start_us, c.end_us, &*c.text))
14150 .collect::<Vec<_>>(),
14151 [(8_000_000, 9_000_000, "late line")],
14152 "a unity placement maps exactly as it always did"
14153 );
14154
14155 // Grouped with the clip and re-rated to 2x: the same window now crosses
14156 // in half the time, so the cue at 8s of it lands 4s in.
14157 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14158 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
14159 .expect("room for it");
14160 let re_timed = p.sub_lane_cues(s1, FPS);
14161 assert_eq!(
14162 re_timed
14163 .iter()
14164 .map(|c| (c.start_us, c.end_us))
14165 .collect::<Vec<_>>(),
14166 [(4_000_000, 4_500_000)],
14167 "the cue crosses with the clip's new rate"
14168 );
14169 }
14170
14171 /// A video arriving on a timeline of words mutates none of them: the
14172 /// import's rippling insert used to open room on the subtitle lanes too,
14173 /// splitting a caption it landed inside and sliding the rest behind the
14174 /// video -- the hand asked for an add, and got a cut it never made. The
14175 /// words keep their own clock; co-travel is what a group is for.
14176 #[test]
14177 fn an_arriving_clip_never_touches_the_captions() {
14178 let caption = |start: u32, frames: u32| SubClip {
14179 start,
14180 frames,
14181 track: 0,
14182 in_us: i64::from(start) * 1_000_000 / 30,
14183 out_us: i64::from(start + frames) * 1_000_000 / 30,
14184 link: None,
14185 };
14186 let track = || SubtitleTrack {
14187 path: FILE.into(),
14188 track: None,
14189 language: "eng".into(),
14190 name: String::new(),
14191 label: "eng".into(),
14192 cues: Vec::new(),
14193 bitmap: false,
14194 refused: None,
14195 };
14196 // A timeline of words alone: 60 frames of caption, no media clips.
14197 let mut p = Project::single(FILE, 60).with_subtitles(vec![track()]);
14198 for l in [Lane::V1, Lane::A1] {
14199 while !p.lane(l).is_empty() {
14200 p.lift(l, 0);
14201 }
14202 }
14203 let s1 = p.add_lane(LaneKind::Subtitle);
14204 p.place_sub(s1, 0, caption(0, 60)).expect("placed");
14205 let before = p.sub_lane(s1).to_vec();
14206
14207 // The video lands BEFORE the caption's span: nothing moves.
14208 let vid = clip(0, 0, 30, 0);
14209 assert!(p.paste(0, vid.clone()), "the video goes down at the head");
14210 assert_eq!(p.sub_lane(s1), &before[..], "the caption keeps its clock");
14211
14212 // ...and OVERLAPPING it, dead centre: no split, no shift, byte for
14213 // byte the placement the hand made.
14214 assert!(p.paste(15, vid), "a second video lands inside the caption");
14215 assert_eq!(p.sub_lane(s1), &before[..], "still one caption, unmoved");
14216 assert_eq!(p.sub_lane(s1).len(), 1, "and uncut");
14217 assert_eq!(p.lane(Lane::V1).len(), 3, "the videos landed");
14218 assert!(links_are_consistent(&p.lanes).is_ok());
14219 }
14220
14221 /// The region's caption pieces re-time by mapped boundaries forced apart:
14222 /// rounding start and length independently can land two cues on one frame,
14223 /// and the artifact is clamped -- one frame each, in order, none past the
14224 /// region's new end -- never an overlap on the lane.
14225 #[test]
14226 fn a_regions_caption_pieces_never_round_onto_one_another() {
14227 let caption = |start: u32, frames: u32| SubClip {
14228 start,
14229 frames,
14230 track: 0,
14231 in_us: 0,
14232 out_us: i64::from(frames) * 1_000_000,
14233 link: None,
14234 };
14235 let track = |n| SubtitleTrack {
14236 path: FILE.into(),
14237 track: None,
14238 language: "eng".into(),
14239 name: String::new(),
14240 label: format!("eng{n}"),
14241 cues: Vec::new(),
14242 bitmap: false,
14243 refused: None,
14244 };
14245 // Three lanes, one repro shape each: adjacent one-frame cues, a
14246 // three-frame pair, and the region's last cue against the first
14247 // caption behind it. The region [0, 30) plays at 2x: 15 frames.
14248 let mut p = Project::single(FILE, 60).with_subtitles(vec![track(0), track(1), track(2)]);
14249 let lanes: Vec<Lane> = (0..3).map(|_| p.add_lane(LaneKind::Subtitle)).collect();
14250 p.place_sub(lanes[0], 9, caption(9, 1)).expect("placed");
14251 p.place_sub(lanes[0], 10, caption(10, 1)).expect("placed");
14252 p.place_sub(lanes[1], 5, caption(5, 3)).expect("placed");
14253 p.place_sub(lanes[1], 8, caption(8, 3)).expect("placed");
14254 p.place_sub(lanes[2], 29, caption(29, 1)).expect("placed");
14255 p.place_sub(lanes[2], 30, caption(30, 15)).expect("placed");
14256
14257 let mut scope = vec![Lane::V1, Lane::A1];
14258 scope.extend(lanes.iter().copied());
14259 p.speed_regions(&[(0, 30)], Speed::from_permille(2000), &scope)
14260 .expect("the region speeds up");
14261 // Adjacent one-frame cues: both map to frame 5, and are forced apart.
14262 let spans = |p: &Project, lane: Lane| -> Vec<(u32, u32)> {
14263 p.sub_lane(lane)
14264 .iter()
14265 .map(|s| (s.start, s.frames))
14266 .collect()
14267 };
14268 assert_eq!(
14269 spans(&p, lanes[0]),
14270 [(5, 1), (6, 1)],
14271 "one frame each, in order"
14272 );
14273 // The three-frame pair: [5, 8) and [8, 11) map to [3, 5) and [4, 6),
14274 // and the walk pushes the second to where the first ends.
14275 assert_eq!(
14276 spans(&p, lanes[1]),
14277 [(3, 1), (4, 2)],
14278 "forced apart, kept in order"
14279 );
14280 // The last cue of the region ends exactly where the region now does
14281 // (frame 15), and the caption behind it lands on that same frame:
14282 // touching, never overlapping.
14283 assert_eq!(
14284 spans(&p, lanes[2]),
14285 [(14, 1), (15, 15)],
14286 "the cue ends with the region"
14287 );
14288 for &lane in &lanes {
14289 assert!(subs_sorted_disjoint(&p.lanes[p.index(lane).unwrap()].subs));
14290 }
14291 }
14292
14293 /// The scope law names a caption half too: a scoped cut that would move one
14294 // track of a group whose caption sits outside the scope is refused.
14295 #[test]
14296 fn the_scope_law_refuses_a_caption_half_outside_the_scope() {
14297 let caption = |start: u32, frames: u32| SubClip {
14298 start,
14299 frames,
14300 track: 0,
14301 in_us: 0,
14302 out_us: i64::from(frames) * 1_000_000,
14303 link: None,
14304 };
14305 let track = || SubtitleTrack {
14306 path: FILE.into(),
14307 track: None,
14308 language: "eng".into(),
14309 name: String::new(),
14310 label: "eng".into(),
14311 cues: Vec::new(),
14312 bitmap: false,
14313 refused: None,
14314 };
14315 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14316 let s1 = p.add_lane(LaneKind::Subtitle);
14317 p.place_sub(s1, 0, caption(0, 90)).expect("placed");
14318 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14319
14320 // The subtitle lane is not in the scope, so the group's caption half
14321 // sits outside it: refused, in the law's own words.
14322 let err = p
14323 .cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1])
14324 .unwrap_err()
14325 .to_string();
14326 assert!(
14327 err.contains("is one take with the S1 caption at frame 0"),
14328 "{err}"
14329 );
14330
14331 // ...and with the caption's lane in the scope, the cut carries it:
14332 // the words over the hole go, and the words behind slide up.
14333 p.cut_regions(&[(10, 5)], &[Lane::V1, Lane::A1, s1])
14334 .expect("the whole group is in the scope");
14335 let subs = p.sub_lane(s1);
14336 assert_eq!(
14337 subs.iter().map(|s| (s.start, s.frames)).collect::<Vec<_>>(),
14338 [(0, 10), (10, 75)],
14339 "the caption is cut and shifted with the clips"
14340 );
14341 }
14342
14343 /// The caption a hand groups: `group_all` over clips *and* a caption, the
14344 /// mates riding along, the offsets kept, the refusals in words.
14345 #[test]
14346 fn a_hand_built_group_holds_clips_and_a_caption() {
14347 let caption = |start: u32, frames: u32| SubClip {
14348 start,
14349 frames,
14350 track: 0,
14351 in_us: 0,
14352 out_us: i64::from(frames) * 1_000_000,
14353 link: None,
14354 };
14355 let track = || SubtitleTrack {
14356 path: FILE.into(),
14357 track: None,
14358 language: "eng".into(),
14359 name: String::new(),
14360 label: "eng".into(),
14361 cues: Vec::new(),
14362 bitmap: false,
14363 refused: None,
14364 };
14365 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14366 let v2 = p.add_lane(LaneKind::Video);
14367 let s1 = p.add_lane(LaneKind::Subtitle);
14368 // A layer at its own offset, and a caption over the head of the take.
14369 assert!(p.place(v2, 2, clip(2, 0, 7, 0)));
14370 p.place_sub(s1, 0, caption(0, 6)).expect("placed");
14371
14372 // Too few, one lane twice, and an index that is not there: words, no
14373 // snapshot.
14374 let history = p.history.len();
14375 assert!(
14376 p.group_all(&[])
14377 .unwrap_err()
14378 .to_string()
14379 .contains("two placements or more")
14380 );
14381 assert!(
14382 p.group_all(&[(Lane::V1, 0), (Lane::V1, 0)])
14383 .unwrap_err()
14384 .to_string()
14385 .contains("V1 is picked twice")
14386 );
14387 assert!(
14388 p.group_all(&[(Lane::V1, 0), (s1, 9)])
14389 .unwrap_err()
14390 .to_string()
14391 .contains("no subtitle 9")
14392 );
14393 assert_eq!(p.history.len(), history, "refusals cost no undo step");
14394
14395 // The group: the picture, the layer, and the caption -- and the sound
14396 // the picture was already grouped with comes along unasked.
14397 p.group_all(&[(Lane::V1, 0), (v2, 0), (s1, 0)])
14398 .expect("three picks, three lanes");
14399 let id = p.lane(Lane::V1)[0].link.expect("grouped");
14400 for lane in [Lane::V1, Lane::A1, v2] {
14401 assert_eq!(
14402 p.lane(lane)[0].link,
14403 Some(id),
14404 "{} rides along",
14405 lane.label()
14406 );
14407 }
14408 assert_eq!(p.sub_lane(s1)[0].link, Some(id), "the caption is a member");
14409 assert_eq!(p.sub_lane(s1)[0].frames, 6, "its own span, kept");
14410 assert_eq!(p.lane(v2)[0].start, 2, "the layer's offset, kept");
14411 assert!(links_are_consistent(&p.lanes).is_ok());
14412 assert_eq!(p.history.len(), history + 1, "one snapshot for the group");
14413
14414 // ...and one undo takes it apart again.
14415 assert!(p.undo());
14416 assert_eq!(p.sub_lane(s1)[0].link, None, "the caption is loose again");
14417
14418 // Detach names a caption like it names a clip: every member an id of
14419 // its own, which is never `None` (see `ungroup`).
14420 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("two picks");
14421 assert!(p.ungroup(s1, 0));
14422 let (loose_sub, loose_clip) = (p.sub_lane(s1)[0].link, p.lane(Lane::V1)[0].link);
14423 assert!(loose_sub.is_some() && loose_clip.is_some());
14424 assert_ne!(loose_sub, loose_clip);
14425 assert!(links_are_consistent(&p.lanes).is_ok());
14426 }
14427
14428 /// Two captions on one sub lane, each already grouped with a *different*
14429 /// clip: `group_all` over both those clips would merge the two existing
14430 /// groups into one id and leave both captions on `s1` carrying it --
14431 /// `links_are_consistent`'s one-member-per-lane law broken the moment the
14432 /// group closes. Refused by name, and nothing moves.
14433 #[test]
14434 fn group_all_refuses_a_merge_that_doubles_up_a_lane() {
14435 let caption = |start: u32, frames: u32| SubClip {
14436 start,
14437 frames,
14438 track: 0,
14439 in_us: 0,
14440 out_us: i64::from(frames) * 1_000_000,
14441 link: None,
14442 };
14443 let track = || SubtitleTrack {
14444 path: FILE.into(),
14445 track: None,
14446 language: "eng".into(),
14447 name: String::new(),
14448 label: "eng".into(),
14449 cues: Vec::new(),
14450 bitmap: false,
14451 refused: None,
14452 };
14453 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14454 let v2 = p.add_lane(LaneKind::Video);
14455 let s1 = p.add_lane(LaneKind::Subtitle);
14456 assert!(p.place(v2, 0, clip(0, 0, 90, 0)));
14457 p.place_sub(s1, 0, caption(0, 30)).expect("placed");
14458 p.place_sub(s1, 30, caption(30, 30)).expect("placed");
14459 // V1 grouped with the first caption, v2 with the second -- two
14460 // separate groups, each already one member per lane.
14461 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14462 p.group_all(&[(v2, 0), (s1, 1)]).expect("grouped");
14463 let (v1_link, v2_link) = (p.lane(Lane::V1)[0].link, p.lane(v2)[0].link);
14464
14465 let history = p.history.len();
14466 let err = p
14467 .group_all(&[(Lane::V1, 0), (v2, 0)])
14468 .unwrap_err()
14469 .to_string();
14470 assert!(err.contains("one placement per lane"), "{err}");
14471 assert_eq!(p.history.len(), history, "the refusal costs no undo step");
14472 assert_eq!(
14473 p.lane(Lane::V1)[0].link,
14474 v1_link,
14475 "the first group untouched"
14476 );
14477 assert_eq!(p.lane(v2)[0].link, v2_link, "the second group untouched");
14478 assert!(links_are_consistent(&p.lanes).is_ok());
14479 }
14480
14481 /// A split hands the caption of a group the same ids it hands the clips:
14482 /// the left halves keep the group, the right halves share a fresh one.
14483 #[test]
14484 fn a_split_cuts_a_grouped_caption_with_its_clips() {
14485 let caption = |start: u32, frames: u32| SubClip {
14486 start,
14487 frames,
14488 track: 0,
14489 in_us: 0,
14490 out_us: i64::from(frames) * 1_000_000,
14491 link: None,
14492 };
14493 let track = || SubtitleTrack {
14494 path: FILE.into(),
14495 track: None,
14496 language: "eng".into(),
14497 name: String::new(),
14498 label: "eng".into(),
14499 cues: Vec::new(),
14500 bitmap: false,
14501 refused: None,
14502 };
14503 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14504 let s1 = p.add_lane(LaneKind::Subtitle);
14505 p.place_sub(s1, 0, caption(0, 9)).expect("placed");
14506 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14507 let take = p.lane(Lane::V1)[0].link.expect("the group id");
14508
14509 assert!(p.split(4));
14510 let (left, right) = (p.sub_lane(s1)[0], p.sub_lane(s1)[1]);
14511 assert_eq!(left.link, Some(take), "the caption's head keeps the group");
14512 assert_eq!(left.frames, 4);
14513 assert_eq!(
14514 right.link,
14515 p.lane(Lane::V1)[1].link,
14516 "the caption's tail shares the clips' fresh id"
14517 );
14518 assert_ne!(right.link, Some(take));
14519 assert!(links_are_consistent(&p.lanes).is_ok());
14520
14521 // Regroup at the seam restores the take, caption included.
14522 assert!(p.regroup(4));
14523 assert_eq!(p.sub_lane(s1).len(), 1, "the caption rejoined");
14524 assert_eq!(p.sub_lane(s1)[0].link, Some(take));
14525 }
14526
14527 /// Deleting a member of a hand-built group takes the group: every
14528 /// member's own span out of its own lane, hole closed -- the lanes may
14529 /// end up out of step, which is what one undo restores together.
14530 #[test]
14531 fn deleting_a_grouped_clip_ripples_every_members_own_lane() {
14532 let caption = |start: u32, frames: u32| SubClip {
14533 start,
14534 frames,
14535 track: 0,
14536 in_us: 0,
14537 out_us: i64::from(frames) * 1_000_000,
14538 link: None,
14539 };
14540 let track = || SubtitleTrack {
14541 path: FILE.into(),
14542 track: None,
14543 language: "eng".into(),
14544 name: String::new(),
14545 label: "eng".into(),
14546 cues: Vec::new(),
14547 bitmap: false,
14548 refused: None,
14549 };
14550 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14551 let s1 = p.add_lane(LaneKind::Subtitle);
14552 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14553 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14554 // A neighbour on a lane the group does not touch.
14555 let v2 = p.add_lane(LaneKind::Video);
14556 assert!(p.place(v2, 10, clip(10, 0, 3, 0)));
14557
14558 // By the picture or by the caption, the same whole-group delete.
14559 assert!(p.delete_sub_in(s1, 0));
14560 assert!(p.lane(Lane::V1).is_empty(), "the take's span left V1");
14561 assert!(
14562 p.sub_lane(s1).is_empty(),
14563 "the caption's span left its lane"
14564 );
14565 assert_eq!(
14566 p.lane(v2)[0].start,
14567 10,
14568 "a lane the group does not touch stays"
14569 );
14570 assert!(links_are_consistent(&p.lanes).is_ok());
14571 assert!(p.undo(), "one step puts the group back");
14572 assert_eq!(p.sub_lane(s1)[0].start, 2, "offsets and all");
14573 }
14574
14575 /// The delete law, one statement for every anchor: a caption deleted
14576 /// WITH its group ripples its lane exactly as its clip siblings do --
14577 /// the hole closes and what follows slides up -- while a caption lifted
14578 /// alone leaves its gap, as it always has. And the delete of a grouped
14579 /// clip takes the group from whichever member was clicked.
14580 #[test]
14581 fn a_grouped_delete_closes_the_caption_lane_and_takes_the_group_from_every_anchor() {
14582 let caption = |start: u32, frames: u32| SubClip {
14583 start,
14584 frames,
14585 track: 0,
14586 in_us: 0,
14587 out_us: i64::from(frames) * 1_000_000,
14588 link: None,
14589 };
14590 let track = || SubtitleTrack {
14591 path: FILE.into(),
14592 track: None,
14593 language: "eng".into(),
14594 name: String::new(),
14595 label: "eng".into(),
14596 cues: Vec::new(),
14597 bitmap: false,
14598 refused: None,
14599 };
14600 // V+A+S grouped, with a second caption BEHIND the group's caption:
14601 // closing the hole is what the second caption's position says.
14602 let group = || {
14603 let mut p = Project::single(FILE, 90).with_subtitles(vec![track()]);
14604 let s1 = p.add_lane(LaneKind::Subtitle);
14605 p.place_sub(s1, 30, caption(30, 30))
14606 .expect("the group's caption");
14607 p.place_sub(s1, 90, caption(90, 30))
14608 .expect("the caption behind");
14609 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14610 (p, s1)
14611 };
14612
14613 // Deleted by the picture: all three lanes close.
14614 let (mut p, s1) = group();
14615 assert!(p.delete_in(Lane::V1, 0));
14616 assert!(p.lane(Lane::V1).is_empty(), "the clip's span left V1");
14617 assert!(p.lane(Lane::A1).is_empty(), "and the sound's");
14618 assert_eq!(
14619 p.sub_lane(s1).iter().map(|s| s.start).collect::<Vec<_>>(),
14620 [60],
14621 "the caption's lane closed by its own span: the follower slid up"
14622 );
14623 assert!(p.undo(), "one step");
14624 assert_eq!(
14625 p.sub_lane(s1).len(),
14626 2,
14627 "both captions back, offsets and all"
14628 );
14629
14630 // By the sound: the same whole-group delete.
14631 let (mut p, s1) = group();
14632 assert!(p.delete_in(Lane::A1, 0));
14633 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14634 assert_eq!(p.sub_lane(s1)[0].start, 60, "the caption lane closed too");
14635
14636 // By the caption itself: the same again.
14637 let (mut p, s1) = group();
14638 assert!(p.delete_sub_in(s1, 0));
14639 assert!(p.lane(Lane::V1).is_empty() && p.lane(Lane::A1).is_empty());
14640 assert_eq!(
14641 p.sub_lane(s1)[0].start,
14642 60,
14643 "closed from the caption's own door"
14644 );
14645 assert!(links_are_consistent(&p.lanes).is_ok());
14646
14647 // A caption lifted ALONE still leaves its gap: the ungrouped law,
14648 // unchanged.
14649 let (mut p, s1) = group();
14650 assert!(p.ungroup(s1, 0), "the caption stands alone");
14651 assert!(p.lift_sub(s1, 0));
14652 assert_eq!(
14653 p.sub_lane(s1)[0].start,
14654 90,
14655 "the follower stayed put: a lone caption's lift is a gap"
14656 );
14657 }
14658
14659 /// Dragging a grouped caption carries its clips, one delta for all of them
14660 /// -- and a caption in no group refuses an overlap exactly as it always did.
14661 #[test]
14662 fn dragging_a_grouped_caption_carries_its_group() {
14663 let caption = |start: u32, frames: u32| SubClip {
14664 start,
14665 frames,
14666 track: 0,
14667 in_us: 0,
14668 out_us: i64::from(frames) * 1_000_000,
14669 link: None,
14670 };
14671 let track = || SubtitleTrack {
14672 path: FILE.into(),
14673 track: None,
14674 language: "eng".into(),
14675 name: String::new(),
14676 label: "eng".into(),
14677 cues: Vec::new(),
14678 bitmap: false,
14679 refused: None,
14680 };
14681 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14682 let s1 = p.add_lane(LaneKind::Subtitle);
14683 p.place_sub(s1, 2, caption(2, 4)).expect("placed");
14684 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14685
14686 // Same lane, further along: everyone moves by the same eight frames.
14687 p.move_sub(s1, 0, s1, 10).expect("room for all of it");
14688 assert_eq!(p.sub_lane(s1)[0].start, 10);
14689 assert_eq!(
14690 p.lane(Lane::V1)[0].start,
14691 8,
14692 "the clip follows by the delta"
14693 );
14694 assert!(links_are_consistent(&p.lanes).is_ok());
14695
14696 // ...and an ungrouped caption is the caption it always was.
14697 assert!(p.ungroup(s1, 0));
14698 let mut q = Project::single(FILE, 9).with_subtitles(vec![track()]);
14699 let s1 = q.add_lane(LaneKind::Subtitle);
14700 q.place_sub(s1, 0, caption(0, 4)).expect("placed");
14701 q.place_sub(s1, 5, caption(5, 4)).expect("placed");
14702 assert!(
14703 q.move_sub(s1, 0, s1, 3)
14704 .unwrap_err()
14705 .to_string()
14706 .contains("already covers")
14707 );
14708 }
14709
14710 /// A trim carries a group's caption by the same delta as its clips, clamped
14711 /// to the caption's own walls -- the offsets between the members survive.
14712 #[test]
14713 fn trimming_a_grouped_clip_carries_the_caption_by_the_same_delta() {
14714 let caption = |start: u32, frames: u32| SubClip {
14715 start,
14716 frames,
14717 track: 0,
14718 in_us: 0,
14719 out_us: i64::from(frames) * 1_000_000,
14720 link: None,
14721 };
14722 let track = || SubtitleTrack {
14723 path: FILE.into(),
14724 track: None,
14725 language: "eng".into(),
14726 name: String::new(),
14727 label: "eng".into(),
14728 cues: Vec::new(),
14729 bitmap: false,
14730 refused: None,
14731 };
14732 let mut p = Project::single(FILE, 9).with_subtitles(vec![track()]);
14733 let s1 = p.add_lane(LaneKind::Subtitle);
14734 // The caption sits two frames into the take and ends one early. The
14735 // source runs past the clip, or there is no tail to pull out.
14736 let src = &[20];
14737 p.place_sub(s1, 2, caption(2, 6)).expect("placed");
14738 p.group_all(&[(Lane::V1, 0), (s1, 0)]).expect("grouped");
14739
14740 // The tail goes out by three: the clip to 12, the caption to 11.
14741 assert!(p.trim(Lane::V1, 0, Edge::End, 12, src));
14742 assert_eq!(p.lane(Lane::V1)[0].end(), 12);
14743 assert_eq!(
14744 (p.sub_lane(s1)[0].start, p.sub_lane(s1)[0].end()),
14745 (2, 11),
14746 "the caption follows by the delta"
14747 );
14748 assert!(p.sub_lane(s1)[0].out_us > p.sub_lane(s1)[0].in_us);
14749
14750 // The head comes in by two: everyone's start moves two along.
14751 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, src));
14752 assert_eq!(p.sub_lane(s1)[0].start, 4, "the offset is kept");
14753 assert!(links_are_consistent(&p.lanes).is_ok());
14754 }
14755
14756 #[test]
14757 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
14758 let mut p = three();
14759 let before = shape(&p);
14760 assert!(!p.split(0), "timeline 0 has nothing before it");
14761 assert!(!p.split(3), "existing boundary");
14762 assert!(!p.split(5), "existing boundary");
14763 assert!(!p.split(9), "one past the last frame");
14764 assert!(!p.split(1_000));
14765 assert_eq!(shape(&p), before);
14766 // one undo lands before the *second* split, so the refusals pushed nothing
14767 assert!(p.undo());
14768 assert_eq!(p.clips().len(), 2, "refused splits push no history");
14769
14770 // ...and a frame that is a gap in both lanes has nothing to split.
14771 let mut p = three();
14772 assert!(p.lift(Lane::V1, 1));
14773 assert!(p.lift(Lane::A1, 1));
14774 assert!(!p.split(4), "a gap is not a clip");
14775 }
14776
14777 #[test]
14778 fn regroup_refuses_what_a_split_could_not_have_made() {
14779 let mut p = three();
14780 // [3,5) and [5,9) are source-contiguous: that pair rejoins.
14781 assert!(p.regroup(5));
14782 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 9, 0)]);
14783 // A boundary with a gap on one side, and one where the sources do not
14784 // meet, are both refused.
14785 let mut p = three();
14786 assert!(p.lift(Lane::V1, 1));
14787 assert!(p.lift(Lane::A1, 1));
14788 assert!(!p.regroup(3), "nothing starts at 3 any more");
14789 let mut p = three();
14790 for l in p.lanes() {
14791 assert!(p.place(l, 3, clip(0, 100, 102, 0)));
14792 }
14793 assert!(!p.regroup(3), "source 100 does not follow source 3");
14794 assert!(!p.regroup(0), "nothing ends at 0");
14795 assert!(!p.regroup(1_000));
14796 }
14797
14798 #[test]
14799 fn map_and_spans_sweep_every_boundary() {
14800 let p = three();
14801 assert_eq!(p.timeline_frames(), 9);
14802 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4)]);
14803 // contiguous source here, so the clip index is what actually moves
14804 let expect = [
14805 (0, (0, 0)),
14806 (1, (0, 1)),
14807 (2, (0, 2)),
14808 (3, (1, 3)), // half-open: the boundary frame belongs to the NEXT clip
14809 (4, (1, 4)),
14810 (5, (2, 5)),
14811 (6, (2, 6)),
14812 (7, (2, 7)),
14813 (8, (2, 8)),
14814 ];
14815 for (t, want) in expect {
14816 assert_eq!(p.map_timeline(t), Some(want), "timeline frame {t}");
14817 }
14818 assert_eq!(p.map_timeline(9), None);
14819 // A span is the rest of the clip from where it was asked about.
14820 assert_eq!(
14821 p.span_at(Lane::V1, 6),
14822 Some(Span {
14823 reverse: false,
14824 ramp: None,
14825 start: 6,
14826 len: 3,
14827 from: Some((0, 6)),
14828 speed: Speed::NORMAL,
14829 pitch: 0,
14830 })
14831 );
14832 assert_eq!(p.span_at(Lane::V1, 9), None);
14833 }
14834
14835 /// The fit policy is one byte *in* the clip rather than an index into a
14836 /// table like the eq and the grade: there is nothing for a table to share.
14837 /// It costs the clip nothing at all -- the fields before it (a `usize`
14838 /// source and two `Option<u16>`s) already left the struct padded to 40
14839 /// bytes, and the byte landed in that padding. `fade_in`/`fade_out` are two
14840 /// `u32`s after it (48 bytes), and `transition_out` is a third word --
14841 /// 52 bytes of fields, but the struct's own alignment is 8 (from the
14842 /// `usize` source and the 8-byte `Option<u32>` link), so an odd number of
14843 /// words after it pads out to the next multiple of 8: 56 bytes total.
14844 /// The transform index is a third `Option<u16>`, same reason as the eq and
14845 /// colour ones before it -- it lands in bytes already spent on padding, so
14846 /// the struct still costs 56.
14847 /// The visualizer look is the first field whose own width outgrows the
14848 /// padding it lands in: it is a `u64` (a strand colour needs bytes above
14849 /// the clip's own four), so the words after it come to 60 and the
14850 /// alignment rounds them to 64 -- one word more than a clip used to cost.
14851 /// Since the gain envelope (`gain_db` plus the `gain_keys` `Vec`, 24 bytes
14852 /// of pointer, length and capacity) the clip is 96 bytes and no longer
14853 /// `Copy`; the `Vec` is what the copy-cost comment above no longer covers.
14854 /// The placement keys (`transform_keys`, a second `Vec`) take it to 120.
14855 /// The fit policy itself is still one byte: it sits in the padding among
14856 /// the other fields, and the total is the 224 (144 before the opacity and colour keys' `Vec`s,
14857 /// 192 before the effects stack's)
14858 /// rounded up to the alignment of 8, so removing it would not shrink the clip.
14859 /// This asserts the one-byte enum and the exact size, so any further growth
14860 /// shows up here first.
14861 #[test]
14862 fn a_fit_policy_costs_the_clip_no_word() {
14863 assert_eq!(std::mem::size_of::<FitPolicy>(), 1);
14864 assert_eq!(
14865 std::mem::size_of::<Clip>(),
14866 224,
14867 "Clip changed size: {} bytes",
14868 std::mem::size_of::<Clip>()
14869 );
14870 }
14871
14872 /// The clip a copy would hand back: source `[100, 102)`, unrelated to
14873 /// anything in `three()` so it is recognisable wherever it lands.
14874 const PASTED: Clip = Clip {
14875 speed_keys: Vec::new(),
14876 reversed: false,
14877 stabilise: None, deinterlace: Deinterlace::Frame, mark: ClipMark { label: 0, off: false },
14878 angle: Angle { video: 0, audio: None },
14879 fade_in: 0,
14880 fade_out: 0,
14881 transition_out: 0,
14882 transition_kind: crate::transitions::TransitionKind::Dissolve,
14883 visualizer: 0,
14884 viz_paint: 0,
14885 gain_db: 0.0,
14886 gain_keys: Vec::new(),
14887 pan: 0,
14888 transform_keys: Vec::new(),
14889 opacity_keys: Vec::new(),
14890 color_keys: Vec::new(),
14891 effects: Vec::new(),
14892 start: 0,
14893 in_frame: 100,
14894 out_frame: 102,
14895 source: 0,
14896 link: None,
14897 eq: None,
14898 color: None,
14899 transform: None,
14900 fit: FitPolicy::Fit,
14901 speed: Speed::NORMAL,
14902 pitch: 0,
14903 };
14904
14905 #[test]
14906 fn paste_mid_clip_splits_around_it() {
14907 let mut p = three();
14908 assert!(p.paste(6, PASTED)); // inside [5,9), one frame in
14909 assert_eq!(p.timeline_frames(), 11);
14910 assert_eq!(
14911 shape(&p)[0],
14912 vec![
14913 clip(0, 0, 3, 0),
14914 clip(3, 3, 5, 0),
14915 clip(5, 5, 6, 0),
14916 clip(6, 100, 102, 0),
14917 clip(8, 6, 9, 0),
14918 ]
14919 );
14920 assert_eq!(shape(&p)[1], shape(&p)[0], "a paste lands on both lanes");
14921 // The pasted frames are exactly where they were asked for, and the
14922 // split-off remainder resumes after them.
14923 assert_eq!(p.map_timeline(6), Some((3, 100)));
14924 assert_eq!(p.map_timeline(7), Some((3, 101)));
14925 assert_eq!(p.map_timeline(8), Some((4, 6)));
14926 }
14927
14928 #[test]
14929 fn paste_at_boundary_zero_and_end() {
14930 let mut p = three();
14931 assert!(p.paste(3, PASTED), "existing boundary: no split");
14932 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 2), (7, 4)]);
14933 assert_eq!(p.map_timeline(3), Some((1, 100)));
14934
14935 let mut p = three();
14936 assert!(p.paste(0, PASTED));
14937 assert_eq!(p.map_timeline(0), Some((0, 100)));
14938 assert_eq!(p.map_timeline(2), Some((1, 0)));
14939
14940 // At the end: appended, there being nothing in front to leave black.
14941 let mut p = three();
14942 assert!(p.paste(9, PASTED));
14943 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 2), (5, 4), (9, 2)]);
14944 // Past it: down on the frame it was asked for, black in front of it --
14945 // a row let go on the open bed lands under the ghost that promised it.
14946 // The clipboard's clamp lives in `PlaybackSession::paste_at`.
14947 assert!(p.paste(1_000, PASTED));
14948 assert_eq!(p.timeline_frames(), 1_002);
14949 assert_eq!(
14950 p.lane(Lane::V1).last().expect("the pasted clip").start,
14951 1_000
14952 );
14953 assert_eq!(
14954 p.lane(Lane::A1).last().expect("its other half").start,
14955 1_000
14956 );
14957
14958 // An empty clip is the one thing refused, and it pushes no history.
14959 let mut p = three();
14960 assert!(!p.paste(4, clip(0, 7, 7, 0)));
14961 assert_eq!(p.clips().len(), 3);
14962 }
14963
14964 /// The data-loss paste: a clip of a source with no picture used to land on
14965 /// `V1` as well as `A1`, where it decodes to nothing -- and the save that
14966 /// carried it was refused on the way back in ("a box with a larger size").
14967 #[test]
14968 fn a_paste_of_a_source_with_no_picture_stays_off_the_video_lane() {
14969 let mut p = three();
14970 let wav = p.import("/nonexistent/song.wav", 0);
14971 let copied = Clip {
14972 fade_in: 0,
14973 fade_out: 0,
14974 transition_out: 0,
14975 transition_kind: Default::default(),
14976 visualizer: 0,
14977 viz_paint: 0,
14978 gain_db: 0.0,
14979 source: wav,
14980 ..PASTED
14981 };
14982 assert!(p.paste(3, copied));
14983 // The room is opened on every lane, or the two would slide apart...
14984 assert_eq!(p.timeline_frames(), 11);
14985 assert_eq!(
14986 shape(&p)[0],
14987 vec![clip(0, 0, 3, 0), clip(5, 3, 5, 0), clip(7, 5, 9, 0)],
14988 "the video lane got room and nothing else"
14989 );
14990 // ...but the clip itself only reaches the lane that can play it.
14991 assert_eq!(
14992 shape(&p)[1],
14993 vec![
14994 clip(0, 0, 3, 0),
14995 clip(3, 100, 102, wav),
14996 clip(5, 3, 5, 0),
14997 clip(7, 5, 9, 0)
14998 ]
14999 );
15000 // A source with a picture is unchanged: still the grouped pair.
15001 let mut p = three();
15002 assert!(p.paste(3, PASTED));
15003 assert_eq!(shape(&p)[0], shape(&p)[1]);
15004 }
15005
15006 /// A hand-written file may hold a clip that ends at the very last frame
15007 /// (`edith::check` permits `start + len == u32::MAX`), and the ripple used
15008 /// to wrap its start round to the front of the lane: an overlap in debug, a
15009 /// project no reload would accept in release.
15010 #[test]
15011 fn a_paste_that_would_run_past_the_last_frame_is_refused() {
15012 let far = clip(u32::MAX - 90, 0, 90, 0);
15013 let parts = |c: Clip| {
15014 Project::from_parts(
15015 vec![Source::new(FILE, 0)],
15016 two(vec![c.clone()], vec![c]),
15017 Vec::new(),
15018 Vec::new(),
15019 Vec::new(),
15020 )
15021 .expect("valid parts")
15022 };
15023 let mut p = parts(far.clone());
15024 assert!(!p.paste(0, PASTED), "no room for the two frames it adds");
15025 assert_eq!(shape(&p)[0], vec![far], "a refusal changes nothing");
15026 assert!(!p.undo(), "...and pushes no history either");
15027 assert!(
15028 !p.paste(u32::MAX, PASTED),
15029 "appending has nowhere to go either: the timeline ends at the last frame"
15030 );
15031 // With room for exactly those frames the same paste is taken.
15032 let mut p = parts(clip(u32::MAX - 92, 0, 90, 0));
15033 assert!(p.paste(0, PASTED));
15034 assert_eq!(p.lane(Lane::V1)[1].end(), u32::MAX);
15035 }
15036
15037 #[test]
15038 fn paste_undoes_in_one_step() {
15039 let mut p = three();
15040 let before = shape(&p);
15041 assert!(p.paste(6, PASTED));
15042 assert!(p.undo());
15043 assert_eq!(shape(&p), before, "a paste is one undo step");
15044 }
15045
15046 #[test]
15047 fn a_copy_outlives_the_clip_it_came_from() {
15048 let mut p = three();
15049 let copied = p.clips()[1].clone(); // [3,5)
15050 assert!(p.delete(1));
15051 // Just a frame range: the source is still on disk either way.
15052 assert!(p.paste(0, copied));
15053 assert_eq!(p.map_timeline(0), Some((0, 3)));
15054 assert_eq!(p.timeline_frames(), 9);
15055 }
15056
15057 #[test]
15058 fn delete_closes_the_gap_on_both_lanes() {
15059 let mut p = three();
15060 assert!(p.delete(1));
15061 assert_eq!(p.timeline_frames(), 7);
15062 assert_eq!(p.clip_spans(), vec![(0, 3), (3, 4)]);
15063 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 4)]);
15064 // timeline 3 used to be source 3; the gap closed so it is source 5 now
15065 assert_eq!(p.map_timeline(3), Some((1, 5)));
15066 assert_eq!(p.map_timeline(6), Some((1, 8)));
15067 assert_eq!(p.map_timeline(7), None);
15068 }
15069
15070 #[test]
15071 fn delete_first_last_and_only() {
15072 let mut p = three();
15073 assert!(p.delete(0));
15074 assert_eq!(p.map_timeline(0), Some((0, 3)));
15075 assert_eq!(p.timeline_frames(), 6);
15076
15077 let mut p = three();
15078 assert!(p.delete(2));
15079 assert_eq!(p.timeline_frames(), 5);
15080 assert_eq!(p.map_timeline(4), Some((1, 4)));
15081
15082 assert!(!p.delete(2), "index past the end");
15083 assert!(p.delete(1));
15084 assert!(p.delete(0), "and the last remaining clip goes too");
15085 assert_eq!(p.clips().len(), 0);
15086 assert_eq!(p.timeline_frames(), 0, "the timeline is emptiable");
15087 assert!(!p.delete(0), "there is nothing left to delete");
15088 assert!(p.undo(), "one gesture, one undo");
15089 assert_eq!(p.clips().len(), 1);
15090 }
15091
15092 /// The offset model's point: one lane loses a clip, the other does not move.
15093 #[test]
15094 fn a_lift_leaves_a_gap_and_moves_nothing() {
15095 let mut p = three();
15096 let video_before = shape(&p)[0].clone();
15097 assert!(p.lift(Lane::A1, 1));
15098 assert_eq!(shape(&p)[0], video_before, "the picture never moved");
15099 assert_eq!(p.timeline_frames(), 9, "nor did the timeline get shorter");
15100 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (5, 4)]);
15101 // The hole is a gap: mapped as nothing, spanned as a gap of its length.
15102 assert_eq!(p.map(Lane::A1, 4), None);
15103 assert_eq!(
15104 p.span_at(Lane::A1, 3),
15105 Some(Span {
15106 reverse: false,
15107 ramp: None,
15108 start: 3,
15109 len: 2,
15110 from: None,
15111 speed: Speed::NORMAL,
15112 pitch: 0,
15113 })
15114 );
15115 assert_eq!(p.map(Lane::V1, 4), Some((1, 4)), "video plays on");
15116 assert!(p.undo());
15117 assert_eq!(p.lane_spans(Lane::A1), vec![(0, 3), (3, 2), (5, 4)]);
15118 }
15119
15120 #[test]
15121 fn a_trailing_gap_is_a_gap_to_the_end_of_the_timeline() {
15122 let mut p = three();
15123 assert!(p.lift(Lane::A1, 2));
15124 assert_eq!(p.timeline_frames(), 9, "video still runs to 9");
15125 assert_eq!(
15126 p.span_at(Lane::A1, 5),
15127 Some(Span {
15128 reverse: false,
15129 ramp: None,
15130 start: 5,
15131 len: 4,
15132 from: None,
15133 speed: Speed::NORMAL,
15134 pitch: 0,
15135 }),
15136 "the audio lane holds silence to the end of the picture"
15137 );
15138 assert_eq!(p.span_at(Lane::A1, 9), None);
15139 // Every lane covers the timeline exactly, gaps included.
15140 for l in p.lanes() {
15141 let spans = p.spans_from(l, 0);
15142 assert_eq!(spans.iter().map(|s| s.len).sum::<u32>(), 9, "{}", l.label());
15143 assert_eq!(spans[0].start, 0);
15144 }
15145 }
15146
15147 /// The timeline is emptiable: the last placement comes off like any other,
15148 /// the project holds "nothing on any lane" as a state, and one undo per
15149 /// gesture brings it back.
15150 #[test]
15151 fn the_last_clip_of_the_last_lane_lifts_and_undoes() {
15152 let mut p = Project::single(FILE, 9);
15153 assert!(p.lift(Lane::A1, 0), "a silent timeline is fine");
15154 assert!(p.lift(Lane::V1, 0), "and an empty one is a timeline too");
15155 assert_eq!(p.timeline_frames(), 0);
15156 assert_eq!(p.composite_span_at(0), None, "nothing to show");
15157 assert!(p.audio_segments_from(0, FPS).len() == 1, "one all-gap list");
15158 assert!(!p.lift(Lane::A1, 0), "index past the end");
15159 assert!(p.undo(), "and the last lift comes back");
15160 assert_eq!(p.lane_spans(Lane::V1), vec![(0, 9)]);
15161 // A saved-and-loaded empty timeline is a project like any other, and it
15162 // still names the file its frame rate came from.
15163 assert!(p.lift(Lane::V1, 0));
15164 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
15165 assert_eq!(sources.len(), 1, "source 0 survives an emptied timeline");
15166 let back = Project::from_parts(sources, lanes, eq, color, Vec::new())
15167 .expect("an empty project loads");
15168 assert_eq!(back.timeline_frames(), 0);
15169 assert_eq!(back.lanes().len(), 2, "and it kept its lanes");
15170 }
15171
15172 /// What a keyboard selection walks: one answer per lane, gaps included --
15173 /// the composite's own answer is one lane's and cannot say what the audio
15174 /// lane holds under the same playhead.
15175 #[test]
15176 fn lane_clip_at_answers_for_each_lane_separately() {
15177 let mut p = Project::single(FILE, 9);
15178 assert!(p.split(3), "both lanes split");
15179 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15180 assert_eq!(p.lane_clip_at(Lane::V1, 3), Some(1));
15181 assert_eq!(p.lane_clip_at(Lane::A1, 3), Some(1));
15182 assert_eq!(p.lane_clip_at(Lane::V1, 9), None, "past the end");
15183 // A gap on one lane leaves the other's clip selectable there.
15184 assert!(p.lift(Lane::A1, 0));
15185 assert_eq!(p.lane_clip_at(Lane::A1, 0), None, "the gap holds nothing");
15186 assert_eq!(
15187 p.lane_clip_at(Lane::A1, 3),
15188 Some(0),
15189 "indices moved with it"
15190 );
15191 assert_eq!(p.lane_clip_at(Lane::V1, 0), Some(0));
15192 // A lane that is not there is not a panic.
15193 assert_eq!(p.lane_clip_at(Lane::new(LaneKind::Video, 1), 0), None);
15194 }
15195
15196 #[test]
15197 fn place_overwrites_only_its_own_lane() {
15198 let mut p = three();
15199 let audio_before = shape(&p)[1].clone();
15200 // Straddles [3,5) and eats into [5,9): the first is trimmed, the second
15201 // is trimmed, nothing shifts.
15202 assert!(p.place(Lane::V1, 4, clip(0, 100, 102, 0)));
15203 assert_eq!(
15204 shape(&p)[0],
15205 vec![
15206 clip(0, 0, 3, 0),
15207 clip(3, 3, 4, 0),
15208 clip(4, 100, 102, 0),
15209 clip(6, 6, 9, 0),
15210 ]
15211 );
15212 assert_eq!(shape(&p)[1], audio_before, "the audio lane is untouched");
15213 assert_eq!(p.timeline_frames(), 9, "an overwrite is not an insert");
15214
15215 // Placed inside one clip, it splits it in two.
15216 let mut p = Project::single(FILE, 9);
15217 assert!(p.place(Lane::V1, 4, clip(0, 100, 101, 0)));
15218 assert_eq!(
15219 shape(&p)[0],
15220 vec![clip(0, 0, 4, 0), clip(4, 100, 101, 0), clip(5, 5, 9, 0)]
15221 );
15222 // ...and placed past the end it makes a gap, which is the whole point.
15223 assert!(p.place(Lane::V1, 20, clip(0, 100, 102, 0)));
15224 assert_eq!(p.timeline_frames(), 22);
15225 assert_eq!(
15226 p.span_at(Lane::V1, 9),
15227 Some(Span {
15228 reverse: false,
15229 ramp: None,
15230 start: 9,
15231 len: 11,
15232 from: None,
15233 speed: Speed::NORMAL,
15234 pitch: 0,
15235 })
15236 );
15237 assert!(!p.place(Lane::V1, 0, clip(0, 7, 7, 0)), "empty clip");
15238 }
15239
15240 /// A file with sound let go over a further video track: both halves go down,
15241 /// on the same frames, and the audio row is added when the `+ V` button left
15242 /// the project without one. One undo takes the lane and both clips back.
15243 #[test]
15244 fn a_take_placed_on_a_layer_lands_with_its_sound() {
15245 let mut p = three();
15246 let v2 = p.add_lane(LaneKind::Video);
15247 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2], "no A2 yet");
15248
15249 assert!(p.place_take(v2, 4, clip(0, 100, 102, 0)));
15250 let a2 = Lane::new(LaneKind::Audio, 1);
15251 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2, a2], "A2 was added");
15252 assert_eq!(p.lane(v2), p.lane(a2), "same frames, same source");
15253 assert_eq!(p.lane(v2)[0].start, 4);
15254 assert_eq!(p.lane(v2)[0].end(), 6);
15255 assert_eq!(
15256 p.lane(v2)[0].link,
15257 p.lane(a2)[0].link,
15258 "one take, not two placements"
15259 );
15260 assert!(p.lane(v2)[0].link.is_some());
15261 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 untouched");
15262 assert_eq!(shape(&p)[1], shape(&three())[1], "and A1 with it");
15263
15264 // The pair overwrites its own two lanes and nothing else, exactly as a
15265 // one-lane place does.
15266 assert!(p.place_take(v2, 5, clip(0, 200, 203, 0)));
15267 assert_eq!(p.lane(v2), p.lane(a2));
15268 assert_eq!(p.lane(v2).len(), 2, "the tail of the first is still there");
15269 assert_eq!(shape(&p)[0], shape(&three())[0], "V1 still untouched");
15270
15271 assert!(p.undo(), "one step for the second pair");
15272 assert_eq!(p.lane(v2).len(), 1);
15273 assert!(p.undo(), "one step for the first pair *and* its lane");
15274 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15275 assert!(p.lane(v2).is_empty());
15276
15277 // Refusals cost nothing: sound placed alone is `place`'s door.
15278 assert!(
15279 !p.place_take(Lane::A1, 0, clip(0, 100, 102, 0)),
15280 "audio lane"
15281 );
15282 assert!(!p.place_take(v2, 0, clip(0, 7, 7, 0)), "empty clip");
15283 assert!(
15284 !p.place_take(Lane::new(LaneKind::Video, 9), 0, clip(0, 1, 2, 0)),
15285 "a lane that is not there"
15286 );
15287 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
15288 }
15289
15290 /// The drag between tracks: let go at the frames it already covers the clip
15291 /// keeps them, one undo takes it back, and every way it can be refused
15292 /// leaves the project untouched.
15293 #[test]
15294 fn move_clip_keeps_the_frames_and_refuses_the_rest() {
15295 let v2 = Lane::new(LaneKind::Video, 1);
15296 let mut p = three();
15297 assert_eq!(p.add_lane(LaneKind::Video), v2);
15298 let before = shape(&p);
15299
15300 assert!(p.move_clip(Lane::V1, 1, v2, 3), "V1's middle clip moves up");
15301 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 5, 9, 0)]);
15302 assert_eq!(shape(&p)[2], vec![clip(3, 3, 5, 0)], "same frames on V2");
15303 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15304 assert_eq!(p.timeline_frames(), 9, "a move is not an insert");
15305 // One snapshot: a single undo, and the lane list survives it.
15306 assert!(p.undo());
15307 assert_eq!(shape(&p), before);
15308
15309 // A lane that is not there, the lane and frame it is already at, an
15310 // index that is not there, and a move across kinds: all refused,
15311 // nothing changed.
15312 let history = p.history.len();
15313 for (from, idx, to, start) in [
15314 (Lane::V1, 1, Lane::new(LaneKind::Video, 7), 3),
15315 (Lane::V1, 1, Lane::V1, 3),
15316 (Lane::V1, 9, v2, 3),
15317 (Lane::V1, 1, Lane::A1, 3),
15318 (Lane::A1, 1, v2, 3),
15319 ] {
15320 assert!(
15321 !p.move_clip(from, idx, to, start),
15322 "{from:?} {idx} -> {to:?} at {start}"
15323 );
15324 }
15325 assert_eq!(shape(&p), before);
15326 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15327
15328 // Landing on another clip is refused rather than overwriting it: the
15329 // pointer named the lane, never the take already sitting there.
15330 assert!(p.place(v2, 3, clip(0, 100, 101, 0)), "V2 holds [3,4)");
15331 assert!(!p.move_clip(Lane::V1, 1, v2, 3), "let go inside it");
15332 assert!(p.move_clip(Lane::V1, 0, v2, 0), "[0,3) merely abuts it");
15333 assert_eq!(shape(&p)[0], vec![clip(3, 3, 5, 0), clip(5, 5, 9, 0)]);
15334 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
15335 }
15336
15337 /// A lane's name is a label: the address is unchanged, it is one undo step, an
15338 /// empty name clears it, a lane's removal takes it along, and a clip's deinterlace
15339 /// choice survives a split, a copy and an undo.
15340 #[test]
15341 fn lane_names_and_deinterlace_follow_the_usual_edit_rules() {
15342 let sources = vec![Source::new(FILE, 0)];
15343 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
15344 let mut p = Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15345 assert_eq!(p.set_lane_name(Lane::V1, " Interview "), Ok(true));
15346 assert_eq!(p.lane_name(Lane::V1), Some("Interview"));
15347 assert_eq!(p.lane_title(Lane::V1), "Interview");
15348 assert_eq!(p.lane_title(Lane::A1), "A1");
15349 assert_eq!(p.set_lane_name(Lane::V1, "Interview"), Ok(false), "no change, no history");
15350 assert!(p.set_lane_name(Lane::V1, &"x".repeat(MAX_LANE_NAME_CHARS + 1)).is_err());
15351 assert!(p.set_lane_name(Lane::V1, "a\nb").is_err());
15352 assert_eq!(p.set_lane_name(Lane::S1, "x"), Ok(false), "no such lane");
15353 assert!(p.undo());
15354 assert_eq!(p.lane_name(Lane::V1), None);
15355 assert!(p.redo());
15356 assert_eq!(p.lane_names(), vec!["Interview".to_string(), String::new()]);
15357 assert_eq!(p.set_lane_name(Lane::V1, " "), Ok(true), "blank clears");
15358 assert_eq!(p.lane_name(Lane::V1), None);
15359
15360 assert!(p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15361 assert!(!p.set_deinterlace(Lane::V1, 0, Deinterlace::Field));
15362 assert!(!p.set_deinterlace(Lane::A1, 0, Deinterlace::Off), "video clips only");
15363 assert!(p.split(5));
15364 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Field);
15365 assert_eq!(p.deinterlace_of(Lane::V1, 1), Deinterlace::Field, "both halves keep it");
15366 assert!(p.undo() && p.undo());
15367 assert_eq!(p.deinterlace_of(Lane::V1, 0), Deinterlace::Frame);
15368 assert!(p.redo());
15369 let copy = p.lane(Lane::V1)[0].clone();
15370 assert_eq!(copy.deinterlace, Deinterlace::Field, "a copy carries it");
15371 }
15372
15373 /// The drag *along* a track, which is the one every other editor has: the
15374 /// clip lands on the frame the pointer let it go at, and stops dead against
15375 /// the neighbour rather than overwriting it.
15376 #[test]
15377 fn a_clip_slides_along_its_own_lane_and_butts_against_its_neighbour() {
15378 let sources = vec![Source::new(FILE, 0)];
15379 let lanes = vec![
15380 (LaneKind::Video, vec![clip(0, 0, 3, 0), clip(10, 3, 6, 0)]),
15381 (LaneKind::Audio, vec![clip(0, 0, 3, 0)]),
15382 ];
15383 let mut p =
15384 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15385 let before = shape(&p);
15386
15387 // Into the gap, exactly where it was let go -- nothing else moves.
15388 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 5));
15389 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(5, 3, 6, 0)]);
15390 assert_eq!(shape(&p)[1], before[1], "the audio lane is untouched");
15391 // Dragged past the clip in front of it: clamped to its wall, laid end
15392 // to end with it, never over it.
15393 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 0));
15394 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 6, 0)]);
15395 // One undo per drag, and both of them together are the state it started
15396 // in -- the frames each clip plays never changed.
15397 assert!(p.undo() && p.undo());
15398 assert_eq!(shape(&p), before);
15399
15400 // A drop that changes nothing is a click, not an edit.
15401 let history = p.history.len();
15402 assert!(!p.move_clip(Lane::V1, 1, Lane::V1, 10));
15403 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
15404 }
15405
15406 /// A move lands on any empty frames of its lane, jumping over the clips
15407 /// between -- where a drag only slides up to the first one it meets.
15408 #[test]
15409 fn a_move_jumps_over_clips_to_empty_frames() {
15410 let sources = vec![Source::new(FILE, 0)];
15411 let lanes = vec![
15412 (LaneKind::Video, vec![clip(0, 0, 4, 0), clip(6, 4, 8, 0), clip(12, 8, 12, 0)]),
15413 (LaneKind::Audio, vec![clip(0, 0, 4, 0)]),
15414 ];
15415 let mut p =
15416 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15417
15418 // [0,4) to [16,20): past the clip at 6 and the clip at 12, both empty
15419 // frames of the lane -- a move, not an insert, so nothing else shifts.
15420 assert!(p.move_clip(Lane::V1, 0, Lane::V1, 16));
15421 assert_eq!(
15422 shape(&p)[0],
15423 vec![clip(6, 4, 8, 0), clip(12, 8, 12, 0), clip(16, 0, 4, 0)]
15424 );
15425 // A gap of two frames (10..12) is too narrow for a four-frame clip: refused.
15426 let before = shape(&p);
15427 assert!(!p.move_clip(Lane::V1, 2, Lane::V1, 10), "no gap that wide");
15428 assert_eq!(shape(&p), before);
15429 }
15430
15431 /// A linked take jumps as one: its partner on the audio lane must be free
15432 /// at the same frames, and where it is not the drop is clamped to the
15433 /// partner's wall rather than overlapping it.
15434 #[test]
15435 fn a_linked_take_jumps_only_where_its_partner_is_free() {
15436 let link = |mut c: Clip| {
15437 c.link = Some(7);
15438 c
15439 };
15440 let sources = vec![Source::new(FILE, 0)];
15441 let lanes = vec![
15442 (LaneKind::Video, vec![link(clip(0, 0, 4, 0)), clip(12, 4, 8, 0)]),
15443 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0))]),
15444 ];
15445 let mut p =
15446 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15447 let v2 = p.add_lane(LaneKind::Video);
15448
15449 // Both halves free at [20,24): the take lands there, partner included.
15450 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15451 assert_eq!(p.lane(v2).iter().map(|c| c.start).collect::<Vec<_>>(), [20]);
15452 assert_eq!(p.lane(Lane::A1)[0].start, 20, "partner moves the same distance");
15453 assert_eq!(p.lane(Lane::A1)[0].link, Some(7));
15454
15455 // A partner blocked at [22,26) on the audio lane: the drop stops at the
15456 // frame where the partner meets nothing, never over the blocker.
15457 let sources = vec![Source::new(FILE, 0)];
15458 let lanes = vec![
15459 (LaneKind::Video, vec![link(clip(0, 0, 4, 0))]),
15460 (LaneKind::Audio, vec![link(clip(0, 0, 4, 0)), clip(22, 0, 4, 0)]),
15461 ];
15462 let mut p =
15463 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
15464 let v2 = p.add_lane(LaneKind::Video);
15465 assert!(p.move_clip(Lane::V1, 0, v2, 20));
15466 assert_eq!(p.lane(v2)[0].start, 18, "clamped to the partner's wall");
15467 assert_eq!(p.lane(Lane::A1)[0].start, 18);
15468 assert_eq!(p.lane(Lane::A1)[1].start, 22, "the blocker is not moved");
15469 }
15470
15471 /// A drag carries the whole take: the sound half travels exactly as far as
15472 /// the picture does, and the tighter of their two walls stops both.
15473 #[test]
15474 fn a_dragged_take_carries_its_sound_and_stops_at_the_tighter_wall() {
15475 let mut p = three();
15476 assert!(
15477 p.lift(Lane::V1, 2) && p.lift(Lane::A1, 2),
15478 "room to the right"
15479 );
15480 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
15481 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
15482 // Something in the sound's way, and nothing at all in the picture's.
15483 assert!(p.place(Lane::A1, 10, clip(0, 0, 2, 0)), "A1 holds [10,12)");
15484 let before = shape(&p);
15485
15486 // Let go over empty frames on both lanes: the take lands there whole,
15487 // jumping the blocker that lies between.
15488 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 30), "dragged far right");
15489 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 30));
15490 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 30), "sound came with it");
15491 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15492 assert!(p.undo());
15493 assert_eq!(shape(&p), before, "one undo for the whole take");
15494
15495 // Let go on the sound's blocker: the take stops against it, picture
15496 // and sound alike, short of the frame the pointer named.
15497 assert!(p.move_clip(Lane::V1, 1, Lane::V1, 9), "dropped on the blocker");
15498 assert!(p.lane(Lane::V1).iter().any(|c| c.start == 8), "stopped where the sound did");
15499 assert!(p.lane(Lane::A1).iter().any(|c| c.start == 8), "and the sound came with it");
15500 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15501 assert!(p.undo());
15502 assert_eq!(shape(&p), before, "one undo for the whole take");
15503 }
15504
15505 /// The drag that does both at once -- another lane *and* another frame --
15506 /// which is what a pointer let go over a lane always names.
15507 #[test]
15508 fn a_clip_dragged_to_another_lane_lands_on_the_pointers_frame() {
15509 let v2 = Lane::new(LaneKind::Video, 1);
15510 let mut p = three();
15511 assert_eq!(p.add_lane(LaneKind::Video), v2);
15512
15513 assert!(p.move_clip(Lane::V1, 2, v2, 20), "[5,9) -> V2 at 20");
15514 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 5, 0)]);
15515 assert_eq!(shape(&p)[2], vec![clip(20, 5, 9, 0)], "at the pointer");
15516 assert_eq!(
15517 p.lane(Lane::A1)[2].start,
15518 20,
15519 "its sound travelled the same distance"
15520 );
15521 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15522 assert_eq!(p.timeline_frames(), 24, "a move is not an insert");
15523 }
15524
15525 /// How long `FILE` is, which is what a trim's tail is allowed to reach:
15526 /// [`three`] cuts up all nine of its frames.
15527 const SRC: &[u32] = &[9];
15528
15529 /// The drag on a clip's tail: it plays less (or more) of its source, nothing
15530 /// else on the lane moves, and every wall stops the edge rather than
15531 /// refusing the gesture.
15532 #[test]
15533 fn trimming_the_tail_stops_at_every_wall() {
15534 let mut p = three();
15535
15536 // Pulled in: a gap opens behind it and the clip after it stays put.
15537 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
15538 assert_eq!(
15539 shape(&p)[0],
15540 vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
15541 );
15542 assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
15543 assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
15544
15545 // ...and back out, no further than the clip behind it.
15546 assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
15547 assert_eq!(
15548 shape(&p)[0][1],
15549 clip(3, 3, 5, 0),
15550 "stopped at the neighbour"
15551 );
15552 assert!(
15553 !p.trim(Lane::V1, 1, Edge::End, 8, SRC),
15554 "already at the wall"
15555 );
15556
15557 // One frame of clip always survives, however far back the pointer went.
15558 assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
15559 assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
15560
15561 // The last clip has no neighbour, so what stops it is the file: nine
15562 // frames is nine frames.
15563 assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
15564 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
15565 assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
15566 assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
15567 // A source nobody told us the length of may not grow at all -- an
15568 // out-point past the end of a file is a save that will not open again.
15569 assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
15570 assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
15571 }
15572
15573 /// The head pulled in takes the in-point with it -- what stays plays what it
15574 /// always played -- and stops at the source's own first frame.
15575 #[test]
15576 fn trimming_the_head_moves_the_in_point() {
15577 let mut p = three();
15578 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15579 assert_eq!(
15580 shape(&p)[0][0],
15581 clip(2, 2, 3, 0),
15582 "two frames off the front"
15583 );
15584 assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
15585 assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
15586 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
15587 assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
15588 // One frame survives here too.
15589 assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
15590 assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
15591
15592 // A clip that does not begin at its source's first frame: its head goes
15593 // back to source frame 0 and not one frame further.
15594 let mut p = Project::single(FILE, 9);
15595 assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
15596 assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
15597 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
15598 assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
15599 }
15600
15601 /// A clip whose in-point is *past* its own start -- what a ripple delete
15602 /// leaves, the piece in front of it gone and this one slid back to frame 0
15603 /// carrying the in-point the cut gave it. Its head has more source behind it
15604 /// than the timeline has room for, and the timeline's own first frame is the
15605 /// wall: asking is not an overflow, and the answer is 0.
15606 #[test]
15607 fn a_ripple_closed_clip_can_still_be_head_trimmed() {
15608 let mut p = Project::single(FILE, 9);
15609 assert!(p.split(5));
15610 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
15611 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
15612
15613 assert_eq!(
15614 p.trim_room(Lane::V1, 0, Edge::Start, SRC),
15615 Some((0, 3)),
15616 "back to frame 0 at most, and one frame of clip always survives"
15617 );
15618 assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
15619 assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
15620 assert_eq!(
15621 shape(&p)[0],
15622 vec![clip(2, 7, 9, 0)],
15623 "the in-point followed"
15624 );
15625 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
15626 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
15627 }
15628
15629 /// A still is trimmed from its head exactly as it is from its tail: it has
15630 /// no earlier frame to walk an in-point back to, so the wall is the length
15631 /// the caller's table allows it, measured back from the tail. Measured from
15632 /// the in-point -- which a placed picture has at 0 -- its left edge could
15633 /// never be dragged outwards at all.
15634 #[test]
15635 fn a_stills_head_stretches_out_like_its_tail() {
15636 const STILL: &str = "/nonexistent/card.png";
15637 /// What a still is held to, as `PlaybackSession` fills the table in.
15638 const CAP: &[u32] = &[60];
15639
15640 let mut p = Project::single(STILL, 20);
15641 assert!(p.lift(Lane::A1, 0), "a picture is silent");
15642 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
15643 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
15644
15645 // A source with no entry in the table may not grow, here as at the tail.
15646 assert_eq!(
15647 p.trim_room(Lane::V1, 0, Edge::Start, &[]),
15648 Some((100, 119)),
15649 "a length nobody told us buys no head room"
15650 );
15651 assert_eq!(
15652 p.trim_room(Lane::V1, 0, Edge::Start, CAP),
15653 Some((60, 119)),
15654 "back to a whole cap's worth, one frame of clip surviving"
15655 );
15656 assert!(p.trim(Lane::V1, 0, Edge::Start, 80, CAP));
15657 assert_eq!(
15658 shape(&p)[0][0],
15659 clip(80, 0, 40, 0),
15660 "twenty frames longer, and still read from the source's first frame"
15661 );
15662 // Past the cap is clamped, exactly as the tail is -- not refused.
15663 assert!(p.trim(Lane::V1, 0, Edge::Start, 0, CAP));
15664 assert_eq!(
15665 shape(&p)[0][0],
15666 clip(60, 0, 60, 0),
15667 "a cap's worth, no more"
15668 );
15669 // ...and the clip in front is the nearer wall of the two: no head trim
15670 // may open an overlap.
15671 assert!(p.trim(Lane::V1, 0, Edge::Start, 90, CAP));
15672 assert!(p.place(Lane::V1, 70, clip(0, 0, 15, 0)));
15673 assert_eq!(
15674 p.trim_room(Lane::V1, 1, Edge::Start, CAP),
15675 Some((85, 119)),
15676 "up to the neighbour's last frame and not over it"
15677 );
15678 assert!(p.trim(Lane::V1, 1, Edge::Start, 0, CAP));
15679 assert_eq!(shape(&p)[0][1], clip(85, 0, 35, 0), "butted against it");
15680 assert!(sorted_disjoint(p.lane(Lane::V1)), "no overlap");
15681 }
15682
15683 /// An end edge that runs out of source names the source's tail as its
15684 /// wall, and the same edge stopped by the clip after it does not -- and the
15685 /// walls are the ones `trim_room` gives, not a second computation.
15686 #[test]
15687 fn trim_walls_name_the_source_tail_or_the_neighbour() {
15688 let mut p = Project::single(FILE, 9);
15689 assert_eq!(
15690 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15691 Some(TrimWalls {
15692 lo: 1,
15693 hi: 9,
15694 lo_media: false,
15695 hi_media: true,
15696 }),
15697 "the whole source, and it runs out at its tail"
15698 );
15699 assert_eq!(
15700 p.trim_walls(Lane::V1, 0, Edge::End, SRC)
15701 .map(|w| (w.lo, w.hi)),
15702 p.trim_room(Lane::V1, 0, Edge::End, SRC),
15703 );
15704
15705 assert!(p.split(5));
15706 assert_eq!(
15707 p.trim_walls(Lane::V1, 0, Edge::End, SRC),
15708 Some(TrimWalls {
15709 lo: 1,
15710 hi: 5,
15711 lo_media: false,
15712 hi_media: false,
15713 }),
15714 "the source has more, but the next piece is nearer"
15715 );
15716 assert_eq!(
15717 p.trim_walls(Lane::V1, 1, Edge::End, SRC),
15718 Some(TrimWalls {
15719 lo: 6,
15720 hi: 9,
15721 lo_media: false,
15722 hi_media: true,
15723 }),
15724 "the last piece runs to the source's tail"
15725 );
15726 assert_eq!(
15727 p.trim_walls(Lane::V1, 2, Edge::End, SRC),
15728 None,
15729 "no such clip"
15730 );
15731 }
15732
15733 /// A start edge that drags back to the source's first frame names that
15734 /// head as its wall; one stopped by the piece in front of it does not.
15735 #[test]
15736 fn trim_walls_name_the_source_head_or_the_neighbour() {
15737 let mut p = Project::single(FILE, 9);
15738 assert!(p.split(5));
15739 assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
15740 assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
15741 assert_eq!(
15742 p.trim_walls(Lane::V1, 0, Edge::Start, SRC),
15743 Some(TrimWalls {
15744 lo: 0,
15745 hi: 3,
15746 lo_media: true,
15747 hi_media: false,
15748 }),
15749 "frame 0 is the head's first frame, and the clip's own minimum is the other wall"
15750 );
15751
15752 let mut p = Project::single(FILE, 9);
15753 assert!(p.split(5));
15754 assert_eq!(
15755 p.trim_walls(Lane::V1, 1, Edge::Start, SRC),
15756 Some(TrimWalls {
15757 lo: 5,
15758 hi: 8,
15759 lo_media: false,
15760 hi_media: false,
15761 }),
15762 "the head has room back to 0, but the piece in front stops it at 5"
15763 );
15764 }
15765
15766 /// A still has no media limit: its head and tail reach as far as the cap
15767 /// says, and that reach is never reported as the source's end.
15768 #[test]
15769 fn a_still_never_reports_media() {
15770 const STILL: &str = "/nonexistent/card.png";
15771 const CAP: &[u32] = &[60];
15772
15773 let mut p = Project::single(STILL, 20);
15774 assert!(p.lift(Lane::A1, 0), "a picture is silent");
15775 assert!(p.lift(Lane::V1, 0), "and this one is not at frame 0");
15776 assert!(p.place(Lane::V1, 100, clip(0, 0, 20, 0)));
15777
15778 assert_eq!(
15779 p.trim_walls(Lane::V1, 0, Edge::Start, CAP),
15780 Some(TrimWalls {
15781 lo: 60,
15782 hi: 119,
15783 lo_media: false,
15784 hi_media: false,
15785 }),
15786 );
15787 assert_eq!(
15788 p.trim_walls(Lane::V1, 0, Edge::End, CAP),
15789 Some(TrimWalls {
15790 lo: 101,
15791 hi: 160,
15792 lo_media: false,
15793 hi_media: false,
15794 }),
15795 );
15796 }
15797
15798 /// Linked halves trim as one: a link is one span on however many lanes, so
15799 /// the sound follows the picture's edge -- and the tightest wall of the two
15800 /// is what stops both.
15801 #[test]
15802 fn linked_halves_trim_together() {
15803 let mut p = three();
15804 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
15805 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
15806
15807 assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
15808 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
15809 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
15810 assert!(
15811 p.trim(Lane::A1, 2, Edge::End, 8, SRC),
15812 "either half drags it"
15813 );
15814 assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
15815 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15816
15817 // Something in the way on the *audio* lane stops the picture's tail as
15818 // well: the group can only go as far as its tightest member.
15819 assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
15820 assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
15821 assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
15822 assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
15823 links_are_consistent(&p.lanes).expect("still one span");
15824 }
15825
15826 /// An overwrite that cuts through a take on both of its lanes leaves the take whole: the head
15827 /// and the tail of the cut each keep one id shared across the lanes, so a trim of either lane
15828 /// still drags the other. A cut that would leave one lane's half without its partner detaches.
15829 #[test]
15830 fn an_overwrite_through_a_take_keeps_the_take_whole() {
15831 let mut p = three();
15832 assert!(p.edit_from_source(SourceEdit::Overwrite, 6, &[(Lane::V1, clip(0, 0, 2, 0)), (Lane::A1, clip(0, 0, 2, 0))]).is_ok());
15833 let head = p.lane(Lane::V1)[2].link;
15834 assert!(head.is_some(), "the head of the cut is still one take");
15835 assert_eq!(p.lane(Lane::A1)[2].link, head, "and so is the sound's head");
15836 assert_eq!(p.lane(Lane::V1)[4].link, p.lane(Lane::A1)[4].link, "the tail is one take too");
15837 assert!(p.lane(Lane::V1)[4].link.is_some());
15838 assert_ne!(p.lane(Lane::V1)[4].link, head, "the tail is a take of its own");
15839 links_are_consistent(&p.lanes).expect("one id per lane, one span");
15840
15841 // The head's sound follows the picture's trim, as it does everywhere else.
15842 assert!(p.trim(Lane::V1, 0, Edge::End, 2, SRC));
15843 assert_eq!(p.lane(Lane::A1)[0].end(), 2, "the sound followed the picture");
15844 links_are_consistent(&p.lanes).expect("still one span");
15845 }
15846
15847 /// A take that loses its last partner is detached: the survivor keeps an id
15848 /// that no other placement shares (a lone id, which the front-ends draw as
15849 /// detached), whichever edit took the partner away -- a lift, a split on some
15850 /// lanes -- and one undo puts the take back exactly.
15851 #[test]
15852 fn a_take_down_to_one_member_is_detached() {
15853 let mut p = three();
15854 let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
15855 assert_eq!(p.lane(Lane::A1)[2].link, Some(link));
15856
15857 assert!(p.lift(Lane::V1, 2));
15858 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "the survivor keeps its id");
15859 assert!(p.undo());
15860 assert_eq!(p.lane(Lane::V1)[2].link, Some(link), "undo restores the picture's link");
15861 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "and the sound's");
15862
15863 // A split on the picture lane only: every half of the take is detached
15864 // (a fresh id of its own), in one snapshot.
15865 let history = p.history.len();
15866 assert!(p.split_on(7, &[Lane::V1]));
15867 assert_eq!(p.history.len(), history + 1, "one snapshot for the whole split");
15868 let ids: Vec<Option<u32>> = vec![
15869 p.lane(Lane::V1)[2].link,
15870 p.lane(Lane::V1)[3].link,
15871 p.lane(Lane::A1)[2].link,
15872 ];
15873 assert!(ids.iter().all(Option::is_some), "each half is detached: {ids:?}");
15874 assert!(ids[0] != ids[1] && ids[0] != ids[2] && ids[1] != ids[2], "{ids:?}");
15875 links_are_consistent(&p.lanes).expect("no two members share an id");
15876 assert!(p.undo());
15877 assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "undo restores the take");
15878 assert_eq!(p.lane(Lane::V1)[2].link, Some(link));
15879 }
15880
15881 /// `swap` trades two placements of one lane: the first takes the second's
15882 /// start, the one between them ripples by the length difference, and the
15883 /// second lands where the first was (moved by that difference). The span
15884 /// keeps its length; a grouped placement refuses; one undo puts it back.
15885 #[test]
15886 fn swap_trades_two_clips_and_ripples_the_difference() {
15887 let mut p = Project::single(FILE, 1);
15888 let v = p.add_lane(LaneKind::Video);
15889 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
15890 assert!(p.place(v, 3, clip(3, 3, 5, 0)));
15891 assert!(p.place(v, 5, clip(5, 5, 9, 0)));
15892 // [0,3) len 3 and [5,9) len 4 trade places; the middle [3,5) moves by +1.
15893 assert!(p.swap(v, 0, 2));
15894 let got: Vec<(u32, u32, u32)> = p
15895 .lane(v)
15896 .iter()
15897 .map(|c| (c.start, c.frames(), c.in_frame))
15898 .collect();
15899 assert_eq!(got, vec![(0, 4, 5), (4, 2, 3), (6, 3, 0)]);
15900 assert!(p.undo());
15901 assert_eq!(p.lane(v)[0].start, 0);
15902 assert_eq!(p.lane(v)[0].frames(), 3, "one undo puts the order back");
15903
15904 // A grouped placement is not swapped apart.
15905 let mut t = three();
15906 assert!(!t.swap(Lane::V1, 0, 2), "the take is moved as a take");
15907 assert!(!t.swap(Lane::V1, 1, 1), "same clip");
15908 }
15909
15910 /// A clip whose link no other clip shares (what `ungroup` leaves) swaps like any other.
15911 #[test]
15912 fn swap_moves_a_detached_clip_but_not_a_take() {
15913 let mut p = three();
15914 assert!(p.ungroup(Lane::V1, 0) && p.ungroup(Lane::V1, 2), "both ends are detached first");
15915 assert!(p.lane(Lane::V1)[0].link.is_some(), "the lone link stays");
15916 assert!(p.swap(Lane::V1, 0, 2), "a lone link is not a take");
15917 assert_eq!(p.lane(Lane::V1)[0].in_frame, 5, "the later clip took the head");
15918 assert!(p.undo());
15919 // Clip 1 on V1 is still in its take with A1, so a swap that includes it is refused.
15920 let mut t = three();
15921 assert!(t.ungroup(Lane::V1, 0));
15922 assert!(!t.swap(Lane::V1, 0, 1), "a take still moves as a take");
15923 assert!(t.swap_in_place(Lane::V1, 0, 1).is_err(), "a take still moves as a take");
15924 }
15925
15926 /// The non-rippling swap: the two clips trade heads, the shorter leaves a gap
15927 /// where it was, and nothing between them moves. A clip moving into the slot
15928 /// the other vacates is allowed -- the check is on the finished positions.
15929 #[test]
15930 fn swap_in_place_exchanges_heads_and_moves_nothing_else() {
15931 let mut p = Project::single(FILE, 1);
15932 let v = p.add_lane(LaneKind::Video);
15933 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
15934 assert!(p.place(v, 4, clip(4, 4, 5, 0)));
15935 assert!(p.place(v, 9, clip(9, 9, 12, 0)));
15936 p.swap_in_place(v, 0, 2).expect("the longer clip fits the 0..4 space");
15937 let got: Vec<(u32, u32, u32)> = p
15938 .lane(v)
15939 .iter()
15940 .map(|c| (c.start, c.frames(), c.in_frame))
15941 .collect();
15942 assert_eq!(got, vec![(0, 3, 9), (4, 1, 4), (9, 2, 0)]);
15943 assert!(p.undo());
15944 assert_eq!(p.lane(v)[0].in_frame, 0, "one undo restores the lane");
15945 assert_eq!(p.lane(v)[2].start, 9);
15946 }
15947
15948 /// A longer clip that cannot fit its new head is refused by name, and the lane
15949 /// is untouched -- nothing is half-swapped.
15950 #[test]
15951 fn swap_in_place_refuses_a_clip_that_would_overlap_by_name() {
15952 let mut p = Project::single(FILE, 1);
15953 let v = p.add_lane(LaneKind::Video);
15954 assert!(p.place(v, 0, clip(0, 0, 2, 0)));
15955 assert!(p.place(v, 2, clip(2, 2, 3, 0)));
15956 assert!(p.place(v, 4, clip(4, 4, 8, 0)));
15957 let before: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
15958 let err = p.swap_in_place(v, 0, 2).expect_err("the 4-frame clip does not fit 0..2");
15959 assert!(err.to_string().contains("clip 1"), "names the clip in the way: {err}");
15960 let after: Vec<(u32, u32)> = p.lane(v).iter().map(|c| (c.start, c.frames())).collect();
15961 assert_eq!(before, after, "a refusal changes nothing");
15962 assert!(p.swap_in_place(v, 1, 1).is_err(), "the same clip twice");
15963 }
15964
15965 /// `ungroup` takes a whole take apart: each member gets an id of its own,
15966 /// so the take is no longer a group, and one undo puts it back.
15967 #[test]
15968 fn ungroup_gives_each_member_its_own_id() {
15969 let mut p = three();
15970 assert!(p.ungroup(Lane::A1, 2));
15971 assert_ne!(p.lane(Lane::A1)[2].link, p.lane(Lane::V1)[2].link);
15972 assert!(p.undo());
15973 assert!(p.lane(Lane::V1)[2].link.is_some(), "undo puts the take back");
15974 }
15975
15976 /// The bug this guards: grouping a take's picture with a clip from another
15977 /// take merges all four into one id, and ungrouping the picture must hand
15978 /// each take back whole -- not detach both halves of the first take too.
15979 #[test]
15980 fn ungroup_of_a_member_of_a_merged_group_keeps_its_take() {
15981 let v2 = Lane::new(LaneKind::Video, 1);
15982 let a2 = Lane::new(LaneKind::Audio, 1);
15983 let mut p = Project::single(FILE, 9);
15984 p.add_lane(LaneKind::Video);
15985 let other = p.lane(Lane::V1)[0].clone();
15986 assert!(p.place_take(v2, 20, other));
15987 let all = |p: &Project| -> Vec<Vec<Clip>> { p.lanes().iter().map(|&l| p.lane(l).to_vec()).collect() };
15988 let before = all(&p);
15989
15990 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
15991 assert_eq!(p.lane(Lane::A1)[0].link, p.lane(v2)[0].link, "one group of four");
15992 assert!(p.ungroup(Lane::V1, 0));
15993 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the first take is still linked");
15994 assert_eq!(p.lane(v2)[0].link, p.lane(a2)[0].link, "the second take is still linked");
15995 assert_ne!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "and the two takes are apart");
15996
15997 // One undo is the merged group, and a second one the state before it.
15998 assert!(p.undo());
15999 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(v2)[0].link, "the merge is back");
16000 assert!(p.undo());
16001 assert_eq!(all(&p), before, "undo is exact");
16002 }
16003
16004 /// A caption grouped onto a whole take: ungrouping the caption takes the
16005 /// caption off and leaves the take linked, the same as a loose clip would.
16006 #[test]
16007 fn ungroup_of_a_caption_on_a_take_keeps_the_take() {
16008 let mut p = Project::single(FILE, 9).with_subtitles(vec![subtitle_track()]);
16009 let subs = p.add_lane(LaneKind::Subtitle);
16010 let caption = SubClip { start: 0, frames: 9, track: 0, in_us: 0, out_us: 300_000, link: None };
16011 p.place_sub(subs, 0, caption).expect("the caption goes down");
16012 p.group_all(&[(Lane::V1, 0), (subs, 0)]).expect("a clip and a caption are a group");
16013 assert!(p.ungroup(subs, 0));
16014 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16015 let cap = p.sub_lane(subs)[0].link;
16016 assert!(cap.is_some() && cap != p.lane(Lane::V1)[0].link, "the caption is a half of its own");
16017 }
16018
16019 /// A take grouped with one loose clip: ungrouping the take's picture
16020 /// detaches the loose clip and leaves the take linked, and ungrouping the
16021 /// loose clip does the same from the other side.
16022 #[test]
16023 fn ungroup_of_a_take_with_a_loose_clip_detaches_only_the_loose_clip() {
16024 let v2 = Lane::new(LaneKind::Video, 1);
16025 let loose = |p: &Project| Clip { link: None, ..p.lane(Lane::V1)[0].clone() };
16026 let mut p = Project::single(FILE, 9);
16027 p.add_lane(LaneKind::Video);
16028 let mut clip = loose(&p);
16029 clip.start = 20;
16030 assert!(p.place(v2, 20, clip.clone()));
16031
16032 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16033 assert!(p.ungroup(v2, 0));
16034 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "the take is still linked");
16035 assert!(p.lane(v2)[0].link.is_some() && p.lane(v2)[0].link != p.lane(Lane::V1)[0].link);
16036 assert!(p.undo());
16037
16038 p.group_all(&[(Lane::V1, 0), (v2, 0)]).unwrap();
16039 assert!(p.ungroup(Lane::V1, 0));
16040 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link, "from the picture too");
16041 assert_ne!(p.lane(v2)[0].link, p.lane(Lane::V1)[0].link);
16042 assert!(links_are_consistent(&p.lanes).is_ok());
16043 }
16044
16045 /// A whole drag is one undo step -- the front-end commits once, at the
16046 /// release -- and an edge asked to stay where it is costs none at all.
16047 #[test]
16048 fn a_trim_is_one_undo_step() {
16049 let mut p = three();
16050 let before = shape(&p);
16051 let history = p.history.len();
16052
16053 assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
16054 assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
16055 assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
16056 assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
16057 assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
16058 assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
16059
16060 assert!(p.undo());
16061 assert_eq!(shape(&p), before, "both halves back, in one step");
16062 }
16063
16064 /// A moved half stays in its group: a link names a span, not a lane, so the
16065 /// picture on `V2` is still the same take as the sound under it on `A1`.
16066 #[test]
16067 fn move_clip_keeps_the_group() {
16068 let v2 = Lane::new(LaneKind::Video, 1);
16069 let mut p = three();
16070 p.add_lane(LaneKind::Video);
16071 let link = p.lane(Lane::V1)[1].link.expect("a split hands out ids");
16072 assert_eq!(p.lane(Lane::A1)[1].link, Some(link), "both halves grouped");
16073 assert!(p.move_clip(Lane::V1, 1, v2, 3));
16074 assert_eq!(p.lane(v2)[0].link, Some(link), "the id travelled with it");
16075 links_are_consistent(&p.lanes).expect("one id per lane, one span");
16076 assert_eq!(
16077 p.lane(v2)[0].start,
16078 p.lane(Lane::A1)[1].start,
16079 "and still covers the same span as its sound"
16080 );
16081 }
16082
16083 /// The gap-close menu's hit test: what `gap_at` says about a frame at the
16084 /// head of a lane, between two clips, inside a clip, past the last one,
16085 /// and on a lane holding nothing at all.
16086 #[test]
16087 fn gap_at_finds_the_hole_a_frame_sits_in() {
16088 let mut p = Project::single(FILE, 1);
16089 let v = p.add_lane(LaneKind::Video);
16090 // Empty lane: nothing before and nothing after -- not a gap, since
16091 // there is nothing to ripple toward.
16092 assert_eq!(p.gap_at(v, 0), None, "an empty lane has nothing to close");
16093
16094 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "single clip at [5,8)");
16095 // Before the only clip: the gap runs from the timeline's own head.
16096 assert_eq!(p.gap_at(v, 0), Some((0, 5)));
16097 assert_eq!(p.gap_at(v, 4), Some((0, 5)));
16098 // Inside the clip: not a gap.
16099 assert_eq!(p.gap_at(v, 5), None);
16100 assert_eq!(p.gap_at(v, 7), None);
16101 // Past the only clip: the open end of the lane, not a gap -- there is
16102 // nothing after it to slide back.
16103 assert_eq!(p.gap_at(v, 8), None);
16104 assert_eq!(p.gap_at(v, 100), None);
16105
16106 assert!(
16107 p.place(v, 12, clip(12, 0, 2, 0)),
16108 "a second clip at [12,14)"
16109 );
16110 // Between the two: the gap [8,12).
16111 assert_eq!(p.gap_at(v, 8), Some((8, 4)));
16112 assert_eq!(p.gap_at(v, 11), Some((8, 4)));
16113 assert_eq!(p.gap_at(v, 14), None, "still the open end");
16114
16115 assert!(
16116 p.place(v, 8, clip(8, 0, 4, 0)),
16117 "fills [8,12) exactly, meeting both neighbours"
16118 );
16119 assert_eq!(
16120 p.gap_at(v, 8),
16121 None,
16122 "adjacent clips leave no frame to name a gap"
16123 );
16124 assert_eq!(p.gap_at(v, 11), None);
16125 }
16126
16127 /// Closing a gap is [`Project::cut_regions`] scoped to the one lane the
16128 /// menu named: the clip after the gap slides back on that lane, a clip on
16129 /// another lane at the very same frame range does not move, and the whole
16130 /// close is one press of undo.
16131 #[test]
16132 fn closing_a_gap_ripples_only_its_own_lane_and_undoes_in_one_step() {
16133 let mut p = Project::single(FILE, 1);
16134 let v = p.add_lane(LaneKind::Video);
16135 let a = p.add_lane(LaneKind::Audio);
16136 assert!(p.place(v, 5, clip(5, 0, 3, 0)), "V clip at [5,8)");
16137 assert!(
16138 p.place(a, 0, clip(0, 0, 3, 0)),
16139 "A clip at [0,3) -- outside the video lane's gap and this scope"
16140 );
16141 let before = shape(&p);
16142 let (start, len) = p.gap_at(v, 0).expect("a gap before the only clip");
16143 assert_eq!((start, len), (0, 5));
16144 assert!(p.cut_regions(&[(start, len)], &[v]).is_ok());
16145 assert_eq!(p.lane(v)[0].start, 0, "the clip slid back to close the gap");
16146 assert_eq!(
16147 p.lane(a)[0].start,
16148 0,
16149 "the untouched lane's clip did not move"
16150 );
16151 assert!(p.undo(), "one press undoes the whole close");
16152 assert_eq!(shape(&p), before, "back to exactly where it was");
16153 }
16154
16155 /// A clip carrying an explicit link id -- what a
16156 /// [`from_parts`](Project::from_parts) fixture below needs to build a take
16157 /// by hand, the same shape `a_link_id_is_never_two_clips_of_one_lane`
16158 /// already builds inline.
16159 fn linked(start: u32, in_frame: u32, out_frame: u32, link: u32) -> Clip {
16160 Clip {
16161 speed_keys: Vec::new(),
16162 reversed: false,
16163 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
16164 angle: Default::default(),
16165 fade_in: 0,
16166 fade_out: 0,
16167 transition_out: 0,
16168 transition_kind: Default::default(),
16169 visualizer: 0,
16170 viz_paint: 0,
16171 gain_db: 0.0,
16172 gain_keys: Vec::new(),
16173 pan: 0,
16174 pitch: 0,
16175 transform_keys: Vec::new(),
16176 opacity_keys: Vec::new(),
16177 color_keys: Vec::new(),
16178 effects: Vec::new(),
16179 start,
16180 in_frame,
16181 out_frame,
16182 source: 0,
16183 link: Some(link),
16184 eq: None,
16185 color: None,
16186 transform: None,
16187 fit: FitPolicy::default(),
16188 speed: Speed::NORMAL,
16189 }
16190 }
16191
16192 /// The ordinary case the defect made a permanent no-op: a gap on `V1`
16193 /// bordered by a linked take whose `A1` half is empty across the very
16194 /// same stretch widens the scope to both lanes, so the ripple carries the
16195 /// take rather than tearing it -- and one undo puts both halves back.
16196 #[test]
16197 fn closing_a_gap_carries_a_linked_take_when_the_gap_matches_on_both_lanes() {
16198 let sources = vec![Source::new(FILE, 0)];
16199 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16200 let audio = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16201 let mut p = Project::from_parts(
16202 sources,
16203 two(video, audio),
16204 Vec::new(),
16205 Vec::new(),
16206 Vec::new(),
16207 )
16208 .expect("valid parts");
16209 let before = shape(&p);
16210 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16211 assert_eq!(
16212 p.gap_at(Lane::A1, 3),
16213 Some((3, 2)),
16214 "the same stretch is empty on A1 too"
16215 );
16216
16217 let scope = p
16218 .gap_take_scope(Lane::V1, 3, 2)
16219 .expect("a matching gap on both halves widens the scope");
16220 assert_eq!(scope.len(), 2, "the take's other lane joins");
16221 assert!(scope.contains(&Lane::V1) && scope.contains(&Lane::A1));
16222
16223 assert!(p.cut_regions(&[(3, 2)], &scope).is_ok());
16224 assert_eq!(p.lane(Lane::V1)[1].start, 3, "V1's far half slid back");
16225 assert_eq!(
16226 p.lane(Lane::A1)[1].start,
16227 3,
16228 "A1's far half rode along, in sync"
16229 );
16230 assert!(p.undo(), "one press undoes the whole close");
16231 assert_eq!(shape(&p), before, "back to exactly where it was");
16232 }
16233
16234 /// The real design question: a take whose gap is not the *same size* on
16235 /// both lanes cannot ripple by one number without pulling a lane's clip
16236 /// out from under the other's sync -- refused by name, with the frame
16237 /// naming which lane is out of step, rather than silently taking real
16238 /// media off the shorter side.
16239 #[test]
16240 fn closing_a_gap_refuses_a_take_whose_gap_lengths_differ() {
16241 let sources = vec![Source::new(FILE, 0)];
16242 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16243 // A1's second half starts at 4, not 5: its gap is [3,4), one frame
16244 // shorter than V1's [3,5) -- a legal offset-preserving group, and
16245 // still one take.
16246 let audio = vec![linked(0, 0, 3, 1), linked(4, 5, 9, 3)];
16247 let p = Project::from_parts(
16248 sources,
16249 two(video, audio),
16250 Vec::new(),
16251 Vec::new(),
16252 Vec::new(),
16253 )
16254 .expect("valid parts");
16255 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16256 assert_eq!(p.gap_at(Lane::A1, 3), Some((3, 1)), "a shorter gap on A1");
16257
16258 let err = p
16259 .gap_take_scope(Lane::V1, 3, 2)
16260 .expect_err("a mismatched gap cannot ripple by one number")
16261 .to_string();
16262 assert!(err.contains("A1"), "{err}");
16263 assert!(err.contains("out of sync"), "{err}");
16264 }
16265
16266 /// A gap on `V1` whose `A1` half is not a gap at all -- real audio plays
16267 /// there -- cannot close without cutting that audio out from under
16268 /// nothing asked to touch it: refused, not widened silently past.
16269 #[test]
16270 fn closing_a_gap_refuses_a_take_whose_other_half_is_solid() {
16271 let sources = vec![Source::new(FILE, 0)];
16272 let video = vec![linked(0, 0, 3, 1), linked(5, 5, 9, 3)];
16273 // A1 plays through the whole span as one continuous clip, sharing
16274 // V1's first-half link: nothing empty at frame 3 there at all.
16275 let audio = vec![linked(0, 0, 9, 1)];
16276 let p = Project::from_parts(
16277 sources,
16278 two(video, audio),
16279 Vec::new(),
16280 Vec::new(),
16281 Vec::new(),
16282 )
16283 .expect("valid parts");
16284 assert_eq!(p.gap_at(Lane::V1, 3), Some((3, 2)));
16285 assert_eq!(
16286 p.gap_at(Lane::A1, 3),
16287 None,
16288 "A1 plays through, no gap there"
16289 );
16290
16291 let err = p
16292 .gap_take_scope(Lane::V1, 3, 2)
16293 .expect_err("a solid partner cannot ripple with the gap")
16294 .to_string();
16295 assert!(err.contains("A1"), "{err}");
16296 assert!(err.contains("out of sync"), "{err}");
16297 }
16298
16299 /// The sweep is the single-gap close repeated on one lane, but measured once
16300 /// and applied from the right. The differing gap lengths here expose a
16301 /// front-to-back bug: the last clip would be cut against a stale frame after
16302 /// the first gap shifted it.
16303 #[test]
16304 fn close_all_gaps_on_one_lane_closes_every_bounded_gap_and_undoes_once() {
16305 let mut p = Project::single(FILE, 1);
16306 let v = p.add_lane(LaneKind::Video);
16307 assert!(p.place(v, 2, clip(2, 0, 2, 0)), "head gap [0,2)");
16308 assert!(p.place(v, 7, clip(7, 2, 4, 0)), "middle gap [4,7)");
16309 assert!(p.place(v, 14, clip(14, 4, 5, 0)), "middle gap [9,14)");
16310 let before = shape(&p);
16311
16312 assert_eq!(p.gap_count(v), 3);
16313 let report = p.close_all_gaps_on_lane(v).expect("the lane exists");
16314 assert_eq!(report.closed, 3);
16315 assert!(report.skipped.is_empty());
16316 assert_eq!(
16317 p.lane(v),
16318 &[clip(0, 0, 2, 0), clip(2, 2, 4, 0), clip(4, 4, 5, 0)],
16319 "all gaps closed without eating source frames"
16320 );
16321 assert!(p.undo(), "one undo for the whole sweep");
16322 assert_eq!(shape(&p), before);
16323 }
16324
16325 /// Empty, already-contiguous and tail-only lanes are not controls that do
16326 /// work. A single clip with a head gap does close, because there is a real
16327 /// placement to ripple back.
16328 #[test]
16329 fn close_all_gaps_on_one_lane_handles_empty_single_contiguous_and_tail_only_lanes() {
16330 let mut p = Project::single(FILE, 9);
16331 let v = p.add_lane(LaneKind::Video);
16332 let history = p.history.len();
16333 let report = p.close_all_gaps_on_lane(v).expect("empty lane exists");
16334 assert_eq!(
16335 report,
16336 GapSweep::default(),
16337 "an empty lane has no bounded gap"
16338 );
16339 assert_eq!(p.history.len(), history, "no undo step for a no-op");
16340
16341 let mut p = Project::single(FILE, 9);
16342 let v = p.add_lane(LaneKind::Video);
16343 assert!(p.place(v, 5, clip(5, 0, 3, 0)));
16344 let before = shape(&p);
16345 let report = p
16346 .close_all_gaps_on_lane(v)
16347 .expect("single clip lane exists");
16348 assert_eq!(report.closed, 1, "the head gap closes");
16349 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16350 assert!(p.undo());
16351 assert_eq!(shape(&p), before);
16352
16353 let mut p = Project::single(FILE, 9);
16354 let history = p.history.len();
16355 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16356 assert_eq!(report, GapSweep::default(), "contiguous clips have no gaps");
16357 assert_eq!(p.history.len(), history);
16358
16359 let mut p = Project::single(FILE, 9);
16360 let v = p.add_lane(LaneKind::Video);
16361 assert!(p.place(v, 0, clip(0, 0, 3, 0)));
16362 let history = p.history.len();
16363 let report = p.close_all_gaps_on_lane(v).expect("tail-only lane exists");
16364 assert_eq!(
16365 report,
16366 GapSweep::default(),
16367 "the open-ended tail is not closed"
16368 );
16369 assert_eq!(p.lane(v), &[clip(0, 0, 3, 0)]);
16370 assert_eq!(p.history.len(), history);
16371 }
16372
16373 /// A sweep closes the gaps that satisfy the linked-take rule and leaves the
16374 /// rest in place with a count and reason. Here [2,4) matches on both lanes,
16375 /// while V1's [6,9) has only [6,8) empty on A1.
16376 #[test]
16377 fn close_all_gaps_on_one_lane_partially_closes_linked_takes_and_reports_skips() {
16378 let sources = vec![Source::new(FILE, 0)];
16379 let video = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(9, 9, 11, 0)];
16380 let audio = vec![linked(0, 0, 2, 1), linked(4, 4, 6, 2), clip(8, 8, 11, 0)];
16381 let mut p = Project::from_parts(
16382 sources,
16383 two(video, audio),
16384 Vec::new(),
16385 Vec::new(),
16386 Vec::new(),
16387 )
16388 .expect("valid parts");
16389 let before = shape(&p);
16390
16391 let report = p.close_all_gaps_on_lane(Lane::V1).expect("V1 exists");
16392 assert_eq!(report.closed, 1);
16393 assert_eq!(report.skipped.len(), 1);
16394 assert_eq!(report.skipped[0].start, 6);
16395 assert!(report.skipped[0].reason.contains("A1"), "{report:?}");
16396 assert!(
16397 report.skipped[0].reason.contains("out of sync"),
16398 "{report:?}"
16399 );
16400
16401 assert_eq!(p.lane(Lane::V1)[1].start, 2, "the matched take moved");
16402 assert_eq!(
16403 p.lane(Lane::A1)[1].start,
16404 2,
16405 "and its other half stayed in sync"
16406 );
16407 assert_eq!(
16408 p.lane(Lane::V1)[2].start,
16409 7,
16410 "the skipped later gap remains"
16411 );
16412 assert_eq!(
16413 p.lane(Lane::A1)[2].start,
16414 6,
16415 "A1's shorter gap remains shorter"
16416 );
16417 links_are_consistent(&p.lanes).expect("every linked take that moved stayed whole");
16418 assert!(p.undo(), "one undo restores every closed gap");
16419 assert_eq!(shape(&p), before);
16420 }
16421
16422 /// Subtitle lanes use the same bounded-hole hit test as clip lanes, against
16423 /// their own caption storage: head gaps and gaps between cues count, an
16424 /// empty lane and the tail after the last cue do not.
16425 #[test]
16426 fn gap_at_finds_the_hole_a_caption_frame_sits_in() {
16427 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16428 let s = p.add_lane(LaneKind::Subtitle);
16429 assert_eq!(
16430 p.gap_at(s, 0),
16431 None,
16432 "an empty subtitle lane has nothing to close"
16433 );
16434
16435 p.place_sub(s, 5, caption(0, 3))
16436 .expect("single cue at [5,8)");
16437 assert_eq!(p.gap_at(s, 0), Some((0, 5)), "head gap before first cue");
16438 assert_eq!(p.gap_at(s, 4), Some((0, 5)));
16439 assert_eq!(p.gap_at(s, 5), None, "inside the cue");
16440 assert_eq!(p.gap_at(s, 8), None, "tail after a single cue is not a gap");
16441
16442 p.place_sub(s, 12, caption(0, 2))
16443 .expect("second cue at [12,14)");
16444 assert_eq!(p.gap_at(s, 8), Some((8, 4)), "gap between cues");
16445 assert_eq!(p.gap_at(s, 11), Some((8, 4)));
16446 assert_eq!(
16447 p.gap_at(s, 14),
16448 None,
16449 "tail after the last cue is still open-ended"
16450 );
16451 }
16452
16453 /// Closing a caption gap ripples the subtitle lane only. It is not a media
16454 /// take close, so the video and audio lanes keep their frame positions.
16455 #[test]
16456 fn closing_a_caption_gap_ripples_no_video_or_audio_clips() {
16457 let mut p = Project::single(FILE, 20).with_subtitles(vec![subtitle_track()]);
16458 let s = p.add_lane(LaneKind::Subtitle);
16459 p.place_sub(s, 5, caption(0, 3))
16460 .expect("single cue at [5,8)");
16461 let before_clips = shape(&p);
16462 let before_subs = p.sub_lane(s).to_vec();
16463
16464 let (start, len) = p.gap_at(s, 0).expect("gap before the caption");
16465 assert_eq!((start, len), (0, 5));
16466 p.cut_regions(&[(start, len)], &[s])
16467 .expect("caption lane gap closes");
16468
16469 assert_eq!(shape(&p), before_clips, "media lanes did not move");
16470 assert_eq!(p.sub_lane(s), &[caption(0, 3)], "caption slid left");
16471 assert!(p.undo(), "one undo restores the caption close");
16472 assert_eq!(shape(&p), before_clips);
16473 assert_eq!(p.sub_lane(s), before_subs);
16474 }
16475
16476 /// The subtitle sweep is the clip sweep's bounded-gap arithmetic on
16477 /// [`SubClip`] storage: right-to-left, one undo, no tail close, and no
16478 /// history entry for empty or already-contiguous lanes.
16479 #[test]
16480 fn close_all_gaps_on_subtitle_lane_closes_bounded_gaps_and_undoes_once() {
16481 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16482 let s = p.add_lane(LaneKind::Subtitle);
16483 let history = p.history.len();
16484 let report = p
16485 .close_all_gaps_on_lane(s)
16486 .expect("empty subtitle lane exists");
16487 assert_eq!(
16488 report,
16489 GapSweep::default(),
16490 "empty subtitle lane has no bounded gap"
16491 );
16492 assert_eq!(p.history.len(), history, "empty sweep is not an undo step");
16493
16494 p.place_sub(s, 2, caption(0, 2)).expect("head gap [0,2)");
16495 p.place_sub(s, 7, caption(0, 2)).expect("middle gap [4,7)");
16496 p.place_sub(s, 14, caption(0, 1))
16497 .expect("middle gap [9,14), tail after 15");
16498 let before = p.sub_lane(s).to_vec();
16499
16500 assert_eq!(p.gap_count(s), 3);
16501 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16502 assert_eq!(report.closed, 3);
16503 assert!(report.skipped.is_empty());
16504 assert_eq!(
16505 p.sub_lane(s),
16506 &[caption(0, 2), caption(2, 2), caption(4, 1)],
16507 "all bounded caption gaps closed without touching windows"
16508 );
16509 assert!(p.undo(), "one undo restores every caption gap");
16510 assert_eq!(p.sub_lane(s), before);
16511
16512 let mut p = Project::single(FILE, 30).with_subtitles(vec![subtitle_track()]);
16513 let s = p.add_lane(LaneKind::Subtitle);
16514 p.place_sub(s, 0, caption(0, 3))
16515 .expect("contiguous at the head");
16516 let history = p.history.len();
16517 let report = p.close_all_gaps_on_lane(s).expect("subtitle lane exists");
16518 assert_eq!(report, GapSweep::default(), "the open tail is not closed");
16519 assert_eq!(p.sub_lane(s), &[caption(0, 3)]);
16520 assert_eq!(p.history.len(), history);
16521 }
16522
16523 #[test]
16524 fn ripple_delete_spans_partial_clips() {
16525 let mut p = three();
16526 // [2, 6) covers the tail of clip 0, all of clip 1 and the head of clip 2.
16527 assert!(p.ripple_delete(2, 4));
16528 assert_eq!(shape(&p)[0], vec![clip(0, 0, 2, 0), clip(2, 6, 9, 0)]);
16529 assert_eq!(shape(&p)[1], shape(&p)[0]);
16530 assert_eq!(p.timeline_frames(), 5);
16531 assert!(!p.ripple_delete(0, 0), "an empty range is not a delete");
16532 assert!(p.undo());
16533 assert_eq!(shape(&p), shape(&three()));
16534 // One that takes everything is a delete like any other: the timeline
16535 // empties, and the undo it cost brings it back whole.
16536 assert!(p.ripple_delete(0, 100), "the timeline is emptiable");
16537 assert_eq!(p.timeline_frames(), 0);
16538 assert!(
16539 !p.ripple_delete(0, 100),
16540 "and a delete with nothing left to take is not an undo step"
16541 );
16542 assert!(p.undo());
16543 assert_eq!(shape(&p), shape(&three()));
16544 }
16545
16546 /// A ripple trim closes the hole its trim leaves: the head cut from the middle clip goes, the
16547 /// clip keeps its start, and the last clip moves up by as much; an end edge moves what follows.
16548 #[test]
16549 fn ripple_trim_closes_the_hole_it_leaves() {
16550 let mut p = three();
16551 assert!(p.ripple_trim(Lane::V1, 1, Edge::Start, 4, &[9]));
16552 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 4, 5, 0), clip(4, 5, 9, 0)]);
16553 assert_eq!(shape(&p)[1], shape(&p)[0], "the linked audio moves with it");
16554 assert!(p.undo());
16555 assert_eq!(shape(&p), shape(&three()));
16556 assert!(p.ripple_trim(Lane::V1, 1, Edge::End, 4, &[9]));
16557 assert_eq!(shape(&p)[0], vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(4, 5, 9, 0)]);
16558 }
16559
16560 /// Undo says the newest step's name and Redo the one it took back, and the names
16561 /// walk back and forth with the steps they belong to.
16562 #[test]
16563 fn labels_follow_undo_and_redo() {
16564 let mut p = Project::single(FILE, 270);
16565 let mark = p.step_mark();
16566 assert!(p.split(100));
16567 p.name_step(mark, "Split");
16568 let mark = p.step_mark();
16569 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16570 p.name_step(mark, "Volume");
16571 assert_eq!(p.undo_label(), Some("Volume"));
16572 assert_eq!(p.redo_label(), None);
16573
16574 assert!(p.undo());
16575 assert_eq!(p.undo_label(), Some("Split"));
16576 assert_eq!(p.redo_label(), Some("Volume"));
16577 assert!(p.undo());
16578 assert_eq!(p.undo_label(), None, "nothing left to take back");
16579 assert_eq!(p.redo_label(), Some("Split"));
16580
16581 assert!(p.redo());
16582 assert_eq!(p.redo_label(), Some("Volume"));
16583 assert!(p.redo());
16584 assert_eq!(p.redo_label(), None);
16585 assert_eq!(p.undo_label(), Some("Volume"));
16586 }
16587
16588 /// A name goes only on a step the named action pushed: an action that changed
16589 /// nothing, and one that pushed nothing at all, leave the step under them alone.
16590 #[test]
16591 fn a_no_op_takes_no_name_and_drops_none() {
16592 let mut p = Project::single(FILE, 270);
16593 assert!(p.split(100));
16594 let mark = p.step_mark();
16595 assert!(!p.set_lane_gain_db(Lane::A1, 0.0), "already at 0 dB");
16596 assert_eq!(p.undo_label(), None, "the unnamed split is still the newest step");
16597 p.name_step(mark, "Volume");
16598 assert_eq!(p.undo_label(), None, "the no-op pushed nothing to name");
16599
16600 let mark = p.step_mark();
16601 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16602 assert!(!p.set_lane_gain_db(Lane::A1, -3.0), "a repeat is a no-op");
16603 assert_eq!(p.undo_label(), None, "the real edit is unnamed so far");
16604 p.name_step(mark, "Volume");
16605 assert_eq!(p.undo_label(), Some("Volume"));
16606 assert_eq!(p.history_len(), 2);
16607 }
16608
16609 /// A step that names itself and then gets settled as a no-op carries its name away
16610 /// with it: the step under it keeps its own.
16611 #[test]
16612 fn a_settled_no_op_drops_its_name_with_its_step() {
16613 let mut p = Project::single(FILE, 270);
16614 let mark = p.step_mark();
16615 assert!(p.split(100));
16616 p.name_step(mark, "Split");
16617 let mark = p.step_mark();
16618 assert!(!p.set_lane_gain_db(Lane::A1, 0.0));
16619 assert_eq!(p.undo_label(), Some("Split"), "the no-op on top is not the step");
16620 p.name_step(mark, "Volume");
16621 assert_eq!(p.undo_label(), Some("Split"));
16622 assert_eq!(p.history_len(), 1);
16623 assert_eq!(p.redo_len(), 0);
16624 }
16625
16626 /// Names ride with their steps through the cap: the oldest step goes, every step kept
16627 /// still says what it did, and the one taken back stays named after a redo.
16628 #[test]
16629 fn labels_survive_the_cap_eviction() {
16630 let mut p = Project::single(FILE, 400);
16631 let frames = HISTORY_CAP as u32 + 5;
16632 for frame in 1..=frames {
16633 let mark = p.step_mark();
16634 assert!(p.split(frame));
16635 let name = if frame <= 3 { "Old" } else { "Split" };
16636 p.name_step(mark, name);
16637 }
16638 assert_eq!(p.history_len(), HISTORY_CAP);
16639 let mut taken = 0;
16640 while let Some(label) = p.undo_label().map(str::to_string) {
16641 assert_eq!(label, "Split", "a kept step keeps its own name");
16642 assert!(p.undo());
16643 taken += 1;
16644 }
16645 assert_eq!(taken, HISTORY_CAP);
16646 assert!(p.redo());
16647 assert_eq!(p.undo_label(), Some("Split"));
16648 assert_eq!(p.redo_label(), Some("Split"));
16649 }
16650
16651 /// A batch is one step and so one name: whatever the batch did, Undo names it once.
16652 #[test]
16653 fn a_batch_carries_one_label() {
16654 let mut p = Project::single(FILE, 270);
16655 let mark = p.step_mark();
16656 p.begin_batch();
16657 assert!(p.split(100));
16658 assert!(p.set_lane_gain_db(Lane::A1, -3.0));
16659 p.end_batch();
16660 p.name_step(mark, "Split, volume");
16661 assert_eq!(p.history_len(), 1, "the batch is one step");
16662 assert_eq!(p.undo_label(), Some("Split, volume"));
16663 assert!(p.undo());
16664 assert_eq!(p.redo_label(), Some("Split, volume"));
16665 }
16666
16667 #[test]
16668 fn undo_restores_exactly() {
16669 let mut p = three();
16670 let after_splits = shape(&p);
16671 assert!(p.delete(1));
16672 assert!(p.undo());
16673 assert_eq!(shape(&p), after_splits);
16674
16675 // walk all the way back through both splits, then run dry
16676 assert!(p.undo());
16677 assert_eq!(p.clips().len(), 2);
16678 assert!(p.undo());
16679 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16680 assert!(!p.undo(), "empty history");
16681 assert_eq!(shape(&p)[0], vec![clip(0, 0, 9, 0)]);
16682 }
16683
16684 #[test]
16685 fn redo_restores_exactly() {
16686 let mut p = three();
16687 assert!(p.delete(1));
16688 let after_delete = p.parts();
16689 assert!(p.undo());
16690 assert!(p.redo());
16691 assert_eq!(p.parts(), after_delete, "redo lands back byte-identical");
16692 assert!(!p.redo(), "empty redo stack");
16693 }
16694
16695 #[test]
16696 fn edit_after_undo_empties_redo() {
16697 let mut p = three();
16698 assert!(p.delete(1));
16699 assert!(p.undo());
16700 assert_eq!(p.redo_len(), 1, "undo left a branch to redo");
16701 assert!(p.split(1), "a fresh edit");
16702 assert_eq!(p.redo_len(), 0, "the fresh edit clears it");
16703 assert!(!p.redo(), "so redo has nothing left");
16704 }
16705
16706 #[test]
16707 fn redo_on_empty_stack_is_false() {
16708 let mut p = three();
16709 assert!(!p.redo(), "nothing has been undone yet");
16710 }
16711
16712 #[test]
16713 fn take_and_restore_redo_round_trips() {
16714 let mut p = three();
16715 assert!(p.delete(1));
16716 let after_delete = p.parts();
16717 assert!(p.undo());
16718 let cp = p.take_redo();
16719 assert_eq!(p.redo_len(), 0, "taken out with no step");
16720 assert!(p.split(1), "a trial edit, which clears what is left");
16721 p.restore_redo(cp);
16722 assert_eq!(p.redo_len(), 1, "the stack the trial found is back");
16723 assert!(p.redo());
16724 assert_eq!(p.parts(), after_delete, "and it still redoes to the same state");
16725 }
16726
16727 #[test]
16728 fn held_history_evicts_nothing_until_released() {
16729 let mut p = Project::single(FILE, 400);
16730 for frame in 1..=HISTORY_CAP as u32 {
16731 assert!(p.split(frame));
16732 }
16733 p.hold_history(true);
16734 for frame in 101..=103 {
16735 assert!(p.split(frame));
16736 }
16737 assert_eq!(p.history.len(), HISTORY_CAP + 3, "a held trial evicts nothing");
16738 for _ in 0..3 {
16739 assert!(p.undo());
16740 }
16741 assert_eq!(p.history.len(), HISTORY_CAP, "the trial rolled back, the cap is still the same");
16742 p.hold_history(false);
16743 assert_eq!(p.history.len(), HISTORY_CAP);
16744 for frame in 101..=103 {
16745 assert!(p.split(frame));
16746 }
16747 p.hold_history(true);
16748 for frame in 110..=112 {
16749 assert!(p.split(frame));
16750 }
16751 assert_eq!(p.history.len(), HISTORY_CAP + 3);
16752 p.hold_history(false);
16753 assert_eq!(p.history.len(), HISTORY_CAP, "releasing trims back to the cap");
16754 }
16755
16756 /// Past the cap the *oldest* step goes, so a long session undoes exactly
16757 /// `HISTORY_CAP` gestures and then runs dry -- it does not grow for ever.
16758 #[test]
16759 fn history_stops_at_the_cap() {
16760 let mut p = Project::single(FILE, 400);
16761 for frame in 1..=150 {
16762 assert!(p.split(frame), "split {frame} is an edit");
16763 }
16764 assert_eq!(p.history.len(), HISTORY_CAP, "and only the last 100 kept");
16765 for step in 0..HISTORY_CAP {
16766 assert!(p.undo(), "undo {step} is inside the cap");
16767 }
16768 assert!(!p.undo(), "and the 101st has nothing left to take");
16769 // 100 undos off 150 splits is the timeline after the 50th: the older
16770 // steps were dropped, not the newer ones.
16771 assert_eq!(p.clips().len(), 51);
16772 }
16773
16774 /// The push count keeps rising past the cap, where `history_len` stops, so a
16775 /// caller can tell how many snapshots a batch pushed even at the cap.
16776 #[test]
16777 fn undo_pushes_counter_keeps_counting_past_the_cap() {
16778 let mut p = Project::single(FILE, 400);
16779 let start = p.history_pushes();
16780 for frame in 1..=HISTORY_CAP as u32 + 5 {
16781 assert!(p.split(frame));
16782 }
16783 assert_eq!(p.history.len(), HISTORY_CAP, "the length has saturated");
16784 assert_eq!(p.history_pushes() - start, HISTORY_CAP as u64 + 5);
16785 assert!(p.undo());
16786 assert_eq!(
16787 p.history_pushes() - start,
16788 HISTORY_CAP as u64 + 5,
16789 "an undo pushes nothing"
16790 );
16791 }
16792
16793 /// Undo/redo by hand across a split must never merge two takes into one
16794 /// group by reusing an id.
16795 #[test]
16796 fn group_ids_are_never_reused() {
16797 let mut p = Project::single(FILE, 9);
16798 assert!(p.split(3));
16799 let first = p.clips()[1].link;
16800 assert!(p.undo());
16801 assert!(p.split(5));
16802 assert_ne!(p.clips()[1].link, first, "a retired id must not come back");
16803 }
16804
16805 #[test]
16806 fn segments_from_reads_the_audio_lane() {
16807 let p = three();
16808 // mid-clip: partial first segment, whole clips after it
16809 assert_eq!(
16810 p.segments_from(4, FPS),
16811 vec![
16812 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
16813 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
16814 ]
16815 );
16816 // on a boundary: nothing partial
16817 assert_eq!(
16818 p.segments_from(3, FPS),
16819 vec![
16820 (Some(0), 3.0 / 30.0, 5.0 / 30.0),
16821 (Some(0), 5.0 / 30.0, 9.0 / 30.0)
16822 ]
16823 );
16824 // from the top: one entry per clip
16825 assert_eq!(p.segments_from(0, FPS).len(), 3);
16826 // last clip only
16827 assert_eq!(p.segments_from(8, FPS), vec![(Some(0), 8.0 / 30.0, 0.3)]);
16828 // past the end / unusable fps
16829 assert!(p.segments_from(9, FPS).is_empty());
16830 assert!(p.segments_from(0, 0.0).is_empty());
16831 assert!(p.segments_from(0, f64::NAN).is_empty());
16832 }
16833
16834 #[test]
16835 fn a_gap_in_the_audio_lane_is_a_silent_segment_of_its_own_length() {
16836 let mut p = three();
16837 assert!(p.lift(Lane::A1, 1)); // silence over timeline [3, 5)
16838 assert_eq!(
16839 p.segments_from(0, FPS),
16840 vec![
16841 (Some(0), 0.0, 3.0 / 30.0),
16842 (None, 0.0, 2.0 / 30.0),
16843 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
16844 ]
16845 );
16846 // The list still covers exactly the timeline: that is what stops the
16847 // master clock stalling at the hole.
16848 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
16849 assert!((played - 9.0 / 30.0).abs() < 1e-9, "{played}");
16850 // Starting inside the gap trims the silence, not the clip after it.
16851 assert_eq!(
16852 p.segments_from(4, FPS),
16853 vec![(None, 0.0, 1.0 / 30.0), (Some(0), 5.0 / 30.0, 9.0 / 30.0)]
16854 );
16855 // ...and a lane that is nothing but gap is a run of silence.
16856 assert!(p.lift(Lane::A1, 0));
16857 assert!(p.lift(Lane::A1, 0));
16858 assert_eq!(p.segments_from(0, FPS), vec![(None, 0.0, 0.3)]);
16859 }
16860
16861 /// `three()` plus a whole second source appended: clips [0,3) [3,5) [5,9)
16862 /// of source 0 then [0,4) of source 1.
16863 fn two_sources() -> Project {
16864 let mut p = three();
16865 let s = p.import(FILE2, 0);
16866 assert_eq!(s, 1);
16867 assert!(p.append_clip(s, 4));
16868 p
16869 }
16870
16871 #[test]
16872 fn import_dedups_and_appends() {
16873 let mut p = Project::single(FILE, 9);
16874 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
16875 assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
16876 assert_eq!(p.import(FILE2, 0), 1);
16877 assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
16878 // ...but the same file on another audio stream is another source: it is
16879 // what a clip names, and a clip plays exactly one stream.
16880 assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
16881 assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
16882 assert_eq!(p.sources()[2].audio_stream, 1);
16883 assert!(p.append_clip(2, 4), "a stream entry is placeable");
16884 assert!(p.undo());
16885 assert_eq!(p.sources().len(), 3);
16886 assert!(!p.append_clip(3, 5), "unknown source index");
16887 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
16888
16889 // Two spellings of one real file are one source: this is the case the
16890 // raw-path comparison above would get wrong.
16891 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
16892 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
16893 let mut p = Project::single(here, 9);
16894 assert_eq!(p.import(detour, 0), 0);
16895 assert_eq!(p.sources().len(), 1);
16896 }
16897
16898 #[test]
16899 fn append_clip_is_one_undo_step() {
16900 let mut p = two_sources();
16901 assert_eq!(p.timeline_frames(), 13);
16902 assert_eq!(shape(&p)[0][3], clip(9, 0, 4, 1));
16903 assert_eq!(shape(&p)[1][3], clip(9, 0, 4, 1), "and on the audio lane");
16904 assert_eq!(p.map_timeline(9), Some((3, 0)), "source 1 starts at 9");
16905 assert!(p.undo());
16906 assert_eq!(shape(&p), shape(&three()), "one step back to one source");
16907 assert_eq!(
16908 p.sources().len(),
16909 2,
16910 "the orphan source entry stays -- indexes are forever"
16911 );
16912 // ...and it is still usable, so a redo-by-hand costs no reimport.
16913 assert!(p.append_clip(1, 0));
16914 assert_eq!(p.clips()[3].len(), 1, "clamped like `single`");
16915 }
16916
16917 #[test]
16918 fn edits_carry_the_source_along() {
16919 let mut p = two_sources();
16920 // A split inside the second source splits into two source-1 clips.
16921 assert!(p.split(11));
16922 assert_eq!(shape(&p)[0][3], clip(9, 0, 2, 1));
16923 assert_eq!(shape(&p)[0][4], clip(11, 2, 4, 1));
16924
16925 // A source-1 clip pasted into source-0 territory keeps its file, and so
16926 // does the source-0 half that got split off around it.
16927 let copied = p.clips()[4].clone();
16928 assert!(p.paste(1, copied));
16929 assert_eq!(p.clips()[1].source, 1);
16930 assert_eq!(p.clips()[1].in_frame, 2);
16931 assert_eq!(p.clips()[2].source, 0);
16932 assert!(p.undo());
16933 assert_eq!(p.clips()[1].source, 0, "undo restores sources too");
16934 }
16935
16936 #[test]
16937 fn segments_from_names_the_source() {
16938 let p = two_sources();
16939 // Mid-clip in source 0, then the rest of source 0, then source 1 whole.
16940 assert_eq!(
16941 p.segments_from(4, FPS),
16942 vec![
16943 (Some(0), 4.0 / 30.0, 5.0 / 30.0),
16944 (Some(0), 5.0 / 30.0, 9.0 / 30.0),
16945 (Some(1), 0.0, 4.0 / 30.0),
16946 ]
16947 );
16948 // Mid-clip in source 1: only that source is left.
16949 assert_eq!(
16950 p.segments_from(10, FPS),
16951 vec![(Some(1), 1.0 / 30.0, 4.0 / 30.0)]
16952 );
16953 assert!(p.segments_from(13, FPS).is_empty());
16954 // Segments still cover exactly the timeline across the join.
16955 let played: f64 = p.segments_from(0, FPS).iter().map(|(_, a, b)| b - a).sum();
16956 assert!((played - f64::from(p.timeline_frames()) / FPS).abs() < 1e-9);
16957 }
16958
16959 #[test]
16960 fn segments_follow_deletes_and_fps() {
16961 let mut p = three();
16962 assert!(p.delete(0));
16963 // source seconds, not timeline: deleting the head does not shift them
16964 let segs = p.segments_from(0, 25.0);
16965 assert_eq!(
16966 segs,
16967 vec![(Some(0), 3.0 / 25.0, 0.2), (Some(0), 0.2, 9.0 / 25.0)]
16968 );
16969 let played: f64 = segs.iter().map(|(_, a, b)| b - a).sum();
16970 assert!(
16971 (played - p.timeline_frames() as f64 / 25.0).abs() < 1e-9,
16972 "segments must cover exactly the timeline: {played}"
16973 );
16974 }
16975
16976 #[test]
16977 fn every_source_is_saved_in_session_order_and_the_clips_keep_theirs() {
16978 // Import a second file, undo it: source 1 is now an orphan. It is kept
16979 // anyway -- an import is not an undo step, so the library entry stays
16980 // at the index a reload will look for it at.
16981 let mut p = two_sources();
16982 assert!(p.undo());
16983 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
16984 assert_eq!(
16985 sources,
16986 vec![Source::new(FILE, 0), Source::new(FILE2, 0)],
16987 "the orphan is kept, in session order"
16988 );
16989 assert!(eq.is_empty(), "and a project with no equalizer writes none");
16990 assert!(color.is_empty(), "nor a colour it never graded with");
16991 assert_eq!(
16992 lanes,
16993 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
16994 "the clips are untouched"
16995 );
16996
16997 // Three sources where only the middle one is unused: all three are
16998 // saved, in order, and the clip keeps the index it was given -- 2 here,
16999 // not renumbered down to 1. (The clip from `single` is still source 0.)
17000 let mut p = Project::single(FILE, 9);
17001 assert_eq!(p.import(FILE2, 0), 1);
17002 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
17003 assert!(p.append_clip(2, 4));
17004 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17005 assert_eq!(
17006 sources,
17007 vec![
17008 Source::new(FILE, 0),
17009 Source::new(FILE2, 0),
17010 Source::new("/nonexistent/c.mp4", 0)
17011 ]
17012 );
17013 assert_eq!(
17014 lanes[0].1.iter().map(|c| c.source).collect::<Vec<_>>(),
17015 [0, 2]
17016 );
17017 // ...and what comes out is loadable, with the same timeline.
17018 let reloaded =
17019 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17020 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
17021 assert_eq!(reloaded.sources().len(), 3);
17022 }
17023
17024 /// Taking a file out of the library: refused by name -- lanes and counts --
17025 /// while a clip still plays from it, and once nothing does, the entry goes
17026 /// and every clip that indexed past it is renumbered onto the short list.
17027 /// A project rebuilt from parts keeps each source's bin and star (the loader's own door).
17028 #[test]
17029 fn from_parts_keeps_a_sources_bin_and_star() {
17030 let mut one = Source::new(FILE, 0);
17031 one.fav = true;
17032 one.bin = 7;
17033 let lanes = vec![(LaneKind::Video, vec![clip(0, 0, 10, 0)]), (LaneKind::Audio, vec![clip(0, 0, 10, 0)])];
17034 let p = Project::from_parts(vec![one], lanes, vec![], vec![], Vec::new()).expect("valid parts");
17035 assert!(p.sources()[0].fav);
17036 assert_eq!(p.sources()[0].bin, 7);
17037 }
17038
17039 #[test]
17040 fn bins_and_favourites_follow_the_usual_edit_rules() {
17041 let mut p = two_sources();
17042 let a = p.create_bin(" Interviews ", 0).expect("makes a bin");
17043 assert_eq!(p.bins()[0].name, "Interviews");
17044 assert!(p.create_bin("interviews", 0).is_err(), "no twin at one place");
17045 let b = p.create_bin("Day 1", a).expect("one level of nesting");
17046 assert!(p.create_bin("deeper", b).is_err(), "no third level");
17047 assert!(p.create_bin(" ", 0).is_err() && p.create_bin("a\nb", 0).is_err() && p.create_bin("x", 99).is_err());
17048 assert_eq!(p.move_to_bin(&[0, 1, 1], b), Ok(2));
17049 assert_eq!(p.move_to_bin(&[0], b), Ok(0), "no change, no history");
17050 assert!(p.move_to_bin(&[7], b).is_err() && p.move_to_bin(&[0], 42).is_err());
17051 assert_eq!(p.set_favourite(&[1], true), Ok(1));
17052 assert_eq!(p.set_favourite(&[1], true), Ok(0));
17053 assert!(p.sources()[1].fav && p.sources()[1].bin == b);
17054 assert_eq!(p.rename_bin(b, "Day one"), Ok(true));
17055 assert_eq!(p.rename_bin(b, "Day one"), Ok(false));
17056 // Undo walks back one step at a time: rename, star, move, then the bins themselves.
17057 assert!(p.undo() && p.bins()[1].name == "Day 1");
17058 assert!(p.undo() && !p.sources()[1].fav);
17059 assert!(p.undo() && p.sources()[0].bin == 0);
17060 assert!(p.redo() && p.sources()[0].bin == b);
17061 // Removing the outer bin keeps what it held: sources go up, inner bins to the top.
17062 assert_eq!(p.remove_bin(a), Ok(0));
17063 assert_eq!(p.bins().len(), 1);
17064 assert_eq!(p.bins()[0].parent, 0);
17065 assert_eq!(p.remove_bin(b), Ok(2));
17066 assert!(p.sources().iter().all(|s| s.bin == 0));
17067 assert!(p.undo() && p.sources()[0].bin == b && p.bins().len() == 1);
17068 assert!(p.undo() && p.bins().len() == 2 && p.bins()[1].parent == a);
17069 // A source's identity is its file and stream, not its star.
17070 assert_eq!(p.sources()[0], Source::new(&p.sources()[0].path, 0));
17071 }
17072
17073 #[test]
17074 fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
17075 // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
17076 // plus a second stream of FILE as source 2 with a take of its own.
17077 let mut p = two_sources();
17078 assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
17079 assert!(p.append_clip(2, 4));
17080
17081 let refusal = p
17082 .remove_source(1)
17083 .expect_err("a source with clips on it cannot go")
17084 .to_string();
17085 assert!(refusal.contains(FILE2), "names the file: {refusal}");
17086 assert!(
17087 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
17088 "names the lanes holding it: {refusal}"
17089 );
17090 assert!(refusal.contains("still plays"), "{refusal}");
17091 assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
17092 assert_eq!(shape(&p)[0][3].source, 1);
17093
17094 // Delete FILE2's take -- the whole span, on every lane -- and the entry
17095 // is free to go. Source 2's clips become source 1's.
17096 assert!(p.delete_in(Lane::V1, 3));
17097 assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
17098 p.remove_source(1).expect("nothing plays FILE2 any more");
17099 assert_eq!(
17100 p.sources(),
17101 [Source::new(FILE, 0), Source::new(FILE, 1)],
17102 "the middle entry is gone"
17103 );
17104 assert_eq!(
17105 shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
17106 [0, 0, 0, 1],
17107 "the clips past it renumbered"
17108 );
17109 assert_eq!(
17110 shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
17111 [0, 0, 0, 1],
17112 "on every lane"
17113 );
17114 // What is left is a project that still loads, which is the whole point
17115 // of renumbering rather than leaving a hole.
17116 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
17117 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("from_parts");
17118 }
17119
17120 /// The two edges of a removal: it retires the undo stack (the corner-cut on
17121 /// [`Project::remove_source`]), and the last entry goes like any other
17122 /// once nothing plays it -- a project may name no file at all.
17123 #[test]
17124 fn relink_is_one_undo_step_and_undo_puts_the_old_path_back() {
17125 let mut p = two_sources();
17126 let old = p.sources()[1].path.clone();
17127 let new = Source::new(FILE, 0).path;
17128 let depth = p.history_len();
17129 p.relink_source(1, Path::new(FILE)).expect("relinks");
17130 assert_eq!(p.sources()[1].path, new);
17131 assert_eq!(p.history_len(), depth + 1, "one step");
17132 assert!(p.undo());
17133 assert_eq!(p.sources()[1].path, old, "undo points back at the old file");
17134 assert!(p.redo());
17135 assert_eq!(p.sources()[1].path, new, "redo re-points it");
17136 p.relink_source(1, Path::new(FILE)).expect("the path it has");
17137 assert_eq!(p.history_len(), depth + 1, "a relink to the same path is no step");
17138 assert!(p.relink_source(9, Path::new(FILE)).is_err(), "no source 9");
17139 }
17140
17141 #[test]
17142 fn undo_keeps_a_source_imported_after_the_step() {
17143 let mut p = three();
17144 assert_eq!(p.import(FILE2, 0), 1);
17145 assert!(p.undo(), "the last split");
17146 assert_eq!(p.sources().len(), 2, "the import outlives the undo, as an import does");
17147 assert_eq!(p.sources()[1].path, Source::new(FILE2, 0).path);
17148 assert!(p.redo());
17149 assert_eq!(p.sources().len(), 2);
17150 }
17151
17152 #[test]
17153 fn adopt_as_step_takes_the_other_timeline_and_undo_gives_this_one_back() {
17154 let geometry = |p: &Project| -> Vec<Vec<(u32, u32, u32, usize)>> {
17155 p.lanes()
17156 .into_iter()
17157 .map(|l| p.lane(l).iter().map(|c| (c.start, c.in_frame, c.out_frame, c.source)).collect())
17158 .collect()
17159 };
17160 let mut p = three();
17161 assert!(p.set_eq(Lane::A1, 0, Some(band_at(7))), "this project's own table entry");
17162 let mut other = two_sources();
17163 assert!(other.set_eq(Lane::A1, 0, Some(band_at(2))));
17164 let (want, want_eq) = (geometry(&other), other.eq_of(Lane::A1, 0).cloned());
17165 let saved = geometry(&p);
17166 let depth = p.history_len();
17167 assert!(p.adopt_as_step(&other));
17168 assert_eq!(p.history_len(), depth + 1, "one step");
17169 assert_eq!(geometry(&p), want, "the other timeline");
17170 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq, "its effects read from the appended table");
17171 assert!(p.undo());
17172 assert_eq!(geometry(&p), saved);
17173 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), Some(band_at(7)), "and this project's own table is still there");
17174 assert!(p.redo());
17175 assert_eq!(geometry(&p), want);
17176 assert_eq!(p.eq_of(Lane::A1, 0).cloned(), want_eq);
17177 assert_eq!(p.sources()[1].path, other.sources()[1].path, "the other sources come with it");
17178 }
17179
17180 /// A recovery takes the autosave's markers with its timeline, and undo gives back the
17181 /// markers this project had: the marker list is part of what a step restores.
17182 #[test]
17183 fn adopt_as_step_carries_the_markers_of_the_other_timeline() {
17184 let marker = |frame: u32, name: &str| Marker {
17185 frame,
17186 length: 0,
17187 name: name.into(),
17188 note: String::new(),
17189 color: MarkerColor::Red,
17190 };
17191 let mut p = three();
17192 assert!(p.add_marker(marker(4, "mine")).is_ok());
17193 let mut other = two_sources();
17194 assert!(other.add_marker(marker(9, "theirs")).is_ok());
17195 assert!(p.adopt_as_step(&other));
17196 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17197 assert_eq!(names, ["theirs"], "the other timeline's markers");
17198 assert!(p.undo());
17199 let names: Vec<&str> = p.markers().iter().map(|m| m.name.as_str()).collect();
17200 assert_eq!(names, ["mine"], "undo gives this project's markers back");
17201 }
17202
17203 #[test]
17204 fn revision_walks_back_with_undo_and_never_repeats() {
17205 let mut p = three();
17206 let saved = p.revision();
17207 assert!(p.delete_in(Lane::V1, 2));
17208 let edited = p.revision();
17209 assert_ne!(edited, saved, "an edit moves the timeline off the saved state");
17210 assert!(p.undo());
17211 assert_eq!(p.revision(), saved, "undo back to the saved timeline gives its id back");
17212 assert!(p.redo());
17213 assert_eq!(p.revision(), edited, "redo walks forward to the same id");
17214 // A new edit after an undo is a state of its own: it must not read as the saved one.
17215 assert!(p.undo());
17216 assert!(p.delete_in(Lane::V1, 0));
17217 assert_ne!(p.revision(), saved, "a branch off the saved timeline is not the saved one");
17218 assert_ne!(p.revision(), edited);
17219 assert!(!p.redo(), "the branch cleared the redo stack");
17220 assert_eq!(p.revision(), p.revision(), "reading is not an edit");
17221 }
17222
17223 #[test]
17224 fn revision_moves_once_per_batch_step_and_undo_takes_the_whole_batch_back() {
17225 let mut p = three();
17226 let saved = p.revision();
17227 p.begin_batch();
17228 assert!(p.delete_in(Lane::V1, 2));
17229 let first = p.revision();
17230 assert!(p.delete_in(Lane::V1, 1));
17231 assert_ne!(p.revision(), first, "each edit in a batch is a new state");
17232 p.end_batch();
17233 assert!(p.undo());
17234 assert_eq!(p.revision(), saved, "one undo takes the whole batch back to the saved id");
17235 }
17236
17237 #[test]
17238 fn revision_of_a_recovery_step_is_undone_back_to_the_timeline_it_replaced() {
17239 let mut current = three();
17240 assert!(current.delete_in(Lane::V1, 2));
17241 let edited = current.revision();
17242 let other = two_sources();
17243 assert!(current.adopt_as_step(&other));
17244 assert_ne!(current.revision(), edited, "the other timeline is a new state");
17245 assert!(current.undo());
17246 assert_eq!(current.revision(), edited, "undo gives back the timeline it replaced, by its id");
17247 }
17248
17249 #[test]
17250 fn remove_source_retires_undo_and_empties_the_library() {
17251 let mut p = two_sources();
17252 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
17253 assert!(!p.history.is_empty(), "there is something to undo");
17254 p.remove_source(1).expect("nothing plays FILE2");
17255 assert!(
17256 p.history.is_empty(),
17257 "a snapshot naming the removed source must not survive it"
17258 );
17259 assert!(!p.undo(), "and so there is nothing left to undo");
17260
17261 // The last file standing is held to the one rule every row is -- what
17262 // plays cannot go -- and to no other.
17263 assert_eq!(p.sources().len(), 1);
17264 let refusal = p
17265 .remove_source(0)
17266 .expect_err("its clips are still on the lanes")
17267 .to_string();
17268 assert!(refusal.contains("still plays"), "{refusal}");
17269 assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
17270 while p.delete_in(Lane::V1, 0) {}
17271 p.remove_source(0)
17272 .expect("the last row goes like any other");
17273 assert!(
17274 p.sources().is_empty(),
17275 "a project may name no file at all: an empty library over an empty timeline"
17276 );
17277 assert_eq!(p.timeline_frames(), 0);
17278 assert!(
17279 p.remove_source(0).is_err(),
17280 "and an index that is not there is refused, not panicked on"
17281 );
17282 }
17283
17284 /// A clip's equalizer is the clip's: it survives every edit that copies a
17285 /// placement, and it comes back with an undo.
17286 #[test]
17287 fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
17288 let mut p = three();
17289 assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
17290 assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
17291 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17292 assert!(
17293 p.eq_of(Lane::V1, 0).is_none(),
17294 "one clip, not the lane above"
17295 );
17296
17297 // Cutting an EQ'd clip must not silence half of it: both halves inherit.
17298 assert!(p.split(1));
17299 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17300 assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
17301 assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
17302
17303 // A clipboard copy carries it -- onto another lane, at that.
17304 let copied = p.lane(Lane::A1)[1].clone();
17305 assert!(p.place(Lane::V1, 20, copied));
17306 assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
17307 assert!(p.undo());
17308 assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
17309
17310 // ...and a change to one is one undo step, in both directions.
17311 assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
17312 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
17313 assert!(p.undo());
17314 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17315 assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
17316 assert!(p.eq_of(Lane::A1, 0).is_none());
17317 assert!(p.undo());
17318 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17319
17320 // Two refusals, neither of which costs an undo step.
17321 let mut nan = band_at(1);
17322 nan.bands[0].q = f32::INFINITY;
17323 assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
17324 assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
17325 assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
17326 assert!(p.undo());
17327 assert_eq!(
17328 p.lane(Lane::A1).len(),
17329 3,
17330 "one step back is before the split"
17331 );
17332 assert!(p.undo());
17333 assert!(
17334 p.eq_of(Lane::A1, 0).is_none(),
17335 "and the next is before the setting: the refusals pushed none"
17336 );
17337 }
17338
17339 /// The table is append-only within a session, exactly as the sources are, so
17340 /// an undone setting is still in it -- and a save is where it goes.
17341 #[test]
17342 fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
17343 let mut p = three();
17344 assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
17345 assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
17346 assert!(p.undo(), "back to the first setting");
17347 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
17348
17349 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17350 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
17351 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
17352 assert_eq!(lanes[0].1[1].eq, None);
17353
17354 // One curve on three clips is one entry: settings that are equal share.
17355 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
17356 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
17357 let (_, lanes, eq, _, _) = p.without_orphan_sources();
17358 assert_eq!(eq.len(), 1, "equal settings share their entry");
17359 assert_eq!(lanes[1].1[2].eq, Some(0));
17360 reloads(&p, "an equalizer that outlived an undo");
17361 }
17362
17363 /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17364 /// grade is the clip's, through every edit that copies a placement.
17365 #[test]
17366 fn a_colour_follows_the_clip_through_split_copy_and_undo() {
17367 let mut p = three();
17368 assert!(
17369 p.color_of(Lane::V1, 0).is_none(),
17370 "a fresh clip is ungraded"
17371 );
17372 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17373 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17374 assert!(
17375 p.color_of(Lane::A1, 0).is_none(),
17376 "one clip, not the lane below"
17377 );
17378 assert!(
17379 p.eq_of(Lane::V1, 0).is_none(),
17380 "and a grade is not an equalizer"
17381 );
17382
17383 // Cutting a graded clip must not grade half of it: both halves inherit.
17384 assert!(p.split(1));
17385 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17386 assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
17387 assert!(
17388 p.color_of(Lane::V1, 2).is_none(),
17389 "the clip after it is ungraded"
17390 );
17391
17392 // A clipboard copy carries it -- onto another lane, at that.
17393 let copied = p.lane(Lane::V1)[1].clone();
17394 assert!(p.place(Lane::A1, 20, copied));
17395 assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
17396 assert!(p.undo());
17397 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17398
17399 // ...and a change to one is one undo step, in both directions.
17400 assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
17401 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
17402 assert!(p.undo());
17403 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17404 assert!(
17405 p.set_color(Lane::V1, 0, None),
17406 "and taking it off is an edit"
17407 );
17408 assert!(p.color_of(Lane::V1, 0).is_none());
17409 assert!(p.undo());
17410 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17411
17412 // Two refusals, neither of which costs an undo step.
17413 let nan = ColorParams {
17414 contrast: f32::NAN,
17415 ..grade_at(1)
17416 };
17417 assert!(
17418 !p.set_color(Lane::V1, 99, Some(grade_at(1))),
17419 "no clip there"
17420 );
17421 assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
17422 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
17423 assert!(p.undo());
17424 assert_eq!(
17425 p.lane(Lane::V1).len(),
17426 3,
17427 "one step back is before the split"
17428 );
17429 assert!(p.undo());
17430 assert!(
17431 p.color_of(Lane::V1, 0).is_none(),
17432 "and the next is before the grade: the refusals pushed none"
17433 );
17434 }
17435
17436 /// A slider drag is one gesture: the press snapshots, every sample after it
17437 /// only regrades, and the single undo lands on what the clip was *before*
17438 /// the hand touched it -- not one step back down the drag.
17439 #[test]
17440 fn a_whole_colour_drag_undoes_in_one_step() {
17441 let mut p = three();
17442 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
17443 for n in 2..=8 {
17444 assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
17445 }
17446 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
17447 assert!(p.undo());
17448 assert!(
17449 p.color_of(Lane::V1, 0).is_none(),
17450 "one undo is the whole gesture, back to ungraded"
17451 );
17452
17453 // The live write refuses what the snapshotting one refuses, and a
17454 // refusal still costs no history either way.
17455 assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
17456 assert!(!p.set_color_live(
17457 Lane::V1,
17458 0,
17459 Some(ColorParams {
17460 contrast: f32::NAN,
17461 ..grade_at(1)
17462 })
17463 ));
17464 assert!(p.undo());
17465 assert_eq!(
17466 p.lane(Lane::V1).len(),
17467 2,
17468 "the next step back is the split before the drag: no sample pushed one"
17469 );
17470 }
17471
17472 /// A drag across the colour wheel is one gesture -- the look's twin of
17473 /// [`a_whole_colour_drag_undoes_in_one_step`]: the press snapshots, every
17474 /// sample after it only repaints, and the single undo lands on the look
17475 /// the clip had *before* the hand touched it. The committing setter is
17476 /// still exactly one step, refusals included.
17477 /// A LUT is relinked like media: every clip naming the old path moves to the
17478 /// new one in one undo step, a missing file is a named problem rather than an
17479 /// error, and keys leave the look alone.
17480 #[test]
17481 fn a_lut_relinks_in_one_step_and_a_missing_one_is_named() {
17482 let dir = std::env::temp_dir().join(format!("edith-relink-lut-{}", std::process::id()));
17483 std::fs::create_dir_all(&dir).unwrap();
17484 let good = dir.join("good.cube");
17485 std::fs::write(&good, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap();
17486 let gone = dir.join("gone.cube");
17487 let mut p = three();
17488 let with = |path: &Path| ColorParams {
17489 look: crate::color::Look { lut: Some(crate::cube::LutRef::open(path)), ..Default::default() },
17490 ..Default::default()
17491 };
17492 assert!(p.set_color(Lane::V1, 0, Some(with(&gone))));
17493 assert!(p.set_color(Lane::V1, 1, Some(with(&gone))));
17494 let problems = p.lut_problems();
17495 assert_eq!(problems.len(), 1, "one file, named once");
17496 assert!(problems[0].0 == gone && problems[0].1.contains("cannot read"));
17497 assert_eq!(p.relink_lut(&dir.join("other.cube"), &good), 0, "nothing names it");
17498 assert_eq!(p.relink_lut(&gone, &good), 2);
17499 assert!(p.lut_problems().is_empty());
17500 assert_eq!(p.color_of(Lane::V1, 1).and_then(|c| c.look.lut).map(|r| r.path()), Some(good.clone()));
17501 assert!(p.undo());
17502 assert_eq!(p.lut_problems().len(), 1, "one undo puts both back");
17503 std::fs::remove_dir_all(&dir).ok();
17504 }
17505
17506 #[test]
17507 fn a_whole_look_drag_undoes_in_one_step() {
17508 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
17509 let mut p = three();
17510 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "the press");
17511 for hue in 2..=8u8 {
17512 assert!(p.set_viz_paint_live(Lane::V1, 0, look(hue)), "a sample");
17513 }
17514 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(8));
17515 assert!(p.undo());
17516 assert_eq!(
17517 p.lane(Lane::V1)[0].viz_paint,
17518 0,
17519 "one undo is the whole gesture, back to the default look"
17520 );
17521
17522 // The live write refuses an index that is not there -- and a refusal
17523 // costs no history -- while one committing write is one step back.
17524 assert!(!p.set_viz_paint_live(Lane::V1, 99, look(1)));
17525 assert!(p.set_viz_paint(Lane::V1, 0, look(1)), "a click, not a drag");
17526 assert_eq!(p.lane(Lane::V1)[0].viz_paint, look(1));
17527 assert!(p.undo());
17528 assert_eq!(
17529 p.lane(Lane::V1)[0].viz_paint,
17530 0,
17531 "the committing setter is one undo step, no more"
17532 );
17533 }
17534
17535 /// The colour table is append-only within a session, exactly as the eq one
17536 /// is -- and a save is where an undone grade goes.
17537 #[test]
17538 fn an_undone_colour_is_pruned_when_the_project_is_saved() {
17539 let mut p = three();
17540 assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
17541 assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
17542 assert!(p.undo(), "back to the first grade");
17543 assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
17544
17545 let (_, lanes, _, color, _) = p.without_orphan_sources();
17546 assert_eq!(
17547 color,
17548 vec![grade_at(1)],
17549 "what nothing plays is not written"
17550 );
17551 assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
17552 assert_eq!(lanes[0].1[1].color, None);
17553
17554 // One grade on three clips is one entry: settings that are equal share.
17555 assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
17556 assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
17557 let (_, lanes, _, color, _) = p.without_orphan_sources();
17558 assert_eq!(color.len(), 1, "equal grades share their entry");
17559 assert_eq!(lanes[1].1[2].color, Some(0));
17560 reloads(&p, "a colour that outlived an undo");
17561
17562 // An equalizer and a grade on one clip are two independent tables.
17563 assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
17564 let (_, lanes, eq, color, _) = p.without_orphan_sources();
17565 assert_eq!((eq.len(), color.len()), (1, 1));
17566 assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
17567 }
17568
17569 /// [`a_colour_follows_the_clip_through_split_copy_and_undo`]'s twin: a
17570 /// placement is the clip's, through every edit that copies one.
17571 #[test]
17572 fn a_transform_follows_the_clip_through_split_copy_and_undo() {
17573 let mut p = three();
17574 assert!(
17575 p.transform_of(Lane::V1, 0).is_none(),
17576 "a fresh clip is untransformed"
17577 );
17578 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17579 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17580 assert!(
17581 p.transform_of(Lane::A1, 0).is_none(),
17582 "one clip, not the lane below"
17583 );
17584 assert!(
17585 p.color_of(Lane::V1, 0).is_none(),
17586 "and a placement is not a grade"
17587 );
17588
17589 // Cutting a transformed clip must not transform half of it: both
17590 // halves inherit.
17591 assert!(p.split(1));
17592 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17593 assert_eq!(p.transform_of(Lane::V1, 1), Some(&transform_at(2)));
17594 assert!(
17595 p.transform_of(Lane::V1, 2).is_none(),
17596 "the clip after it is untransformed"
17597 );
17598
17599 // A clipboard copy carries it -- onto another lane, at that.
17600 let copied = p.lane(Lane::V1)[1].clone();
17601 assert!(p.place(Lane::A1, 20, copied));
17602 assert_eq!(p.transform_of(Lane::A1, 4), Some(&transform_at(2)));
17603 assert!(p.undo());
17604 assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
17605
17606 // ...and a change to one is one undo step, in both directions.
17607 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(5))));
17608 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(5)));
17609 assert!(p.undo());
17610 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17611 assert!(
17612 p.set_transform(Lane::V1, 0, None),
17613 "and taking it off is an edit"
17614 );
17615 assert!(p.transform_of(Lane::V1, 0).is_none());
17616 assert!(p.undo());
17617 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17618
17619 // Two refusals, neither of which costs an undo step.
17620 let nan = TransformParams {
17621 scale: f32::NAN,
17622 ..transform_at(1)
17623 };
17624 assert!(
17625 !p.set_transform(Lane::V1, 99, Some(transform_at(1))),
17626 "no clip there"
17627 );
17628 assert!(
17629 !p.set_transform(Lane::V1, 0, Some(nan)),
17630 "not a finite value"
17631 );
17632 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(2)));
17633 assert!(p.undo());
17634 assert_eq!(
17635 p.lane(Lane::V1).len(),
17636 3,
17637 "one step back is before the split"
17638 );
17639 assert!(p.undo());
17640 assert!(
17641 p.transform_of(Lane::V1, 0).is_none(),
17642 "and the next is before the placement: the refusals pushed none"
17643 );
17644 }
17645
17646 /// The transform table is append-only within a session, exactly as the eq
17647 /// and colour ones are -- and a save is where an undone placement goes.
17648 #[test]
17649 fn an_undone_transform_is_pruned_when_the_project_is_saved() {
17650 let mut p = three();
17651 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(1))));
17652 assert!(p.set_transform(Lane::V1, 0, Some(transform_at(2))));
17653 assert!(p.undo(), "back to the first placement");
17654 assert_eq!(p.transform_of(Lane::V1, 0), Some(&transform_at(1)));
17655
17656 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17657 assert_eq!(
17658 transform,
17659 vec![transform_at(1)],
17660 "what nothing plays is not written"
17661 );
17662 assert_eq!(
17663 lanes[0].1[0].transform,
17664 Some(0),
17665 "and the survivor renumbers"
17666 );
17667 assert_eq!(lanes[0].1[1].transform, None);
17668
17669 // One placement on three clips is one entry: settings that are equal
17670 // share.
17671 assert!(p.set_transform(Lane::V1, 1, Some(transform_at(1))));
17672 assert!(p.set_transform(Lane::A1, 2, Some(transform_at(1))));
17673 let (_, lanes, _, _, transform) = p.without_orphan_sources();
17674 assert_eq!(transform.len(), 1, "equal placements share their entry");
17675 assert_eq!(lanes[1].1[2].transform, Some(0));
17676 reloads(&p, "a transform that outlived an undo");
17677
17678 // A grade and a placement on one clip are two independent tables.
17679 assert!(p.set_color(Lane::V1, 0, Some(grade_at(3))));
17680 let (_, lanes, _, color, transform) = p.without_orphan_sources();
17681 assert_eq!((color.len(), transform.len()), (1, 1));
17682 assert_eq!(
17683 (lanes[0].1[0].color, lanes[0].1[0].transform),
17684 (Some(0), Some(0))
17685 );
17686 }
17687
17688 /// Not a claim about correctness but about cost: a clip is cloned on every
17689 /// paste, every undo snapshot and every lane clone, so its size is worth
17690 /// bounding. A clip is no longer `Copy` by design -- the keyframed gain
17691 /// envelope (`gain_keys`) owns a `Vec` -- so a clone is a heap allocation
17692 /// too, and the bound that matters is the inline size: 224 bytes today (the
17693 /// deinterlace choice, one byte, took it from 216 as there was no padding left)
17694 /// (the visualizer `u64` and six `Vec`s, the volume, placement, speed
17695 /// ramp, opacity and colour keys and the effects stack, are the wide fields; the placement keys raised it from 96 by one
17696 /// `Vec`, the speed ramp raised it from 120 by another, the opacity and
17697 /// colour keys took it from 144 to 192, and the effects stack to 216, the multicam angle to 224). The
17698 /// bound is `<=` rather than `==` so a field that shrinks the clip does not
17699 /// trip it; growing past it is the thing to notice.
17700 #[test]
17701 fn a_clip_stays_within_224_bytes() {
17702 assert!(
17703 std::mem::size_of::<Clip>() <= 224,
17704 "Clip grew to {} bytes -- every undo snapshot and clone pays for it",
17705 std::mem::size_of::<Clip>()
17706 );
17707 }
17708
17709 #[test]
17710 fn from_parts_has_no_history_and_checks_the_invariants() {
17711 let (sources, lanes, eq, color, _transform) = three().without_orphan_sources();
17712 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
17713 let mut p = Project::from_parts(
17714 sources.clone(),
17715 lanes.clone(),
17716 eq.clone(),
17717 color.clone(),
17718 Vec::new(),
17719 )
17720 .expect("valid parts");
17721 assert_eq!(p.clips(), three().clips());
17722 assert!(!p.undo(), "a loaded project has nothing to undo");
17723 assert!(p.split(4), "...and is editable from there");
17724 assert!(p.undo());
17725
17726 // A lane may be empty, and so may every lane -- an emptied timeline is a
17727 // project. No lane at all is not one: there would be nothing to place on.
17728 assert!(
17729 Project::from_parts(
17730 sources.clone(),
17731 two(video.clone(), Vec::new()),
17732 Vec::new(),
17733 Vec::new(),
17734 Vec::new(),
17735 )
17736 .is_ok()
17737 );
17738 assert!(
17739 Project::from_parts(
17740 sources.clone(),
17741 two(Vec::new(), Vec::new()),
17742 Vec::new(),
17743 Vec::new(),
17744 Vec::new(),
17745 )
17746 .is_ok()
17747 );
17748 assert!(
17749 Project::from_parts(
17750 sources.clone(),
17751 Vec::new(),
17752 Vec::new(),
17753 Vec::new(),
17754 Vec::new()
17755 )
17756 .is_err()
17757 );
17758 let bad: [Vec<Clip>; 5] = [
17759 vec![clip(0, 0, 3, 1)], // source that is not there
17760 vec![clip(0, 3, 3, 0)], // empty clip
17761 vec![clip(3, 0, 3, 0), clip(0, 3, 5, 0)], // out of order
17762 vec![clip(0, 0, 5, 0), clip(3, 3, 5, 0)], // overlapping
17763 vec![clip(u32::MAX - 1, 0, 3, 0)], // end past the last frame
17764 ];
17765 for clips in bad {
17766 assert!(
17767 Project::from_parts(
17768 sources.clone(),
17769 two(clips.clone(), Vec::new()),
17770 Vec::new(),
17771 Vec::new(),
17772 Vec::new(),
17773 )
17774 .is_err(),
17775 "{clips:?}"
17776 );
17777 assert!(
17778 Project::from_parts(
17779 sources.clone(),
17780 two(video.clone(), clips.clone()),
17781 Vec::new(),
17782 Vec::new(),
17783 Vec::new(),
17784 )
17785 .is_err()
17786 );
17787 // ...and on a third lane, which is checked by the same walk.
17788 assert!(
17789 Project::from_parts(
17790 sources.clone(),
17791 vec![
17792 (LaneKind::Video, video.clone()),
17793 (LaneKind::Audio, audio.clone()),
17794 (LaneKind::Video, clips),
17795 ],
17796 Vec::new(),
17797 Vec::new(),
17798 Vec::new(),
17799 )
17800 .is_err()
17801 );
17802 }
17803 // An equalizer index no table entry answers, and a table entry the file
17804 // format could not have written, are refused at this door too.
17805 let eqd = |i: u16| {
17806 vec![Clip {
17807 fade_in: 0,
17808 fade_out: 0,
17809 transition_out: 0,
17810 transition_kind: Default::default(),
17811 visualizer: 0,
17812 viz_paint: 0,
17813 gain_db: 0.0,
17814 eq: Some(i),
17815 ..video[0].clone()
17816 }]
17817 };
17818 assert!(
17819 Project::from_parts(
17820 sources.clone(),
17821 two(eqd(0), Vec::new()),
17822 Vec::new(),
17823 Vec::new(),
17824 Vec::new(),
17825 )
17826 .is_err()
17827 );
17828 let mut nan = band_at(1);
17829 nan.bands[0].freq_hz = f32::NAN;
17830 assert!(
17831 Project::from_parts(
17832 sources.clone(),
17833 two(eqd(0), Vec::new()),
17834 vec![nan],
17835 Vec::new(),
17836 Vec::new(),
17837 )
17838 .is_err()
17839 );
17840 let loaded = Project::from_parts(
17841 sources.clone(),
17842 two(eqd(0), Vec::new()),
17843 vec![band_at(1)],
17844 Vec::new(),
17845 Vec::new(),
17846 )
17847 .expect("an eq the table holds");
17848 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
17849
17850 // The same two refusals for a colour, at the same door.
17851 let graded = |i: u16| {
17852 vec![Clip {
17853 fade_in: 0,
17854 fade_out: 0,
17855 transition_out: 0,
17856 transition_kind: Default::default(),
17857 visualizer: 0,
17858 viz_paint: 0,
17859 gain_db: 0.0,
17860 color: Some(i),
17861 fit: FitPolicy::default(),
17862 speed: Speed::NORMAL,
17863 ..video[0].clone()
17864 }]
17865 };
17866 assert!(
17867 Project::from_parts(
17868 sources.clone(),
17869 two(graded(0), Vec::new()),
17870 Vec::new(),
17871 Vec::new(),
17872 Vec::new(),
17873 )
17874 .is_err(),
17875 "a colour index no entry answers"
17876 );
17877 assert!(
17878 Project::from_parts(
17879 sources.clone(),
17880 two(graded(0), Vec::new()),
17881 Vec::new(),
17882 vec![ColorParams {
17883 tint: f32::NAN,
17884 ..grade_at(1)
17885 }],
17886 Vec::new(),
17887 )
17888 .is_err(),
17889 "a value the file format could not have written"
17890 );
17891 let loaded = Project::from_parts(
17892 sources.clone(),
17893 two(graded(0), Vec::new()),
17894 Vec::new(),
17895 vec![grade_at(1)],
17896 Vec::new(),
17897 )
17898 .expect("a colour the table holds");
17899 assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
17900
17901 // Group ids survive a load, and the next split gets a fresh one.
17902 let mut p =
17903 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("valid parts");
17904 assert!(p.split(4));
17905 assert!(p.clips().iter().all(|c| c.link.is_some()));
17906 }
17907
17908 /// The grouping rules, at the untrusted door and after every edit that can
17909 /// touch a link. A link id is at most one placement per lane -- a clip or a
17910 /// caption, whichever carries it -- and no sequence of edits may produce
17911 /// otherwise, because what an edit produces is what a save writes and a load
17912 /// reads.
17913 ///
17914 /// Amended for the offset-preserving group: the members keep their own
17915 /// spans, so two placements of one id covering different frames is *legal*
17916 /// -- it is what a hand-built group is -- and the only refusal left is the
17917 /// doubled id inside one lane.
17918 #[test]
17919 fn a_link_id_is_never_two_clips_of_one_lane() {
17920 let sources = vec![Source::new(FILE, 0)];
17921 let linked = |start, in_frame, out_frame, link| Clip {
17922 speed_keys: Vec::new(),
17923 reversed: false,
17924 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
17925 angle: Default::default(),
17926 fade_in: 0,
17927 fade_out: 0,
17928 transition_out: 0,
17929 transition_kind: Default::default(),
17930 visualizer: 0,
17931 viz_paint: 0,
17932 gain_db: 0.0,
17933 gain_keys: Vec::new(),
17934 pan: 0,
17935 pitch: 0,
17936 transform_keys: Vec::new(),
17937 opacity_keys: Vec::new(),
17938 color_keys: Vec::new(),
17939 effects: Vec::new(),
17940 start,
17941 in_frame,
17942 out_frame,
17943 source: 0,
17944 link: Some(link),
17945 eq: None,
17946 color: None,
17947 transform: None,
17948 fit: FitPolicy::default(),
17949 speed: Speed::NORMAL,
17950 };
17951
17952 // The door: a doubled id inside one lane, refused by name.
17953 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
17954 Project::from_parts(
17955 sources.clone(),
17956 two(video, audio),
17957 Vec::new(),
17958 Vec::new(),
17959 Vec::new(),
17960 )
17961 .expect_err("refused")
17962 .to_string()
17963 };
17964 assert!(
17965 err(vec![linked(0, 0, 3, 7), linked(3, 3, 5, 7)], Vec::new())
17966 .contains("link 7 names two clips in the V1 lane"),
17967 "a duplicate id inside one lane is refused by name"
17968 );
17969 // ...and the same doubling on a subtitle lane, in its own words: a
17970 // caption is the other placement an id may name.
17971 let caption = |start: u32, frames: u32, link| SubClip {
17972 start,
17973 frames,
17974 track: 0,
17975 in_us: 0,
17976 out_us: i64::from(frames) * 1_000_000,
17977 link: Some(link),
17978 };
17979 let subs = LaneData {
17980 clips: Vec::new(),
17981 subs: vec![caption(0, 3, 7), caption(4, 3, 7)],
17982 ..LaneData::new(LaneKind::Subtitle, Vec::new())
17983 };
17984 assert_eq!(
17985 links_are_consistent(&[subs]).unwrap_err().to_string(),
17986 "link 7 names two captions in the S1 lane"
17987 );
17988 // A pair covering *different* frames is legal now: the members of a
17989 // hand-built group keep their own spans, and what binds them is the id.
17990 let apart = Project::from_parts(
17991 sources.clone(),
17992 two(vec![linked(0, 0, 5, 2)], vec![linked(0, 0, 3, 2)]),
17993 Vec::new(),
17994 Vec::new(),
17995 Vec::new(),
17996 );
17997 assert!(apart.is_ok(), "offsets within one group load: {apart:?}");
17998 // A one-sided link is *not* an error: it is what a lift leaves behind.
17999 let mut p = Project::single(FILE, 9);
18000 assert!(p.lift(Lane::A1, 0));
18001 let (sources, lanes, eq, color, _transform) = p.clone().without_orphan_sources();
18002 assert!(
18003 Project::from_parts(sources, lanes, eq, color, Vec::new()).is_ok(),
18004 "a lifted lane's project has to load again"
18005 );
18006
18007 // The edits: nothing below may break either rule.
18008 let consistent = |p: &Project, what: &str| {
18009 assert!(
18010 links_are_consistent(&p.lanes).is_ok(),
18011 "{what}: {:?}",
18012 p.lanes
18013 );
18014 };
18015 let mut p = three();
18016 let copied = p.clips()[0].clone();
18017 assert!(
18018 copied.link.is_some(),
18019 "the clipboard clip carries its group"
18020 );
18021 assert!(p.lift(Lane::V1, 0));
18022 assert!(p.place(Lane::V1, 0, copied.clone()));
18023 assert!(
18024 p.place(Lane::V1, 20, copied.clone()),
18025 "and again, further out"
18026 );
18027 assert_eq!(
18028 p.clips().iter().filter(|c| c.link == copied.link).count(),
18029 0,
18030 "a placement belongs to no group, so it cannot duplicate one"
18031 );
18032 consistent(&p, "lift + place twice");
18033 assert!(
18034 p.place(Lane::A1, 4, copied.clone()),
18035 "over a linked clip's middle"
18036 );
18037 consistent(&p, "place through a grouped clip");
18038 assert!(
18039 p.paste(6, copied.clone()),
18040 "a rippling paste through another"
18041 );
18042 consistent(&p, "paste");
18043 assert!(p.split(2));
18044 consistent(&p, "split");
18045 assert!(p.ripple_delete(1, 3));
18046 consistent(&p, "ripple_delete");
18047 assert!(p.undo());
18048 consistent(&p, "undo");
18049 }
18050
18051 /// What an edit produces is what a save writes, so *every* state the public
18052 /// API can reach has to load again. The two the verifier panel found where
18053 /// it did not: a split and a regroup handed one group id to two clips that
18054 /// were not the same span, because the lanes had been edited apart.
18055 #[test]
18056 fn every_reachable_state_reloads() {
18057 let mut p = Project::single(FILE, 150);
18058 assert!(p.place(Lane::A1, 3, clip(0, 0, 50, 0)));
18059 assert!(p.split(10), "the lanes are cut apart at 10");
18060 reloads(&p, "place on one lane, then split");
18061
18062 let mut p = Project::single(FILE, 150);
18063 assert!(p.split(30));
18064 assert!(p.lift(Lane::V1, 0), "the picture goes, the sound stays");
18065 assert!(p.regroup(30), "only the audio lane can rejoin");
18066 assert!(p.split(60));
18067 reloads(&p, "lift, regroup one lane, split");
18068
18069 // Two audio streams of one file, both placed: two source entries with
18070 // one path between them, which is the state a stream picked out of the
18071 // library reaches -- and the state a save has to write and read back.
18072 let mut p = Project::single(FILE, 150);
18073 let second = p.import(FILE, 1);
18074 assert_eq!(second, 1, "the same file on another stream is a new source");
18075 assert!(p.append_clip(second, 150));
18076 assert!(p.split(200));
18077 reloads(
18078 &p,
18079 "a second audio stream of the same file, placed and split",
18080 );
18081 let (sources, ..) = p.without_orphan_sources();
18082 assert_eq!(
18083 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
18084 [0, 1],
18085 "both entries survive the orphan prune: both are played"
18086 );
18087 }
18088
18089 /// The pairing the whole model rests on: [`Speed::source_at`] (floor) is
18090 /// what an export encodes at a timeline frame, [`Speed::timeline_at`] (ceil)
18091 /// is the stamp playback puts on a decoded source frame -- and the *last*
18092 /// source frame the pump is still holding at a timeline frame has to be
18093 /// exactly the one the export encoded there, at every rate. Anything else is
18094 /// A/V drift that grows with the clip, and no test of either side alone
18095 /// would see it.
18096 ///
18097 /// (Grafted from the rival build of this feature, whose floor/ceil pairing
18098 /// is a better answer than the floor/floor this had: floor/floor put the
18099 /// preview a whole held frame off the export at slow rates.)
18100 #[test]
18101 fn speed_maps_both_ways() {
18102 for permille in (250..=4000).step_by(1) {
18103 let speed = Speed::from_permille(permille);
18104 assert_eq!(speed.permille(), permille, "no clamping in range");
18105 for d in 0..200u32 {
18106 let want = speed.source_at(d);
18107 // What the pump shows at `d` is the last frame whose stamp has
18108 // come due -- and it is `want`, the frame the export encodes
18109 // there. Slowed, that is the frame it is still holding; sped up,
18110 // it is the newest of the several that arrived.
18111 let held = (0..=want + 8).rev().find(|&s| speed.timeline_at(s) <= d);
18112 assert_eq!(held, Some(want), "{speed} at timeline frame {d}");
18113 }
18114 for n in 1..300u32 {
18115 // A footprint is never zero: a clip occupying no timeline frame
18116 // is a placement the lane invariants cannot hold.
18117 let frames = speed.frames(n);
18118 assert!(frames >= 1, "{speed} of {n} frames");
18119 // ...and its last timeline frame never reads past the clip.
18120 assert!(
18121 speed.source_at(frames - 1) < n,
18122 "{speed}: the last timeline frame of {n} reads past the clip"
18123 );
18124 // The trim inverse never overshoots the room it was given, and
18125 // answers for every room a footprint can be.
18126 let fit = speed.fit(frames).expect("a clip fits its own footprint");
18127 assert!(speed.frames(fit) <= frames, "{speed}: fit({frames}) grew");
18128 // A room narrower than one source frame's own footprint holds
18129 // nothing, and says so rather than rounding something into it.
18130 assert_eq!(speed.fit(speed.room(1) - 1), None, "{speed}: too narrow");
18131 assert_eq!(speed.room(0), 0, "{speed}: no head is no room");
18132 }
18133 }
18134 // Real time is the identity map, byte for byte.
18135 for d in 0..1000 {
18136 assert_eq!(Speed::NORMAL.source_at(d), d);
18137 assert_eq!(Speed::NORMAL.timeline_at(d), d);
18138 assert_eq!(Speed::NORMAL.frames(d.max(1)), d.max(1));
18139 assert_eq!(Speed::NORMAL.fit(d.max(1)), Some(d.max(1)));
18140 assert_eq!(Speed::NORMAL.repeats(d, d + 1), 1);
18141 }
18142 // The one door: no zero, no reverse, nothing past the ends.
18143 assert_eq!(Speed::from_permille(0), Speed::MIN);
18144 assert_eq!(Speed::from_permille(249), Speed::MIN);
18145 assert_eq!(Speed::from_permille(4001), Speed::MAX);
18146 assert_eq!(Speed::from_permille(1000), Speed::NORMAL);
18147 assert_eq!(Speed::NORMAL.to_string(), "1.00x");
18148 assert_eq!(Speed::from_permille(2500).to_string(), "2.50x");
18149 }
18150
18151 /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an
18152 /// export encodes at a timeline frame is the one playback is holding there,
18153 /// a file is as long in timeline frames as the seconds it lasts, and the two
18154 /// compose so a speeded clip at another rate is exactly both.
18155 #[test]
18156 fn rate_composes_with_speed() {
18157 // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976,
18158 // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be
18159 // the identity map or a single-rate project would move.
18160 for (source_fps, timeline_fps) in [
18161 (24000. / 1001., 30.),
18162 (30., 24000. / 1001.),
18163 (60., 30.),
18164 (25., 30.),
18165 (30., 30.),
18166 ] {
18167 let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate");
18168 for n in 0..2000u32 {
18169 let source = rate.source_at(n);
18170 // The stamp is the *first* timeline-rate frame that shows it, so
18171 // the picture on screen at `n` is the picture encoded at `n`.
18172 let held = (0..=source + 4).rev().find(|&s| rate.timeline_at(s) <= n);
18173 assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}");
18174 }
18175 // A file of `count` frames is `timeline_at(count)` frames long here,
18176 // and its last one still reads a frame the file has.
18177 for count in 1..500u32 {
18178 let frames = rate.timeline_at(count);
18179 assert!(frames >= 1, "a file is never zero frames long");
18180 assert!(
18181 rate.source_at(frames - 1) < count,
18182 "{source_fps} on {timeline_fps}: {count} frames reads past the file"
18183 );
18184 }
18185 // No drift: the mapping is one exact division of the *rate itself*,
18186 // not an accumulation and not a rounded rate, so an hour in is as
18187 // true as the first second. (Held to the real ratio of the two rates
18188 // the caller asked for -- `as_f64` would be true of a wrong rate.)
18189 for n in [1u32, 100, 10_000, 500_000, 3_000_000] {
18190 let want = f64::from(n) * source_fps / timeline_fps;
18191 assert!(
18192 (f64::from(rate.source_at(n)) - want).abs() < 1.,
18193 "{source_fps} on {timeline_fps}: frame {n} drifted"
18194 );
18195 }
18196 }
18197 // The timeline's own rate is the identity, whichever way it is written.
18198 assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time());
18199 assert!(
18200 Rate::from_fps(30.0004, 30.)
18201 .expect("30.0004 over 30")
18202 .is_real_time(),
18203 "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001"
18204 );
18205 // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the
18206 // one thing `matches_timeline` refuses a file for now that the rate gate
18207 // is gone.
18208 assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all");
18209 assert!(Rate::from_fps(30., f64::NAN).is_err());
18210 for n in 0..1000 {
18211 assert_eq!(Rate::REAL_TIME.source_at(n), n);
18212 assert_eq!(Rate::REAL_TIME.timeline_at(n), n);
18213 }
18214 // ...and the composition, in the order the decoder's door applies it:
18215 // the speed picks the clip's (timeline-rate) frame, the rate picks the
18216 // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two
18217 // timeline frames per frame shown, each of them exactly 800/1001 of a
18218 // file frame.
18219 let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30");
18220 let speed = Speed::from_permille(2000);
18221 for d in 0..100u32 {
18222 assert_eq!(
18223 rate.source_at(speed.source_at(d)),
18224 (u64::from(d) * 2 * 800 / 1001) as u32,
18225 "2x of a 23.976 fps file at timeline frame {d}"
18226 );
18227 }
18228 }
18229
18230 /// The mapping a speed changes, and the one it does not: a 2x clip reads two
18231 /// source frames per timeline frame and still starts at its own in-point,
18232 /// and a half-speed one shows every source frame twice.
18233 #[test]
18234 fn a_rate_maps_timeline_frames_onto_source_frames() {
18235 let mut p = Project::single(FILE, 40);
18236 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18237 .expect("room enough");
18238 assert_eq!(p.timeline_frames(), 20, "40 source frames at 2x");
18239 assert_eq!(
18240 p.map(Lane::V1, 0),
18241 Some((0, 0)),
18242 "and it starts where it did"
18243 );
18244 assert_eq!(p.map(Lane::V1, 1), Some((0, 2)));
18245 assert_eq!(p.map(Lane::V1, 19), Some((0, 38)));
18246 assert_eq!(p.map(Lane::V1, 20), None, "and ends where the clip does");
18247 // The span a decoder is handed: as many source frames as it will read,
18248 // which is the last shown frame's own and not one more -- timeline frame
18249 // 19 shows source frame 38, so 39 frames are read and the 40th is a
18250 // picture nothing would display.
18251 let span = p.span_at(Lane::V1, 0).expect("a span");
18252 assert_eq!((span.len, span.source_len()), (20, 39));
18253 assert_eq!(span.timeline_at(38), 19, "and it is stamped where it shows");
18254 // ...and the same clip the other way round.
18255 let mut p = Project::single(FILE, 40);
18256 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18257 .expect("room enough");
18258 assert_eq!(p.timeline_frames(), 80);
18259 assert_eq!(p.map(Lane::V1, 0), Some((0, 0)));
18260 assert_eq!(p.map(Lane::V1, 1), Some((0, 0)), "each frame shows twice");
18261 assert_eq!(p.map(Lane::V1, 2), Some((0, 1)));
18262 assert_eq!(
18263 p.map(Lane::V1, 79),
18264 Some((0, 39)),
18265 "and the last timeline frame is still inside the source range"
18266 );
18267 }
18268
18269 /// A trim of a speeded clip is still a trim of its *source*, and the edge
18270 /// still stops at the wall: the room a rate leaves is measured in timeline
18271 /// frames and the range it commits in source ones.
18272 #[test]
18273 fn trimming_a_speeded_clip_stays_inside_its_room() {
18274 let mut p = Project::single(FILE, 40);
18275 p.set_speed(Lane::V1, 0, Speed::from_permille(2000))
18276 .expect("room enough");
18277 // A second clip butted against the first, so the wall is a real one.
18278 assert!(p.place(Lane::V1, 20, clip(0, 0, 10, 0)));
18279 let room = p.trim_room(Lane::V1, 0, Edge::End, &[40]).expect("a clip");
18280 assert_eq!(room, (1, 20), "out to the neighbour and no further");
18281 assert!(
18282 !p.trim(Lane::V1, 0, Edge::End, 30, &[40]),
18283 "clamped to the wall, which is where the edge already is"
18284 );
18285 let c = p.clips()[0].clone();
18286 assert_eq!(c.end(), 20, "so nothing moved");
18287 assert_eq!(c.out_frame, 40, "and it is still the whole source range");
18288 // ...and in: half the timeline frames is half the source range.
18289 assert!(p.trim(Lane::V1, 0, Edge::End, 10, &[40]));
18290 let c = p.clips()[0].clone();
18291 assert_eq!((c.in_frame, c.out_frame), (0, 20), "in source frames");
18292 assert_eq!(c.end(), 10, "and ten timeline frames of them");
18293 assert!(sorted_disjoint(p.clips()));
18294 }
18295
18296 /// The frames a rate cannot address: at half speed each source frame is on
18297 /// screen twice, and the cut between the two showings is not a cut in the
18298 /// file. Refused, so the two halves always add up to the clip that was cut.
18299 #[test]
18300 fn a_slow_clip_cuts_only_where_its_source_has_a_frame() {
18301 let mut p = Project::single(FILE, 10);
18302 p.set_speed(Lane::V1, 0, Speed::from_permille(500))
18303 .expect("room enough");
18304 assert_eq!(p.timeline_frames(), 20);
18305 assert!(
18306 !p.split(3),
18307 "an odd frame is between two showings of one frame"
18308 );
18309 assert_eq!(p.clips().len(), 1, "and nothing was cut");
18310 assert!(p.split(4), "an even one is a frame boundary");
18311 let halves = p.clips().to_vec();
18312 assert_eq!(
18313 (halves[0].end(), halves[1].start, halves[1].end()),
18314 (4, 4, 20),
18315 "the halves meet, and still end where the clip did"
18316 );
18317 assert_eq!(halves[0].out_frame, halves[1].in_frame, "in source frames");
18318 assert!(p.regroup(4), "and the inverse puts it back");
18319 assert_eq!(p.clips().len(), 1);
18320 }
18321
18322 /// The same claim, swept: random op sequences off the public surface, the
18323 /// project reloaded after every one of them. A failure prints its seed, and
18324 /// the seed replays the whole sequence.
18325 #[test]
18326 fn random_edit_sequences_reload() {
18327 // Two thousand, not two hundred: the overlap a hole punched into a slow
18328 // clip at a frame its rate cannot address leaves behind sat in ~0.7% of
18329 // sequences, and a 200-seed sweep walked straight past it (it took a
18330 // judge's 2000-seed run to surface `place` at all). A sweep this cheap
18331 // has no business being the narrow one.
18332 for seed in 0..2000u64 {
18333 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
18334 let mut next = move |n: u32| {
18335 // xorshift64*: no dependency, and the seed replays it exactly.
18336 rng ^= rng << 13;
18337 rng ^= rng >> 7;
18338 rng ^= rng << 17;
18339 (rng >> 33) as u32 % n
18340 };
18341 let mut p = Project::single(FILE, 40);
18342 for step in 0..24 {
18343 let frame = next(44);
18344 // A clipboard copy carries the group id of the take it came from
18345 // -- the input that made a placement duplicate an id -- and, one
18346 // time in three, a rate of its own: a *speeded clip placed over
18347 // a speeded clip* is the shape whose remainders have to be run
18348 // through `Speed::fit`, and it is not a shape the lanes hand out
18349 // on their own often enough to be sure of.
18350 let mut copied = p
18351 .lane(if next(2) == 0 { Lane::V1 } else { Lane::A1 })
18352 .get(next(4) as usize)
18353 .cloned()
18354 .unwrap_or_else(|| clip(0, 0, 5, 0));
18355 if next(3) == 0 {
18356 copied.speed = Speed::from_permille(250 + next(16) as u16 * 250);
18357 }
18358 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
18359 let idx = next(4) as usize;
18360 let _ = match next(16) {
18361 // A clip dragged along its own lane to wherever the pointer
18362 // let it go: the op that moves a placement without changing
18363 // what it plays, so what it may not do is land on top of the
18364 // neighbour it was dragged at.
18365 15 => p.move_clip(lane, idx, lane, frame),
18366 // ...and a second `place`, so a punch lands inside a clip
18367 // far more often than one op in fourteen would put it there.
18368 14 => p.place(lane, frame, copied.clone()),
18369 0 => p.split(frame),
18370 1 => p.regroup(frame),
18371 2 => p.lift(lane, idx),
18372 3 => p.place(lane, frame, copied.clone()),
18373 4 => p.paste(frame, copied.clone()),
18374 5 => p.ripple_delete(frame, next(9)),
18375 6 => p.delete(idx),
18376 7 => p.undo(),
18377 // An equalizer put on and taken off in the mix: what a clip
18378 // carries has to reload with it, and the entries an undo
18379 // orphans must not come back out of the prune.
18380 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
18381 9 => p.set_eq(lane, idx, None),
18382 // ...and a colour grade in the same mix, for the same
18383 // reason: it rides on the clip and its orphans must go.
18384 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
18385 11 => p.set_color(lane, idx, None),
18386 // ...and a rate in with them, which is the one of the three
18387 // that moves *placements*: a clip that grew has to be
18388 // refused rather than overlap, and one that shrank leaves a
18389 // lane that still loads. Both are what `reloads` asks.
18390 12 => p
18391 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
18392 .is_ok(),
18393 _ => p.append_clip(0, 1 + next(9)),
18394 };
18395 reloads(&p, &format!("seed {seed}, step {step}"));
18396 }
18397 }
18398 }
18399
18400 /// The save/load round trip a project must survive: the parts a save writes,
18401 /// handed back to the constructor a load goes through -- every lane of them,
18402 /// and the reloaded timeline has to be the same lanes in the same order.
18403 fn reloads(p: &Project, what: &str) {
18404 let (sources, lanes, eq, color, transform) = p.clone().without_orphan_sources();
18405 match Project::from_parts(sources, lanes, eq, color, transform) {
18406 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
18407 Ok(back) => {
18408 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
18409 // Placements, not whole clips: an orphan prune renumbers the
18410 // sources a clip names, which is the point of it.
18411 let spans = |p: &Project| -> Vec<Vec<(u32, u32)>> {
18412 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
18413 };
18414 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
18415 // The prune renumbers the eq table too, so what has to survive
18416 // is the settings themselves, clip by clip.
18417 let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
18418 p.lanes()
18419 .into_iter()
18420 .map(|l| {
18421 (0..p.lane(l).len())
18422 .map(|i| p.eq_of(l, i).cloned())
18423 .collect()
18424 })
18425 .collect()
18426 };
18427 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
18428 // The colour table renumbers in the same prune, so the same
18429 // claim: the params a clip names, not the index it names them by.
18430 let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
18431 p.lanes()
18432 .into_iter()
18433 .map(|l| {
18434 (0..p.lane(l).len())
18435 .map(|i| p.color_of(l, i).copied())
18436 .collect()
18437 })
18438 .collect()
18439 };
18440 assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
18441 // ...and the transform table, by the same claim again.
18442 let transforms = |p: &Project| -> Vec<Vec<Option<TransformParams>>> {
18443 p.lanes()
18444 .into_iter()
18445 .map(|l| {
18446 (0..p.lane(l).len())
18447 .map(|i| p.transform_of(l, i).copied())
18448 .collect()
18449 })
18450 .collect()
18451 };
18452 assert_eq!(
18453 transforms(&back),
18454 transforms(p),
18455 "{what}: the transforms changed"
18456 );
18457 }
18458 }
18459 }
18460
18461 /// The two invariants [`Project::from_parts`] checks that are about *lanes*
18462 /// -- each one sorted and disjoint, and one span per group id -- asserted
18463 /// directly, where the point is the invariant rather than the round trip.
18464 fn invariants_hold(p: &Project, what: &str) {
18465 for lane in p.lanes() {
18466 assert!(
18467 sorted_disjoint(p.lane(lane)),
18468 "{what}: {} is out of order or overlaps itself: {:?}",
18469 lane.label(),
18470 p.lane(lane)
18471 );
18472 }
18473 if let Err(e) = links_are_consistent(&p.lanes) {
18474 panic!("{what}: {e}\n{:?}", p.lanes);
18475 }
18476 }
18477
18478 /// A lane is a lane: `V2` is added, counted, reached by `(kind, ord)`, and
18479 /// edited without any other lane hearing about it. A handle naming a lane
18480 /// that is not there reads as empty and refuses to mutate.
18481 #[test]
18482 fn a_third_lane_is_a_peer() {
18483 let mut p = three();
18484 assert_eq!(p.lane_count(LaneKind::Video), 1);
18485 assert_eq!(p.lane_count(LaneKind::Audio), 1);
18486 let v2 = p.add_lane(LaneKind::Video);
18487 assert_eq!(v2, Lane::new(LaneKind::Video, 1));
18488 assert_eq!(v2.label(), "V2");
18489 assert_eq!(p.lane_count(LaneKind::Video), 2);
18490 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18491 assert!(p.lane(v2).is_empty(), "a new lane holds nothing");
18492
18493 // A handle for a lane that is not there: empty, and no mutation takes.
18494 let v3 = Lane::new(LaneKind::Video, 2);
18495 assert!(p.lane(v3).is_empty());
18496 assert!(!p.place(v3, 0, clip(0, 0, 3, 0)), "no lane, no placement");
18497 assert!(!p.lift(v3, 0));
18498 assert_eq!(p.lane_count(LaneKind::Video), 2, "and none was made");
18499
18500 // Placing on V2 moves nothing else, and the lane can outrun the rest.
18501 let before = shape(&p);
18502 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
18503 assert_eq!(shape(&p)[0], before[0], "V1 never moved");
18504 assert_eq!(shape(&p)[1], before[1], "A1 never moved");
18505 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18506 assert_eq!(
18507 p.timeline_frames(),
18508 16,
18509 "the last lane to end sets the length"
18510 );
18511 assert_eq!(p.map(v2, 5), Some((0, 21)));
18512 assert_eq!(p.map(v2, 3), None, "V2's own leading gap");
18513 assert_eq!(
18514 p.span_at(v2, 0),
18515 Some(Span {
18516 reverse: false,
18517 ramp: None,
18518 start: 0,
18519 len: 4,
18520 from: None,
18521 speed: Speed::NORMAL,
18522 pitch: 0,
18523 })
18524 );
18525 // Every lane still covers the whole timeline, gaps included.
18526 for l in p.lanes() {
18527 let spans = p.spans_from(l, 0);
18528 assert_eq!(
18529 spans.iter().map(|s| s.len).sum::<u32>(),
18530 16,
18531 "{}",
18532 l.label()
18533 );
18534 }
18535 // ...and playback still reads V1 and A1, whatever else is there.
18536 assert_eq!(p.clips(), p.lane(Lane::V1));
18537 assert_eq!(p.map_timeline(4), p.map(Lane::V1, 4));
18538 let segments = p.segments_from(0, FPS);
18539 assert_eq!(segments[..3], three().segments_from(0, FPS)[..]);
18540 assert_eq!(
18541 segments[3],
18542 (None, 0.0, 7.0 / FPS),
18543 "A1 keeps the clock counting over the picture V2 added"
18544 );
18545 invariants_hold(&p, "place on V2");
18546
18547 // A lift is that lane's business too, and the lane list undoes.
18548 assert!(p.lift(v2, 0));
18549 assert!(p.lane(v2).is_empty());
18550 assert_eq!(p.timeline_frames(), 9, "V2 no longer runs the longest");
18551 assert!(p.undo());
18552 assert_eq!(p.lane_spans(v2), vec![(4, 12)]);
18553 assert!(p.undo());
18554 assert!(p.lane(v2).is_empty(), "the placement came off V2");
18555 assert!(p.undo(), "and one more step takes the lane itself back");
18556 assert_eq!(p.lane_count(LaneKind::Video), 1);
18557 assert_eq!(shape(&p), shape(&three()));
18558 }
18559
18560 /// The add taken back: an empty lane comes off, a lane holding clips never
18561 /// does (and says which clips), the last lane of a kind never does, the
18562 /// lanes below the one that went move up an `ord`, and one undo puts it
18563 /// back where it stood.
18564 #[test]
18565 fn an_empty_lane_comes_off_again() {
18566 let mut p = three();
18567 let v2 = p.add_lane(LaneKind::Video);
18568 let v3 = p.add_lane(LaneKind::Video);
18569 assert!(p.place(v3, 0, clip(0, 0, 3, 0)));
18570 let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
18571 let history = p.history.len();
18572
18573 // The last lane of its kind stays: `V1`/`A1` are where an import and a
18574 // paste land, and a project missing one would swallow half of a file
18575 // dropped on it.
18576 assert!(why(p.remove_lane(Lane::A1)).contains("only audio track"));
18577 assert_eq!(
18578 why(p.remove_lane(Lane::new(LaneKind::Video, 9))),
18579 "there is no V10 to remove"
18580 );
18581
18582 // A lane with clips on it refuses and names them: a track removal never
18583 // deletes a take.
18584 let refusal = why(p.remove_lane(v3));
18585 assert!(refusal.contains("V3 still holds"), "{refusal}");
18586 assert!(refusal.contains(FILE), "{refusal}");
18587 assert!(refusal.contains("at frame 0"), "{refusal}");
18588 assert_eq!(p.lane_spans(v3), vec![(0, 3)], "the clip is still there");
18589 assert_eq!(p.history.len(), history, "a refusal snapshots nothing");
18590
18591 // The empty one in the middle goes, and `V3` becomes `V2` -- clip and
18592 // all.
18593 p.remove_lane(v2).expect("V2 is empty");
18594 assert_eq!(p.lane_count(LaneKind::Video), 2);
18595 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1, v2]);
18596 assert_eq!(p.lane_spans(v2), vec![(0, 3)], "the lane below moved up");
18597 assert_eq!(p.history.len(), history + 1, "one snapshot per removal");
18598 invariants_hold(&p, "remove V2");
18599
18600 // ...and one stroke puts the empty lane back above it.
18601 assert!(p.undo());
18602 assert_eq!(p.lane_count(LaneKind::Video), 3);
18603 assert!(p.lane(v2).is_empty(), "back where it stood, still empty");
18604 assert_eq!(p.lane_spans(v3), vec![(0, 3)]);
18605 }
18606
18607 /// A duck is the audio lane's own setting: it names another audio lane as
18608 /// its key, refuses itself and video lanes as a key or a target, is one undo
18609 /// step, and reaches the mix only for a key that is in the mix.
18610 #[test]
18611 fn a_duck_keys_off_another_audio_lane_and_is_one_undo_step() {
18612 use crate::duck::Duck;
18613 let mut p = Project::single(FILE, 9);
18614 let a2 = p.add_lane(LaneKind::Audio);
18615 let duck = Duck::new(0, -12.0);
18616 let history = p.history.len();
18617 assert!(
18618 !p.set_lane_duck(Lane::A1, Some(duck)),
18619 "a lane is not its own key"
18620 );
18621 assert!(
18622 !p.set_lane_duck(Lane::V1, Some(duck)),
18623 "a video lane does not duck"
18624 );
18625 assert!(
18626 !p.set_lane_duck(a2, Some(Duck::new(5, -12.0))),
18627 "no such key"
18628 );
18629 assert!(!p.set_lane_duck(
18630 a2,
18631 Some(Duck {
18632 depth_db: f32::NAN,
18633 ..duck
18634 })
18635 ));
18636 assert_eq!(p.history.len(), history, "a refusal writes no history");
18637 assert!(p.set_lane_duck(a2, Some(duck)));
18638 assert_eq!(p.lane_duck(a2), Some(duck));
18639 assert_eq!(p.history.len(), history + 1, "one undo step");
18640 // A2 is empty, so it is not in the mix and cannot be a key in it.
18641 assert_eq!(p.audio_ducks(), vec![Vec::<Duck>::new()], "one mixed lane, unducked");
18642 assert_eq!(p.lane_ducks()[2], vec![duck], "saved by its own lane");
18643 assert!(p.undo());
18644 assert_eq!(p.lane_duck(a2), None, "undone");
18645 }
18646
18647 /// A lane is ducked under several keys at once, each set on its own: a duck
18648 /// under a key the lane already has replaces that one, a clear takes one key
18649 /// away, and the mix reads them all in the order they were set.
18650 #[test]
18651 fn a_lane_ducks_under_several_keys_and_each_can_be_cleared() {
18652 use crate::duck::Duck;
18653 let mut p = Project::single(FILE, 9);
18654 let a2 = p.add_lane(LaneKind::Audio);
18655 let a3 = p.add_lane(LaneKind::Audio);
18656 // A1 and A2 are the keys that A3 is ducked under.
18657 assert!(p.set_lane_duck(a3, Some(Duck::new(0, -12.0))), "A3 under A1");
18658 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -6.0))), "A3 under A2 too");
18659 assert_eq!(p.lane_duck_list(a3).len(), 2, "both kept");
18660 assert_eq!(p.lane_duck(a3), Some(Duck::new(0, -12.0)), "the first set");
18661 // The same key again replaces its duck and keeps the other.
18662 assert!(p.set_lane_duck(a3, Some(Duck::new(1, -20.0))));
18663 let list = p.lane_duck_list(a3);
18664 assert_eq!(list.len(), 2);
18665 assert_eq!(list[1].depth_db, -20.0, "the A2 key's depth changed in place");
18666 assert_eq!(list[0].depth_db, -12.0, "the A1 key untouched");
18667 // A key that is the lane itself is still refused, whatever else it holds.
18668 assert!(!p.set_lane_duck(a3, Some(Duck::new(2, -6.0))));
18669 // Clearing one key leaves the other; clearing a key it lacks is a refusal.
18670 assert!(p.clear_lane_duck(a3, 0));
18671 assert_eq!(p.lane_duck_list(a3), vec![Duck { depth_db: -20.0, ..Duck::new(1, -20.0) }]);
18672 assert!(!p.clear_lane_duck(a3, 0), "no duck under A1 now");
18673 // None clears them all.
18674 assert!(p.set_lane_duck(a3, None));
18675 assert!(p.lane_duck_list(a3).is_empty());
18676 assert!(!p.set_lane_duck(a2, None), "nothing to clear is no change");
18677 }
18678
18679 /// Mute is the audio lane's switch and nothing else: it zeroes the lane's
18680 /// amplitude in the mix, leaves the lane's volume and clips where they were,
18681 /// is one undo step each way, and refuses the lanes it cannot mean anything
18682 /// for.
18683 #[test]
18684 fn a_muted_audio_lane_is_silent_in_the_mix_and_unmuting_restores_it() {
18685 let mut p = Project::single(FILE, 9);
18686 assert_eq!(p.audio_gains(), vec![1.0], "one lane at unity");
18687 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
18688 let loud = p.audio_gains()[0];
18689 let history = p.history.len();
18690
18691 assert!(p.set_lane_muted(Lane::A1, true));
18692 assert_eq!(p.audio_gains(), vec![0.0], "muted is silence in the sum");
18693 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "the volume is kept");
18694 assert_eq!(p.lane(Lane::A1).len(), 1, "and so are the clips");
18695 assert_eq!(p.history.len(), history + 1, "one undo step");
18696 assert!(
18697 !p.set_lane_muted(Lane::A1, true),
18698 "already muted is a no-op"
18699 );
18700 assert_eq!(p.history.len(), history + 1, "and no undo step for it");
18701
18702 assert!(p.set_lane_muted(Lane::A1, false));
18703 assert_eq!(p.audio_gains(), vec![loud], "unmuted is what it was");
18704
18705 // One undo per switch: the flag comes back through the lane list.
18706 assert!(p.undo());
18707 assert!(p.lane_muted(Lane::A1), "undo restores the muted flag");
18708 assert!(p.undo());
18709 assert!(!p.lane_muted(Lane::A1), "and the one before it");
18710
18711 assert!(
18712 !p.set_lane_muted(Lane::V1, true),
18713 "a video lane is never mixed"
18714 );
18715 assert!(
18716 !p.set_lane_hidden(Lane::A1, true),
18717 "an audio lane has no picture to hide"
18718 );
18719 assert!(
18720 !p.set_lane_hidden(Lane::new(LaneKind::Video, 7), true),
18721 "a lane that is not there"
18722 );
18723 }
18724
18725 /// Hiding a video lane takes it out of the composite: the picture is what
18726 /// the visible lanes cover, the lane under a hidden one shows through, and
18727 /// hiding the last covering lane leaves black. One undo step, and the flag
18728 /// is in the lane list, so a save and an undo both carry it.
18729 #[test]
18730 fn a_hidden_video_lane_leaves_the_composite() {
18731 let mut p = Project::single(FILE, 9);
18732 let v2 = p.add_lane(LaneKind::Video);
18733 assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
18734 assert_eq!(p.composite_clip_at(3), Some((v2, 0)), "V2 is on top");
18735
18736 let history = p.history.len();
18737 assert!(p.set_lane_hidden(v2, true));
18738 assert_eq!(p.history.len(), history + 1, "one undo step");
18739 assert!(p.lane_hidden(v2));
18740 assert_eq!(
18741 p.composite_clip_at(3),
18742 Some((Lane::V1, 0)),
18743 "V1 shows through"
18744 );
18745 assert_eq!(
18746 p.composite_spans_from(0).len(),
18747 1,
18748 "one span, from V1 alone"
18749 );
18750
18751 assert!(p.set_lane_hidden(Lane::V1, true));
18752 assert_eq!(p.composite_clip_at(3), None, "nothing visible, so black");
18753 assert!(p.undo());
18754 assert!(!p.lane_hidden(Lane::V1), "undo restores the flag");
18755 assert!(p.lane_hidden(v2));
18756 assert!(p.undo());
18757 assert!(!p.lane_hidden(v2));
18758 assert_eq!(p.composite_clip_at(3), Some((v2, 0)));
18759
18760 // Lock is state only: it refuses nothing in the engine.
18761 assert!(p.set_lane_locked(v2, true));
18762 assert!(p.lane_locked(v2));
18763 assert!(
18764 p.place(v2, 0, clip(0, 0, 3, 0)),
18765 "a locked lane still takes edits"
18766 );
18767 assert!(p.undo());
18768 assert!(p.lane_locked(v2), "undoing the edit leaves the lock");
18769 assert!(p.undo());
18770 assert!(!p.lane_locked(v2), "and the lock is one step of its own");
18771 }
18772
18773 /// A hidden subtitle lane has no cues, so the screen draws none and the
18774 /// export writes no track for it; showing it again brings them back.
18775 #[test]
18776 fn a_hidden_subtitle_lane_yields_no_cues_until_shown_again() {
18777 let track = SubtitleTrack {
18778 path: FILE.into(),
18779 track: None,
18780 language: "eng".into(),
18781 name: String::new(),
18782 label: "eng".into(),
18783 cues: vec![crate::subtitle::Cue {
18784 start_us: 8_000_000,
18785 end_us: 9_000_000,
18786 text: "a line".into(),
18787 image: None,
18788 words: Vec::new(),
18789 karaoke: Vec::new(),
18790 }],
18791 bitmap: false,
18792 refused: None,
18793 };
18794 let mut p = Project::single(FILE, 300).with_subtitles(vec![track]);
18795 let s1 = p.add_lane(LaneKind::Subtitle);
18796 p.place_sub(
18797 s1,
18798 0,
18799 SubClip {
18800 start: 0,
18801 frames: 300,
18802 track: 0,
18803 in_us: 0,
18804 out_us: 10_000_000,
18805 link: None,
18806 },
18807 )
18808 .expect("placed");
18809 assert_eq!(p.sub_lane_cues(s1, FPS).len(), 1, "shown, the cue is there");
18810
18811 assert!(p.set_lane_hidden(s1, true));
18812 assert!(
18813 p.sub_lane_cues(s1, FPS).is_empty(),
18814 "hidden, the lane gives no cues"
18815 );
18816
18817 assert!(p.set_lane_hidden(s1, false));
18818 assert_eq!(
18819 p.sub_lane_cues(s1, FPS).len(),
18820 1,
18821 "shown again, the cue comes back"
18822 );
18823 }
18824
18825 /// The switches live in the lane list, so a snapshot carries them with the
18826 /// rest; and [`Project::with_lane_flags`] puts them back on load with no undo
18827 /// step, as [`Project::with_mix`] does for the volumes.
18828 #[test]
18829 fn lane_switches_come_back_on_load_without_an_undo_step() {
18830 let mut p = Project::single(FILE, 9);
18831 assert!(p.set_lane_locked(Lane::V1, true));
18832 assert!(p.set_lane_hidden(Lane::V1, true));
18833 let flags = p.lane_flags();
18834 assert_eq!(
18835 flags[0],
18836 LaneFlags {
18837 hidden: true,
18838 muted: false,
18839 locked: true,
18840 pan: 0.0,
18841 }
18842 );
18843 let back = Project::from_parts(
18844 p.sources().to_vec(),
18845 p.lanes()
18846 .into_iter()
18847 .map(|l| (l.kind, p.lane(l).to_vec()))
18848 .collect(),
18849 Vec::new(),
18850 Vec::new(),
18851 Vec::new(),
18852 )
18853 .expect("the same lanes load")
18854 .with_lane_flags(&flags);
18855 assert!(back.lane_hidden(Lane::V1) && back.lane_locked(Lane::V1));
18856 assert!(!back.lane_muted(Lane::A1));
18857 let mut back = back;
18858 assert!(!back.undo(), "a loaded switch is not an undo step");
18859 }
18860
18861 /// A track dragged to another place in the stack: the whole lane travels --
18862 /// clips, gain and kind -- nothing is remapped, an audio track may sit above
18863 /// a video one, a lane that crosses one of its own kind swaps names with it
18864 /// (and swaps the composite with it), one undo puts the order back, and a
18865 /// save carries it.
18866 #[test]
18867 fn a_track_is_dragged_to_another_place_in_the_stack() {
18868 let mut p = three();
18869 assert!(p.set_lane_gain_db(Lane::A1, -6.0));
18870 let before = shape(&p);
18871 let history = p.history.len();
18872
18873 // A1 over V1: the screen is rearranged and nothing else is. Both keep
18874 // their names -- neither crossed a lane of its own kind -- so every
18875 // handle a front-end holds still names the track it named before.
18876 assert_eq!(p.move_lane(Lane::A1, 0), Some(Lane::A1));
18877 assert_eq!(p.lanes(), vec![Lane::A1, Lane::V1], "A1 is on top now");
18878 assert_eq!(
18879 shape(&p),
18880 vec![before[1].clone(), before[0].clone()],
18881 "each lane's clips travelled with it, and none was remapped"
18882 );
18883 assert_eq!(p.lane_gain_db(Lane::A1), -6.0, "so did its gain");
18884 assert_eq!(p.history.len(), history + 1, "one snapshot per move");
18885 invariants_hold(&p, "A1 over V1");
18886
18887 // Nothing moves for a lane that is not there, a slot that is not, or a
18888 // lane already standing in the one it was pointed at.
18889 assert_eq!(p.move_lane(Lane::new(LaneKind::Video, 9), 0), None);
18890 assert_eq!(p.move_lane(Lane::V1, 2), None, "there is no third slot");
18891 assert_eq!(p.move_lane(Lane::A1, 0), None, "already there");
18892 assert_eq!(p.history.len(), history + 1, "and none of those snapshot");
18893
18894 // ...and one stroke puts the order back.
18895 assert!(p.undo());
18896 assert_eq!(p.lanes(), vec![Lane::V1, Lane::A1]);
18897 assert_eq!(shape(&p), before);
18898
18899 // A second video lane over the first: display order *is* the stack, so
18900 // the last video lane covering a frame is the picture that shows.
18901 let v2 = p.add_lane(LaneKind::Video);
18902 assert!(p.place(v2, 0, clip(0, 0, 5, 0)));
18903 let over = shape(&p)[2].clone();
18904 assert_eq!(
18905 p.composite_span_at(0).map(|s| s.len),
18906 Some(5),
18907 "V2's five frames are what frame 0 shows"
18908 );
18909
18910 // V2 dragged to the top takes V1's slot -- and V1's name, a label being
18911 // a position among the lanes of its kind. The picture that wins changes
18912 // with it: the take that was covering is the covered one now.
18913 assert_eq!(p.move_lane(v2, 0), Some(Lane::V1), "a label is a position");
18914 assert_eq!(p.lanes(), vec![Lane::V1, v2, Lane::A1]);
18915 assert_eq!(
18916 shape(&p),
18917 vec![over.clone(), before[0].clone(), before[1].clone()],
18918 "V2's clips answer to V1 now, the old V1's to V2, and A1 kept its own"
18919 );
18920 assert_eq!(
18921 p.composite_span_at(0).map(|s| s.len),
18922 Some(3),
18923 "the lower video lane wins, and it is the old V1 now"
18924 );
18925 invariants_hold(&p, "V2 over V1");
18926
18927 // A save writes that order and a load takes it back.
18928 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
18929 assert_eq!(
18930 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
18931 [LaneKind::Video, LaneKind::Video, LaneKind::Audio]
18932 );
18933 let back =
18934 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("three lanes load");
18935 assert_eq!(back.lanes(), p.lanes());
18936 assert_eq!(shape(&back), shape(&p), "the same lane is still on top");
18937
18938 assert!(p.undo(), "and the stack goes back to how it stood");
18939 assert_eq!(shape(&p), vec![before[0].clone(), before[1].clone(), over]);
18940 }
18941
18942 /// The grouping rule across more than two lanes, under the offset model: a
18943 /// split *keeps* the group on the left halves and hands the right halves of
18944 /// that group one fresh id of their own -- a clip in no group comes out of
18945 /// the cut in none. So a take cut apart is two takes, one per side, and a
18946 /// lane that was never part of it stays out of both.
18947 #[test]
18948 fn a_split_keeps_the_left_group_and_shares_a_fresh_right_one() {
18949 let mut p = Project::single(FILE, 9);
18950 let take = p.clips()[0].link.expect("a fresh project is one take");
18951 let v2 = p.add_lane(LaneKind::Video);
18952 assert!(
18953 p.place(v2, 0, clip(0, 0, 9, 0)),
18954 "a placement joins no group"
18955 );
18956 assert!(p.split(4));
18957 let side = |p: &Project, i: usize| -> Vec<Option<u32>> {
18958 p.lanes().into_iter().map(|l| p.lane(l)[i].link).collect()
18959 };
18960 let (left, right) = (side(&p, 0), side(&p, 1));
18961 // The lanes in order are V1, A1, V2: the take's two keep its id on the
18962 // left, and the placed clip never had one for the cut to keep.
18963 assert_eq!(
18964 left,
18965 vec![Some(take), Some(take), None],
18966 "the left halves keep the take"
18967 );
18968 // ...and the right halves of that take are one fresh group.
18969 assert_eq!(right[0], right[1]);
18970 assert_ne!(right[0], Some(take));
18971 assert_eq!(right[2], None, "an unlinked lane stays unlinked");
18972 invariants_hold(&p, "split across three lanes");
18973
18974 // V2 ends early: the left halves still keep what each clip carried --
18975 // the take on V1 and A1, nothing on V2 -- and the fresh right id is
18976 // shared by exactly the take's lanes.
18977 let mut p = Project::single(FILE, 9);
18978 let v2 = p.add_lane(LaneKind::Video);
18979 assert!(p.place(v2, 0, clip(0, 0, 6, 0)));
18980 assert!(p.split(3));
18981 assert_eq!(p.lane(Lane::V1)[0].link, Some(take));
18982 assert_eq!(p.lane(v2)[0].link, None, "[0, 3) of a placement");
18983 assert_eq!(p.lane(Lane::V1)[1].link, p.lane(Lane::A1)[1].link);
18984 assert_eq!(p.lane(v2)[1].link, None, "[3, 6) of a placement");
18985 invariants_hold(&p, "split where one lane ends early");
18986
18987 // The inverse rejoins each lane into the group its left half kept.
18988 assert!(p.regroup(3));
18989 assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
18990 assert_eq!(
18991 p.lane(Lane::V1)[0].link,
18992 Some(take),
18993 "the take's id is back, not a fresh one"
18994 );
18995 assert_eq!(p.lane(v2)[0].link, None, "V2 rejoined into no group");
18996 invariants_hold(&p, "regroup across three lanes");
18997 }
18998
18999 /// A group is one placement per lane, on however many lanes carry the id --
19000 /// not a video/audio pair and not a pairing by `ord` -- and the members may
19001 /// cover whatever frames they cover: the offset between them is what a
19002 /// hand-built group keeps. Lanes built by hand, because the rule is checked
19003 /// at the untrusted door and no edit can produce the one thing it refuses.
19004 #[test]
19005 fn a_group_may_span_any_lane() {
19006 let lane = |kind, clips: Vec<Clip>| LaneData::new(kind, clips);
19007 let one = |start: u32, end: u32, link| Clip {
19008 speed_keys: Vec::new(),
19009 reversed: false,
19010 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
19011 angle: Default::default(),
19012 fade_in: 0,
19013 fade_out: 0,
19014 transition_out: 0,
19015 transition_kind: Default::default(),
19016 visualizer: 0,
19017 viz_paint: 0,
19018 gain_db: 0.0,
19019 gain_keys: Vec::new(),
19020 pan: 0,
19021 pitch: 0,
19022 transform_keys: Vec::new(),
19023 opacity_keys: Vec::new(),
19024 color_keys: Vec::new(),
19025 effects: Vec::new(),
19026 start,
19027 in_frame: start,
19028 out_frame: end,
19029 source: 0,
19030 link: Some(link),
19031 eq: None,
19032 color: None,
19033 transform: None,
19034 fit: FitPolicy::default(),
19035 speed: Speed::NORMAL,
19036 };
19037 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
19038 let kinds = [
19039 LaneKind::Video,
19040 LaneKind::Audio,
19041 LaneKind::Video,
19042 LaneKind::Audio,
19043 ];
19044 let build = |clips: [Vec<Clip>; 4]| -> Vec<LaneData> {
19045 kinds.iter().zip(clips).map(|(&k, c)| lane(k, c)).collect()
19046 };
19047 let take = || vec![one(0, 4, 7)];
19048 assert!(links_are_consistent(&build([take(), take(), take(), take()])).is_ok());
19049 // The same take on V1 + A2 only, the lanes between it empty: legal, the
19050 // way a lifted half is legal.
19051 let across = build([take(), Vec::new(), Vec::new(), take()]);
19052 assert!(links_are_consistent(&across).is_ok(), "V1 grouped with A2");
19053 // ...and so is a group whose members disagree about their spans: the
19054 // offset between them is the hand's business, not the loader's.
19055 let apart = build([take(), Vec::new(), Vec::new(), vec![one(2, 6, 7)]]);
19056 assert!(
19057 links_are_consistent(&apart).is_ok(),
19058 "[0, 4) on V1 and [2, 6) on A2 are one group"
19059 );
19060 // One id twice in one lane is still that lane's error, by name.
19061 let twice = build([
19062 Vec::new(),
19063 Vec::new(),
19064 vec![one(0, 4, 7), one(4, 8, 7)],
19065 Vec::new(),
19066 ]);
19067 assert_eq!(
19068 links_are_consistent(&twice).unwrap_err().to_string(),
19069 "link 7 names two clips in the V2 lane"
19070 );
19071 }
19072
19073 /// Every lane a save writes comes out, in display order and with its kind --
19074 /// an empty one included, since it is state a front-end shows -- and a
19075 /// two-lane project still writes exactly the parts it always did.
19076 #[test]
19077 fn a_save_writes_every_lane_it_has() {
19078 let mut p = three();
19079 let before = p.without_orphan_sources();
19080 assert_eq!(before.1.len(), 2, "V1 and A1");
19081 let v2 = p.add_lane(LaneKind::Video);
19082 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
19083 let a2 = p.add_lane(LaneKind::Audio);
19084 let (sources, lanes, eq, color, _transform) = p.without_orphan_sources();
19085 assert_eq!(
19086 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
19087 [
19088 LaneKind::Video,
19089 LaneKind::Audio,
19090 LaneKind::Video,
19091 LaneKind::Audio
19092 ],
19093 "display order, not video-then-audio"
19094 );
19095 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
19096 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
19097 // ...and all four load again as the same four.
19098 let back =
19099 Project::from_parts(sources, lanes, eq, color, Vec::new()).expect("four lanes load");
19100 assert_eq!(back.lanes(), p.lanes());
19101 assert_eq!(back.lane(a2), p.lane(a2));
19102
19103 // Taking the lanes back leaves exactly what a two-lane save wrote.
19104 for _ in 0..3 {
19105 assert!(p.undo());
19106 }
19107 assert_eq!(
19108 p.without_orphan_sources(),
19109 before,
19110 "byte for byte the same parts a two-lane save always wrote"
19111 );
19112 }
19113
19114 /// [`random_edit_sequences_reload`]'s sweep on a timeline that starts with
19115 /// three lanes and grows more: every lane's own order and the one
19116 /// span-per-id rule after every op, *and* the reload the v4 format restored
19117 /// as the oracle -- with `add_lane` in the op mix, so what is reloaded is a
19118 /// project of any number of lanes.
19119 #[test]
19120 fn random_edit_sequences_keep_many_lanes_consistent() {
19121 for seed in 0..2000u64 {
19122 let mut rng = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
19123 let mut next = move |n: u32| {
19124 rng ^= rng << 13;
19125 rng ^= rng >> 7;
19126 rng ^= rng << 17;
19127 (rng >> 33) as u32 % n
19128 };
19129 let mut p = Project::single(FILE, 40);
19130 let v2 = p.add_lane(LaneKind::Video);
19131 assert!(p.place(v2, 5, clip(0, 0, 20, 0)));
19132 let lanes = [Lane::V1, Lane::A1, v2];
19133 for step in 0..24 {
19134 let frame = next(44);
19135 let copied = p
19136 .lane(lanes[next(3) as usize])
19137 .get(next(4) as usize)
19138 .cloned()
19139 .unwrap_or_else(|| clip(0, 0, 5, 0));
19140 let lane = lanes[next(3) as usize];
19141 let idx = next(4) as usize;
19142 let _ = match next(14) {
19143 // The drag, in the mix: a clip dragged along its own lane
19144 // and onto another one, at a frame the pointer picked --
19145 // which is where the group rule and the sorted+disjoint one
19146 // meet, since every half travels the same distance.
19147 13 => p.move_clip(lane, idx, lanes[next(3) as usize], frame),
19148 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
19149 11 => p.set_eq(lane, idx, None),
19150 // A rate, which on many lanes is the group rule as well:
19151 // every clip carrying the link moves together or none of
19152 // them does, and `invariants_hold` is what says so.
19153 12 => p
19154 .set_speed(lane, idx, Speed::from_permille(250 + next(16) as u16 * 250))
19155 .is_ok(),
19156 0 => p.split(frame),
19157 1 => p.regroup(frame),
19158 2 => p.lift(lane, idx),
19159 3 => p.place(lane, frame, copied.clone()),
19160 4 => p.paste(frame, copied.clone()),
19161 5 => p.ripple_delete(frame, next(9)),
19162 6 => p.delete(idx),
19163 7 => p.undo(),
19164 8 => {
19165 p.add_lane(if next(2) == 0 {
19166 LaneKind::Video
19167 } else {
19168 LaneKind::Audio
19169 });
19170 true
19171 }
19172 _ => p.append_clip(0, 1 + next(9)),
19173 };
19174 invariants_hold(&p, &format!("seed {seed}, step {step}"));
19175 reloads(&p, &format!("seed {seed}, step {step}"));
19176 }
19177 }
19178 }
19179
19180 /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
19181 /// there, `V1` shows again on either side of it, and a frame no video lane
19182 /// covers is a gap however many lanes there are.
19183 #[test]
19184 fn the_composite_is_the_topmost_lane_with_a_clip() {
19185 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19186 let lanes = vec![
19187 // V1: the whole 30 frames of source 0.
19188 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19189 // V2: source 1 over the middle third.
19190 (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
19191 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19192 ];
19193 let p =
19194 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19195 assert_eq!(
19196 p.composite_spans_from(0),
19197 vec![
19198 Span {
19199 reverse: false,
19200 ramp: None,
19201 start: 0,
19202 len: 10,
19203 from: Some((0, 0)),
19204 speed: Speed::NORMAL,
19205 pitch: 0,
19206 },
19207 Span {
19208 reverse: false,
19209 ramp: None,
19210 start: 10,
19211 len: 10,
19212 from: Some((1, 5)),
19213 speed: Speed::NORMAL,
19214 pitch: 0,
19215 },
19216 Span {
19217 reverse: false,
19218 ramp: None,
19219 start: 20,
19220 len: 10,
19221 from: Some((0, 20)),
19222 speed: Speed::NORMAL,
19223 pitch: 0,
19224 },
19225 ],
19226 "V2 takes over for its own span and hands V1 back"
19227 );
19228 // A mid-span ask resolves the same way, which is what a seek does.
19229 assert_eq!(
19230 p.composite_span_at(15),
19231 Some(Span {
19232 reverse: false,
19233 ramp: None,
19234 start: 15,
19235 len: 5,
19236 from: Some((1, 10)),
19237 speed: Speed::NORMAL,
19238 pitch: 0,
19239 })
19240 );
19241 assert_eq!(p.composite_span_at(30), None, "past the end");
19242
19243 // A hole in V1 under V2's clip: black between the two, and black after
19244 // both run out (the audio lane is still holding the timeline open).
19245 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19246 let holed = vec![
19247 (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
19248 (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
19249 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19250 ];
19251 let p =
19252 Project::from_parts(sources, holed, vec![], vec![], Vec::new()).expect("valid parts");
19253 assert_eq!(
19254 p.composite_spans_from(0),
19255 vec![
19256 Span {
19257 reverse: false,
19258 ramp: None,
19259 start: 0,
19260 len: 5,
19261 from: Some((0, 0)),
19262 speed: Speed::NORMAL,
19263 pitch: 0,
19264 },
19265 Span {
19266 reverse: false,
19267 ramp: None,
19268 start: 5,
19269 len: 5,
19270 from: None,
19271 speed: Speed::NORMAL,
19272 pitch: 0,
19273 },
19274 Span {
19275 reverse: false,
19276 ramp: None,
19277 start: 10,
19278 len: 10,
19279 from: Some((1, 0)),
19280 speed: Speed::NORMAL,
19281 pitch: 0,
19282 },
19283 Span {
19284 reverse: false,
19285 ramp: None,
19286 start: 20,
19287 len: 10,
19288 from: None,
19289 speed: Speed::NORMAL,
19290 pitch: 0,
19291 },
19292 ]
19293 );
19294
19295 // One video lane: the composite *is* that lane, span for span -- the
19296 // promise every existing two-lane project rests on.
19297 let p = Project::single(FILE, 30);
19298 assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
19299 assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
19300 }
19301
19302 /// Every audio lane holding something gets a play list, and only those.
19303 #[test]
19304 fn audio_segments_cover_every_lane_that_holds_something() {
19305 let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
19306 let lanes = vec![
19307 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19308 (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
19309 (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
19310 (LaneKind::Audio, Vec::new()),
19311 ];
19312 let p =
19313 Project::from_parts(sources, lanes, vec![], vec![], Vec::new()).expect("valid parts");
19314 let lists = p.audio_segments_from(0, FPS);
19315 assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
19316 assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
19317 // A2 is a gap up to frame 15, then the whole of source 1.
19318 assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
19319
19320 // No audio lane holds anything: one all-gap list, so such a timeline
19321 // still plays silence against a master clock.
19322 let p = Project::from_parts(
19323 vec![Source::new(FILE, 0)],
19324 vec![
19325 (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
19326 (LaneKind::Audio, Vec::new()),
19327 ],
19328 vec![],
19329 vec![],
19330 Vec::new(),
19331 )
19332 .expect("valid parts");
19333 assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
19334 }
19335
19336 /// D4: removing a subtitle column used to clear the whole undo history,
19337 /// because a placement names its track by index into the palette and the
19338 /// reindex left every later entry naming the wrong one. The entry holds the
19339 /// palette beside the lanes now, so the reindex undoes with it.
19340 #[test]
19341 fn removing_a_subtitle_column_undoes_with_its_reindex() {
19342 let track = |label: &str| SubtitleTrack {
19343 path: FILE.into(),
19344 track: None,
19345 language: "eng".into(),
19346 name: String::new(),
19347 label: label.into(),
19348 cues: Vec::new(),
19349 bitmap: false,
19350 refused: None,
19351 };
19352 let mut p = Project::single(FILE, 300).with_subtitles(vec![
19353 track("one"),
19354 track("two"),
19355 track("three"),
19356 ]);
19357 assert_eq!(p.subtitles().len(), 3);
19358 let before = p.parts();
19359 let palette = p.subtitles().to_vec();
19360 // Column 0 goes, which renumbers the two behind it.
19361 p.remove_subtitles(0).expect("a column with nothing on it");
19362 assert_eq!(p.subtitles().len(), 2);
19363 assert_eq!(p.subtitles()[0].label, "two");
19364 assert!(p.undo(), "the removal is a step like any other cut");
19365 // The palette itself, and not only what `parts` happens to compare: this
19366 // is the assertion that cannot go vacuous if the restore below it ever
19367 // leaves a field of it behind.
19368 assert_eq!(
19369 p.subtitles(),
19370 palette.as_slice(),
19371 "the palette itself, back"
19372 );
19373 assert_eq!(p.parts(), before, "the palette and the lanes, both back");
19374 assert!(p.redo(), "and forward again");
19375 assert_eq!(p.subtitles().len(), 2, "the column goes again");
19376 assert_eq!(p.subtitles()[0].label, "two");
19377 assert_ne!(p.subtitles(), palette.as_slice(), "and it is not back");
19378 }
19379
19380 /// Finds every line that **writes** a caption's clock, in three forms: an
19381 /// assignment through any operator (`.out_us = `, `.out_us += `,
19382 /// `.out_us <<= `), a struct-literal field (`out_us: ...`) and the
19383 /// shorthand form (`out_us,`). A `let` binding is skipped for the literal
19384 /// forms only, so `let x: &mut SubClip = ..; (*x).in_us = 5;` is still
19385 /// caught while `let out_us = s.out_us;` is not.
19386 ///
19387 /// The operator list is `=` plus one assignment operator each, and
19388 /// deliberately excludes `<=`: the first version of this matcher counted
19389 /// `s.out_us <= s.in_us` as a write, which would have flagged every
19390 /// never-empty check in the file.
19391 fn window_writes(text: &str) -> Vec<(usize, String)> {
19392 const FIELDS: [&str; 2] = ["in_us", "out_us"];
19393 const OPS: [&str; 11] = [
19394 "=", "+=", "-=", "*=", "/=", "%=", "^=", "&=", "|=", "<<=", ">>=",
19395 ];
19396 let mut found = Vec::new();
19397 for (n, raw) in text.lines().enumerate() {
19398 let line = raw.trim();
19399 if line.starts_with("//") {
19400 continue;
19401 }
19402 let is_binding = line.starts_with("let ");
19403 // `let (a, b) = ..` is a tuple pattern, not a struct literal: the
19404 // commas there bind names. `let half = SubClip { frames: n, in_us,
19405 // out_us, ..s };` is the opposite -- the same commas are shorthand
19406 // fields -- and what separates them is the paren, not the `let`.
19407 let tuple_pattern = line.starts_with("let (");
19408 for field in FIELDS {
19409 let access = format!(".{field}");
19410 if let Some(at) = line.find(&access) {
19411 let after = &line[at + access.len()..];
19412 let after = after.trim_start();
19413 if OPS
19414 .iter()
19415 .any(|op| after.starts_with(op) && !after[op.len()..].starts_with('='))
19416 {
19417 found.push((n + 1, line.to_owned()));
19418 continue;
19419 }
19420 }
19421 // A bare name: a literal field, a shorthand, or a local
19422 // binding. Skipped when a `.` or an identifier character
19423 // precedes it -- that is a read, not a field being set.
19424 //
19425 // The `let` exclusion is per-occurrence and keyed on what
19426 // FOLLOWS, not on the line. `let out_us = s.out_us;` names a
19427 // local, so the `=` form is skipped; but `let tail = SubClip {
19428 // in_us: cut, out_us: s.out_us, ..s };` is a struct literal
19429 // behind a `let`, and an earlier version of this matcher
19430 // skipped the whole line for being a `let` -- so that shape,
19431 // which is exactly what a plausible composer looks like, went
19432 // through green. Keyed on the follower, a `let` hides nothing.
19433 for (at, _) in line.match_indices(field) {
19434 let preceded_by_name = line[..at]
19435 .chars()
19436 .next_back()
19437 .is_some_and(|c| c == '.' || c.is_alphanumeric() || c == '_');
19438 if preceded_by_name {
19439 continue;
19440 }
19441 let after = line[at + field.len()..].trim_start();
19442 let sets_a_field =
19443 after.starts_with(':') || (after.starts_with(',') && !tuple_pattern);
19444 let names_a_local = after.starts_with('=') && !after[1..].starts_with('=');
19445 if sets_a_field || (names_a_local && !is_binding) {
19446 found.push((n + 1, line.to_owned()));
19447 break;
19448 }
19449 }
19450 }
19451 }
19452 found
19453 }
19454
19455 /// A **heuristic guard**, not a proof. The honest reading of a green here
19456 /// is the residual risk in this comment, not the green itself.
19457 ///
19458 /// Three rounds of review each found one more composer a per-arm check had
19459 /// missed -- a tail trim, a head trim, a rejoin that SUMS two legal
19460 /// widths -- and each produced the same failure: the editor wrote a
19461 /// `.edith` its own loader then refused, with no in-app way back. The
19462 /// invariant is now structural in the code (every composer calls
19463 /// [`set_window`]); this is what keeps that structure from quietly losing
19464 /// a caller.
19465 ///
19466 /// **Why this is a scan and not the compiler**, which is the better answer
19467 /// and was priced rather than skipped: making `in_us`/`out_us` private to
19468 /// this module turns every outside write into a compile error, which no
19469 /// one-token edit can defeat. It costs 74 `SubClip` construction sites
19470 /// (31 of them in this crate's own integration tests) plus a public
19471 /// constructor, and it reaches `crates/app`'s `timeline_edit.rs` and
19472 /// `timeline_math.rs`, which other lanes own. That is a refactor of a
19473 /// door's public shape rather than a bound, and the wrong size for this
19474 /// lane -- so the guard stands here with its limits written down instead.
19475 ///
19476 /// **Residual risk, by class, most likely first.** These are not all
19477 /// equally hypothetical; the first is the one a real composer would reach
19478 /// for, and it is the one this matcher cannot see at all:
19479 ///
19480 /// 1. **Field-less writes.** `*a = *b;`, `*a = other;`,
19481 /// `std::mem::swap(a, b)`, `a.clone_from(b)`, and any macro that
19482 /// expands to a field write (`bump!(s.out_us, by)`). None of these ever
19483 /// spell `in_us` or `out_us` on the line, so `window_writes` returns
19484 /// nothing for all of them. A *helper* that writes the field directly IS
19485 /// caught; it is specifically the whole-struct and macro forms that go
19486 /// through. This is the class most likely to be used, and it is
19487 /// unmatched by construction rather than by oversight.
19488 /// 2. **A rename.** The matcher keys on the literal strings `in_us` and
19489 /// `out_us`. Renaming the fields silences it entirely while it stays
19490 /// green -- the sharpest failure here, because the guard is supposed to
19491 /// be the thing that notices a rule drifting.
19492 /// 3. **A writer inside a test.** `/tests/` paths and `mod tests` blocks
19493 /// are cut. A test cannot produce a file a user loses, so the line is
19494 /// drawn there deliberately, not by omission.
19495 /// 4. **A file the walk does not reach**: a path outside `crates/`, or one
19496 /// under a directory named `target`, `.git`, `vendor`, or any
19497 /// dot-directory (`.delta/` holds scratch clones of other checkouts).
19498 ///
19499 /// What the matcher DOES now cover, after four rounds of it not doing so:
19500 /// every assignment operator; struct-literal fields and the shorthand form,
19501 /// including behind a `let`; writes through an indirect `&mut`; and every
19502 /// `.rs` under `crates/` with no filter on what the file contains, so a
19503 /// glob import or a type alias can no longer hide a module.
19504 #[test]
19505 fn every_window_write_outside_set_window_is_named() {
19506 // `CARGO_MANIFEST_DIR`, not `file!()`: a test runs with the WORKSPACE
19507 // root as its working directory, so `file!()`'s crate-relative path
19508 // does not resolve from where the binary actually starts.
19509 let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19510 .parent()
19511 .and_then(std::path::Path::parent)
19512 .expect("crates/engine sits two levels under the workspace root")
19513 .to_path_buf();
19514 // Every line in the workspace that names a clock and is not a
19515 // composer, each with its reason. A new entry is a claim someone has
19516 // to defend in review, which is the point of writing the list out.
19517 let allowed = [
19518 ("pub in_us: i64,", "the field declaration"),
19519 ("pub out_us: i64,", "the field declaration"),
19520 (
19521 "fn set_window(s: &mut SubClip, in_us: i64, out_us: i64) {",
19522 "set_window's own signature",
19523 ),
19524 ("s.in_us = in_us;", "set_window"),
19525 ("s.out_us = out_us;", "set_window"),
19526 (
19527 "set_window(&mut data.subs[idx], in_us, out_us);",
19528 "regroup naming the two values it is about to set",
19529 ),
19530 ("in_us: micros(f[3], n)?,", "edith.rs: the parse door"),
19531 ("out_us: micros(f[4], n)?,", "edith.rs: the parse door"),
19532 // Non-test helpers that build a value to hand `place_sub`, which is
19533 // a door. Not composers: nobody was mid-gesture, which is exactly
19534 // why a door refuses where a composer clamps.
19535 (
19536 "in_us: 0,",
19537 "sweep.rs caption helper, and timeline_edit.rs's palette row, -> place_sub",
19538 ),
19539 (
19540 "out_us: i64::from(frames) * 1_000_000,",
19541 "sweep.rs caption helper -> place_sub",
19542 ),
19543 // `SubClip::whole_track`: the one constructor a palette drop uses; its
19544 // window is the frames' own length, and the value goes to place_sub.
19545 (
19546 "SubClip { start: 0, frames, track, in_us: 0, out_us, link: None }",
19547 "SubClip::whole_track: whole-track value -> place_sub",
19548 ),
19549 ];
19550
19551 let mut found: Vec<String> = Vec::new();
19552 let (mut files, mut lines) = (0usize, 0usize);
19553 let mut seen_app = false;
19554 for (file, text) in read_workspace_rust(&workspace) {
19555 // Test code, by path or by module: a test builds `SubClip`s by hand
19556 // and its value is not one the loader ever reads, so the 31 sites in
19557 // `crates/engine/tests/` and three in `crates/app/src/tests/` are
19558 // not composers. A real limit rather than a technicality -- the
19559 // guard does not cover a writer hidden inside a test -- but a test
19560 // cannot produce a file a user loses, so it is where the line goes.
19561 let path = file.to_string_lossy().replace('\\', "/");
19562 if path.contains("/tests/") {
19563 continue;
19564 }
19565 let code = match text.find("\n#[cfg(test)]\nmod tests {") {
19566 Some(at) => &text[..at],
19567 None => text.as_str(),
19568 };
19569 lines += code.lines().count();
19570 files += 1;
19571 seen_app |= path.contains("crates/app/");
19572 for (n, line) in window_writes(code) {
19573 if !allowed.iter().any(|(text, _)| *text == line) {
19574 let at = file.strip_prefix(&workspace).unwrap_or(&file);
19575 found.push(format!("{}:{n}: {line}", at.display()));
19576 }
19577 }
19578 }
19579 // A floor, not a census: the walk now opens EVERY `.rs` under
19580 // `crates/` that is not test code -- 86 files and ~77,600 lines today,
19581 // which is 141 files and ~116,000 before `/tests/` and `mod tests` are
19582 // cut. The point is only to catch a walk rooted in the wrong place,
19583 // which reads a file or two.
19584 // The `seen_app` half is the one that matters: the two-file version of
19585 // this guard read `project.rs` and `edith.rs` and was silently
19586 // certifying a claim about the app it had never opened, and the
19587 // `contains("SubClip")` filter that came next
19588 // was the same mistake wearing a derived hat -- a file that reached
19589 // the type by glob import or alias was never opened either.
19590 assert!(
19591 lines > 70_000 && files >= 80 && seen_app,
19592 "the walk read {lines} lines in {files} files (app reached: \
19593 {seen_app}) -- it is not covering the workspace, and a guard that \
19594 reads nothing is worse than no guard because it reads as one"
19595 );
19596 // The assertion this whole test exists for. It was DELETED by a clumsy
19597 // edit while the coverage floor above was being retuned, and for a
19598 // moment the test reported green while `found` held a real offender --
19599 // the fourth version of this guard failing in the one way that looks
19600 // exactly like success. If you retune anything here, check this line
19601 // still exists.
19602 assert!(
19603 found.is_empty(),
19604 "a caption window is written outside set_window:\n {}",
19605 found.join("\n ")
19606 );
19607 }
19608
19609 /// The blind spot, pinned as cases. Every one of these is a write, and the
19610 /// guard exists because each of its earlier versions caught none of them --
19611 /// `s.out_us += by(...)` being a one-token edit that made it green while a
19612 /// grouped caption really did grow past the ceiling. A matcher that has
19613 /// quietly stopped matching is the failure mode that looks most like a
19614 /// pass, so it gets its own test rather than a comment.
19615 ///
19616 /// The last group is the opposite: the field-less forms that are a write
19617 /// and that this matcher CANNOT see. They are asserted to be missed, on
19618 /// purpose, so that the day someone can match them the test says so --
19619 /// and so nobody reads this file as claiming more than it does.
19620 #[test]
19621 fn the_window_write_matcher_catches_the_ways_a_composer_hides() {
19622 for (what, code) in [
19623 (
19624 "the one-token compound assignment",
19625 " s.out_us += by(s.end(), to);",
19626 ),
19627 ("a plain compound assignment", " s.in_us -= 1;"),
19628 ("a shift-assign", " s.out_us <<= 1;"),
19629 (
19630 "a write through a &mut the matcher cannot see past",
19631 " let x: &mut SubClip = q; (*x).in_us = 5;",
19632 ),
19633 (
19634 "a struct literal",
19635 " out.push(SubClip { in_us: 0, out_us: 1, ..s });",
19636 ),
19637 (
19638 "the shorthand form",
19639 " SubClip { in_us, out_us, ..s }",
19640 ),
19641 (
19642 "a struct literal behind a `let`, which the old line-wide `let` \
19643 exclusion skipped whole",
19644 " let tail = SubClip { in_us: cut, out_us: s.out_us, ..s };",
19645 ),
19646 (
19647 "a struct literal behind a `let` using the shorthand too",
19648 " let half = SubClip { frames: n, in_us, out_us, ..s };",
19649 ),
19650 ] {
19651 assert!(
19652 !window_writes(code).is_empty(),
19653 "the matcher misses {what}: {code:?}"
19654 );
19655 }
19656 // ...and the other side, so the allowlist is not padded with reads.
19657 for quiet in [
19658 " if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {",
19659 " debug_assert!(s.frames >= 1 && s.out_us > s.in_us && s.in_us >= 0);",
19660 " let out_us = s.out_us;",
19661 " (next.start == frame && next.in_us == subs[idx].out_us)",
19662 " let total = s.out_us - s.in_us;",
19663 ] {
19664 assert!(
19665 window_writes(quiet).is_empty(),
19666 "the matcher flags a read as a write: {quiet:?}"
19667 );
19668 }
19669 // The class this matcher CANNOT see, asserted as missed. Each of these
19670 // really does write a caption's window and none of them spell the field
19671 // name, so a field matcher returns nothing -- that is a property of the
19672 // approach, not a bug to be fixed here, and the test exists so the
19673 // doc comment's residual-risk list cannot quietly grow a claim this
19674 // matcher has not earned. If one of these ever starts matching, this
19675 // test fails and asks which side of the line moved.
19676 for unmatchable in [
19677 " *a = *b;",
19678 " *a = other;",
19679 " std::mem::swap(a, b);",
19680 " a.clone_from(b);",
19681 " bump!(s.out_us, by);",
19682 ] {
19683 assert!(
19684 window_writes(unmatchable).is_empty(),
19685 "the matcher now matches a field-less form it documented as \
19686 unmatched -- update the residual-risk list too: {unmatchable:?}"
19687 );
19688 }
19689 }
19690
19691 /// Every `.rs` under the workspace, paired with its text. Recursive
19692 /// because the set of files that can name `SubClip` is a fact about the
19693 /// tree, and a hardcoded pair of names goes stale the moment a lane adds a
19694 /// module -- which is how the two-file version of this guard came to
19695 /// certify a claim about `crates/app` it had never read.
19696 fn read_workspace_rust(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> {
19697 let mut out = Vec::new();
19698 let mut stack = vec![root.to_path_buf()];
19699 while let Some(dir) = stack.pop() {
19700 let Ok(entries) = std::fs::read_dir(&dir) else {
19701 continue;
19702 };
19703 for entry in entries.flatten() {
19704 let path = entry.path();
19705 if path.is_dir() {
19706 // `target` is not source and `vendor` is not ours to rule on.
19707 //
19708 // Every DOT-directory, for the same reason and one more: a
19709 // dot-dir is by convention not part of the tree we are
19710 // making claims about. This workspace root holds `.delta/`,
19711 // a scratch area of clones and worktrees left by delta/A-B
19712 // tooling, and the walk used to descend into it and report
19713 // the ten window writes inside a checkout that is not this
19714 // one -- so the guard was RED here for a file nobody edits,
19715 // and, worse, VACUOUS about its own tree: the same stale
19716 // clone that produced the noise could have hidden a real
19717 // offender behind it, and the floor below was being met in
19718 // part by lines this guard has no business reading. Skipping
19719 // the whole class rather than naming `.delta` is the point:
19720 // the next scratch dir a tool drops here is skipped too.
19721 let name = path.file_name().unwrap_or_default().to_string_lossy();
19722 let skip = name == "target"
19723 || name == ".git"
19724 || name == "vendor"
19725 || name.starts_with('.');
19726 if !skip {
19727 stack.push(path);
19728 }
19729 // EVERY `.rs`, with no filter on what it contains. The filter
19730 // that was here (`text.contains("SubClip")`) was a name-based
19731 // guess about which files can reach the type, and a glob import
19732 // or a type alias defeats it exactly as it defeats a
19733 // hardcoded file list: a new module holding the struct behind
19734 // `use engine::project::*;` was never opened, and stayed green.
19735 // The scan is text-only and the tree is small, so the honest
19736 // thing costs nothing here.
19737 } else if path.extension().is_some_and(|e| e == "rs")
19738 && let Ok(text) = std::fs::read_to_string(&path)
19739 {
19740 out.push((path, text));
19741 }
19742 }
19743 }
19744 out
19745 }
19746}
19747
19748#[cfg(test)]
19749mod title_tests {
19750 use super::*;
19751 use crate::text::{Outline, Place};
19752
19753 const FILE: &str = "/nonexistent/film.mkv";
19754
19755 fn title(start: u32, frames: u32, text: &str) -> Title {
19756 Title {
19757 start,
19758 frames,
19759 text: text.to_string(),
19760 style: TextStyle::default(),
19761 fade_in: 0,
19762 fade_out: 0,
19763 in_anim: Default::default(),
19764 out_anim: Default::default(),
19765 anim_frames: 0,
19766 }
19767 }
19768
19769 /// Going from 30 to 25 fps keeps the seconds: a title that shows for two
19770 /// seconds still shows for two (50 frames, not the 60 it was stored as),
19771 /// and every frame-counted envelope -- title fades, clip fades, the dissolve
19772 /// into the next clip, a volume point -- lands on the same moment of the
19773 /// new grid as the picture it belongs to.
19774 #[test]
19775 fn a_rate_change_rescales_titles_and_frame_envelopes() {
19776 let k = Rate::from_fps(30.0, 25.0).expect("a rate both grids name");
19777 let mut p = Project::single(FILE, 300);
19778 assert!(p.split(150));
19779 assert!(p.set_fade_in(Lane::A1, 0, 30));
19780 assert!(p.set_fade_out(Lane::A1, 0, 30));
19781 assert!(p.set_transition_out(Lane::V1, 0, 30));
19782 assert!(p.set_gain_keys(
19783 Lane::A1,
19784 0,
19785 vec![
19786 GainKey::new(60, -6.0),
19787 GainKey::new(120, -3.0),
19788 ],
19789 ));
19790 assert!(p.add_title(Title { fade_in: 0, fade_out: 12, ..title(0, 60, "Intro") }).is_ok());
19791 assert!(p.add_title(Title { fade_in: 12, fade_out: 0, ..title(90, 60, "Credit") }).is_ok());
19792
19793 p.retime(k, &[250]);
19794
19795 let t = p.titles();
19796 assert_eq!((t[0].start, t[0].frames, t[0].fade_out), (0, 50, 10));
19797 assert_eq!((t[1].start, t[1].frames, t[1].fade_in), (75, 50, 10));
19798 assert_eq!(t[0].frames * 6, 60 * 5, "the two seconds stay two seconds");
19799
19800 let a = p.lane(Lane::A1);
19801 assert_eq!((a[0].fade_in, a[0].fade_out), (25, 25));
19802 assert_eq!(p.lane(Lane::V1)[0].transition_out, 25);
19803 let keys: Vec<u32> = a[0].gain_keys.iter().map(|g| g.at).collect();
19804 assert_eq!(keys, [50, 100], "volume points follow their footage");
19805 }
19806
19807 #[test]
19808 fn title_add_set_remove_and_undo_redo() {
19809 let mut p = Project::single(FILE, 150);
19810 assert_eq!(p.add_title(title(160, 40, "Episode 17")).unwrap(), 0);
19811 assert_eq!(
19812 p.add_title(title(10, 20, "Intro")).unwrap(),
19813 0,
19814 "kept sorted by start"
19815 );
19816 assert_eq!(p.titles()[0].text, "Intro");
19817 assert_eq!(
19818 p.timeline_frames(),
19819 200,
19820 "a title past the clip extends the timeline"
19821 );
19822 assert_eq!(p.media_frames(), 200, "and the picture runs on over black");
19823
19824 assert!(p.undo());
19825 assert_eq!(p.titles().len(), 1);
19826 assert_eq!(p.timeline_frames(), 200);
19827 assert!(p.undo());
19828 assert!(p.titles().is_empty());
19829 assert_eq!(p.timeline_frames(), 150, "the timeline shrinks back");
19830 assert!(p.redo());
19831 assert!(p.redo());
19832 assert_eq!(p.titles().len(), 2);
19833
19834 assert!(p.remove_title(0));
19835 assert_eq!(p.titles().len(), 1);
19836 assert!(p.undo());
19837 assert_eq!(p.titles().len(), 2);
19838 assert!(!p.remove_title(9), "an index that is not there is refused");
19839
19840 let mut edited = p.titles()[1].clone();
19841 edited.text = "Episode 18".into();
19842 assert!(p.set_title(1, edited.clone()));
19843 assert!(!p.set_title(1, edited), "the same title is no edit");
19844 assert_eq!(p.titles()[1].text, "Episode 18");
19845 assert!(p.undo());
19846 assert_eq!(p.titles()[1].text, "Episode 17");
19847 }
19848
19849 #[test]
19850 fn chapter_add_set_move_remove_and_undo() {
19851 let chapter = |frame, title: &str| Chapter { frame, title: title.into() };
19852 let mut p = Project::single(FILE, 300);
19853 assert_eq!(p.add_chapter(chapter(150, "Setup")).unwrap(), 0);
19854 assert_eq!(p.add_chapter(chapter(0, "Intro")).unwrap(), 0, "kept sorted by frame");
19855 assert!(p.add_chapter(chapter(150, "Again")).is_err(), "one chapter per frame");
19856 assert!(p.add_chapter(chapter(20, " ")).is_err(), "a chapter needs a name");
19857 assert_eq!(p.chapters().len(), 2, "a refusal changes nothing");
19858
19859 assert!(p.undo());
19860 assert_eq!(p.chapters(), &[chapter(150, "Setup")], "undo takes back the last add");
19861 assert!(p.undo());
19862 assert!(p.chapters().is_empty());
19863 assert!(p.redo());
19864 assert!(p.redo());
19865
19866 assert_eq!(p.move_chapter(0, 200).unwrap(), 1, "its index follows its frame");
19867 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
19868 assert!(p.move_chapter(0, 200).is_err(), "a frame another chapter holds is refused");
19869 assert!(p.move_chapter(9, 10).is_err(), "an index that is not there is refused");
19870
19871 assert!(p.set_chapter_title(0, "Begin"));
19872 assert!(!p.set_chapter_title(0, "Begin"), "the same name is no edit");
19873 assert!(!p.set_chapter_title(0, ""), "an empty name is refused");
19874 assert!(p.remove_chapter(1));
19875 assert_eq!(p.chapters(), &[chapter(150, "Begin")]);
19876 assert!(!p.remove_chapter(4), "an index that is not there is refused");
19877 assert!(p.undo());
19878 assert_eq!(p.chapters().len(), 2);
19879 assert_eq!(p.chapters()[0], chapter(150, "Begin"), "the rename is still there");
19880 assert_eq!(p.chapters()[1], chapter(200, "Intro"));
19881 }
19882
19883 #[test]
19884 fn the_caption_style_is_an_undoable_project_setting() {
19885 use crate::captionanim::{CaptionAnim, CaptionStyle};
19886 let mut p = Project::single(FILE, 9);
19887 assert_eq!(p.caption_style(), CaptionStyle::default());
19888 assert!(!p.set_caption_style(CaptionStyle::default()), "the style in force is no step");
19889 let karaoke = CaptionStyle { anim: CaptionAnim::Karaoke, words_per_line: 40, ..CaptionStyle::default() };
19890 assert!(p.set_caption_style(karaoke));
19891 assert_eq!(p.caption_style().words_per_line, crate::captionanim::MAX_WORDS_PER_LINE, "clamped");
19892 assert!(p.undo());
19893 assert_eq!(p.caption_style(), CaptionStyle::default());
19894 assert!(p.redo());
19895 assert_eq!(p.caption_style().anim, CaptionAnim::Karaoke);
19896 }
19897
19898 #[test]
19899 fn markers_add_set_remove_remap_and_undo() {
19900 let m = |frame, length, name: &str| Marker { frame, length, name: name.into(), note: String::new(), color: MarkerColor::Red };
19901 let mut p = Project::single(FILE, 9);
19902 assert_eq!(p.add_marker(m(100, 0, "B")).unwrap(), 0);
19903 assert_eq!(p.add_marker(m(10, 40, "A")).unwrap(), 0, "kept sorted by frame");
19904 assert_eq!(p.add_marker(m(100, 0, "B2")).unwrap(), 2, "a second on a frame goes after the first");
19905 assert!(p.add_marker(m(5, 0, " ")).is_err(), "a marker needs a name");
19906 assert_eq!(p.markers().len(), 3);
19907 assert!(p.undo());
19908 assert_eq!(p.markers().len(), 2, "undo takes back the last add");
19909 // A set that moves the frame re-sorts; an identical set is refused.
19910 assert_eq!(p.set_marker(0, m(200, 0, "A")).unwrap(), 1);
19911 assert!(p.set_marker(1, m(200, 0, "A")).is_err());
19912 assert!(p.set_marker(9, m(1, 0, "x")).is_err());
19913 // A remap moves a range's start and end; a ripple inside a range grows it.
19914 assert!(p.remap_markers(|f| if f >= 150 { f + 30 } else { f }));
19915 assert_eq!(p.markers()[0].frame, 100);
19916 assert_eq!(p.markers()[1].frame, 230);
19917 assert!(!p.remap_markers(|f| f), "no frame moves: no step");
19918 assert!(p.undo());
19919 assert_eq!(p.markers()[1].frame, 200, "one undo takes the whole remap back");
19920 let mut q = Project::single(FILE, 9);
19921 q.add_marker(m(10, 40, "R")).unwrap();
19922 assert!(q.remap_markers(|f| if f >= 30 { f + 100 } else { f }));
19923 assert_eq!((q.markers()[0].frame, q.markers()[0].length), (10, 140), "an insert inside a range grows it");
19924 assert!(q.remap_markers(|f| if f >= 20 { 20 } else { f }));
19925 assert_eq!(q.markers()[0].length, 10, "a cut through a range shortens it");
19926 assert!(q.remove_marker(0));
19927 assert!(!q.remove_marker(0));
19928 }
19929
19930 #[test]
19931 fn remap_chapters_is_one_undo_step_and_keeps_the_first_of_a_pair() {
19932 let mut p = Project::single(FILE, 300);
19933 p.add_chapter(Chapter { frame: 0, title: "A".into() }).unwrap();
19934 p.add_chapter(Chapter { frame: 50, title: "B".into() }).unwrap();
19935 p.add_chapter(Chapter { frame: 60, title: "C".into() }).unwrap();
19936 // C moves onto B's frame, so it is the one dropped.
19937 let dropped = p.remap_chapters(|f| if f == 60 { 50 } else { f });
19938 assert_eq!(dropped, 1);
19939 let titles: Vec<&str> = p.chapters().iter().map(|c| c.title.as_str()).collect();
19940 assert_eq!(titles, ["A", "B"]);
19941 assert!(p.undo());
19942 assert_eq!(p.chapters().len(), 3, "one undo brings back every chapter");
19943 assert_eq!(p.remap_chapters(|f| f), 0, "no frame moves: no step");
19944 assert!(p.undo());
19945 assert_eq!(p.chapters().len(), 2, "the step before was the add of C");
19946 }
19947
19948 #[test]
19949 fn title_refusals_change_nothing() {
19950 let mut p = Project::single(FILE, 150);
19951 let before = p.clone();
19952 assert!(p.add_title(title(0, 0, "none")).is_err(), "no frames");
19953 assert!(p.add_title(title(0, 10, " ")).is_err(), "no text");
19954 assert!(
19955 p.add_title(title(0, 10, &"x".repeat(MAX_TITLE_CHARS + 1)))
19956 .is_err()
19957 );
19958 assert!(
19959 p.add_title(title(MAX_TITLE_END, 10, "past")).is_err(),
19960 "past the maximum"
19961 );
19962 let mut big = title(0, 10, "size");
19963 big.style.size = 9;
19964 assert!(p.add_title(big).is_err(), "a size under the range");
19965 let mut fade = title(0, 10, "fade");
19966 fade.fade_in = 11;
19967 assert!(p.add_title(fade).is_err(), "a fade longer than the title");
19968 assert!(p.titles().is_empty());
19969 assert_eq!(p.parts(), before.parts());
19970 assert!(
19971 !p.undo() || p.titles().is_empty(),
19972 "a refusal takes no undo step"
19973 );
19974 }
19975
19976 #[test]
19977 fn title_alpha_ramps_in_and_out() {
19978 let mut t = title(10, 10, "fades");
19979 t.fade_in = 4;
19980 t.fade_out = 4;
19981 assert_eq!(t.alpha_at(9), 0, "before the title");
19982 assert_eq!(t.alpha_at(10), 51, "the first frame is one part in five");
19983 assert_eq!(t.alpha_at(13), 204);
19984 assert_eq!(t.alpha_at(14), 255, "full between the fades");
19985 assert_eq!(t.alpha_at(16), 204, "the fade-out counts off the end");
19986 assert_eq!(t.alpha_at(19), 51);
19987 assert_eq!(t.alpha_at(20), 0, "after the title");
19988 let plain = title(0, 3, "plain");
19989 assert_eq!(
19990 (0..3).map(|f| plain.alpha_at(f)).collect::<Vec<_>>(),
19991 [255, 255, 255]
19992 );
19993 }
19994
19995 #[test]
19996 fn title_style_outline_is_kept_by_the_title() {
19997 let mut t = title(0, 5, "edged");
19998 t.style.outline = Outline::Thick;
19999 t.style.place = Place::Top;
20000 let mut p = Project::single(FILE, 150);
20001 p.add_title(t.clone()).unwrap();
20002 assert_eq!(p.titles()[0], t);
20003 }
20004}
20005
20006#[cfg(test)]
20007mod speed_ramp_tests {
20008 use super::*;
20009
20010 const FILE: &str = "/nonexistent/a.mp4";
20011
20012 fn key(at: u32, permille: u16) -> SpeedKey {
20013 SpeedKey {
20014 at,
20015 speed: Speed::from_permille(permille),
20016 }
20017 }
20018
20019 /// The 1x-to-2x ramp over 60 frames of the brief.
20020 fn ramp() -> Vec<SpeedKey> {
20021 vec![key(0, 1000), key(60, 2000)]
20022 }
20023
20024 #[test]
20025 fn the_integral_of_a_one_to_two_ramp_over_sixty_frames_covers_ninety() {
20026 let keys = ramp();
20027 assert!((ramp_source_at(&keys, 60.) - 90.).abs() < 1e-9);
20028 // The midpoint: 30 frames at ~1.25x average to 37.5 of source.
20029 assert!((ramp_source_at(&keys, 30.) - 37.5).abs() < 1e-9);
20030 // Held at 2x past the last key: 90 + 2 * 10.
20031 assert!((ramp_source_at(&keys, 70.) - 110.).abs() < 1e-9);
20032 // Held at 1x before the first key.
20033 assert!((ramp_source_at(&[key(10, 1000), key(20, 2000)], 5.) - 5.).abs() < 1e-9);
20034 }
20035
20036 #[test]
20037 fn a_ramp_of_ninety_source_frames_is_sixty_timeline_frames() {
20038 assert_eq!(ramp_frames(&ramp(), 90), 60);
20039 // Constant keys are the constant speed, to the frame.
20040 for permille in [250u16, 500, 1000, 1500, 4000] {
20041 let flat = [key(0, permille)];
20042 for len in [1u32, 7, 90, 301] {
20043 assert_eq!(ramp_frames(&flat, len), Speed::from_permille(permille).frames(len), "{permille} over {len}");
20044 }
20045 }
20046 // Never zero, even for a source frame at the fastest speed.
20047 assert_eq!(ramp_frames(&[key(0, 4000), key(1, 4000)], 1), 1);
20048 }
20049
20050 #[test]
20051 fn source_pos_is_the_integral_and_constant_speed_is_bit_identical() {
20052 let mut p = Project::single(FILE, 90);
20053 let lane = Lane::V1;
20054 let clip = p.lane(lane)[0].clone();
20055 // An unramped clip maps exactly as the constant speed always did.
20056 for t in 0..=clip.frames() {
20057 let want = clip.in_frame + clip.speed.source_at(t);
20058 assert_eq!(source_pos(&clip, t).floor() as u32, want, "frame {t}");
20059 assert_eq!(source_pos(&clip, t).fract(), 0.0);
20060 }
20061 p.set_speed_ramp(lane, 0, &ramp()).expect("the ramp sets");
20062 let clip = p.lane(lane)[0].clone();
20063 assert_eq!(clip.frames(), 60, "the ramp's footprint");
20064 assert!((source_pos(&clip, 30) - 37.5).abs() < 1e-9);
20065 assert_eq!(source_frame(&clip, 30), 37, "the midpoint shows source frame 37");
20066 assert_eq!(source_frame(&clip, 59), 88, "the last frame shows the ramp's end");
20067 }
20068
20069 #[test]
20070 fn a_ramp_span_maps_both_ways_and_reads_real_time_for_its_field() {
20071 let mut p = Project::single(FILE, 90);
20072 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20073 let span = p.span_at(Lane::V1, 0).expect("a span");
20074 assert_eq!(span.len, 60);
20075 assert_eq!(span.speed, Speed::NORMAL, "a ramped span has no constant rate");
20076 assert_eq!(span.source_offset(30), 37, "offset 30 is source frame 37");
20077 // The last timeline frame shows source 88, as a constant 2x would stop short
20078 // of the file's last frame: 89 frames are read, the same rule as a constant speed.
20079 assert_eq!(span.source_len(), 89, "the span reads up to its last frame's source");
20080 for s in 0..90 {
20081 let t = span.timeline_at(s);
20082 assert!(span.source_offset(t) >= s, "source {s} is shown by timeline {t}");
20083 assert!(t == 0 || span.source_offset(t - 1) < s, "and not before it: {s}");
20084 }
20085 // A span from the middle of the clip is based there.
20086 let mid = p.span_at(Lane::V1, 30).expect("a span");
20087 assert_eq!(mid.from, Some((0, 37)));
20088 // S(40) - S(30) in floors: 53 - 37.
20089 assert_eq!(mid.source_offset(10), 16, "ten frames on from the midpoint");
20090 }
20091
20092 #[test]
20093 fn a_ramp_is_saved_undone_and_cleared_as_one_step_each() {
20094 let mut p = Project::single(FILE, 90);
20095 let before = p.lane(Lane::V1)[0].clone();
20096 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20097 assert_eq!(p.lane(Lane::V1)[0].speed_keys, ramp());
20098 assert!(p.undo(), "one undo step");
20099 assert_eq!(p.lane(Lane::V1)[0], before, "undo restores the constant clip");
20100 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets again");
20101 p.set_speed_ramp(Lane::V1, 0, &[]).expect("clears");
20102 assert_eq!(p.lane(Lane::V1)[0].frames(), 90, "a cleared ramp is real time");
20103 }
20104
20105 #[test]
20106 fn a_ramp_refuses_a_bad_key_list_and_a_constant_speed_on_top() {
20107 let mut p = Project::single(FILE, 90);
20108 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(5, 1000), key(5, 2000)]).is_err());
20109 assert!(p.set_speed_ramp(Lane::V1, 0, &[key(9, 1000), key(3, 2000)]).is_err());
20110 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20111 assert!(p.set_speed(Lane::V1, 0, Speed::from_permille(2000)).is_err(), "clear the ramp first");
20112 assert!(p.speeded_playhead(Lane::V1, 0, Speed::from_permille(2000), 5).is_none());
20113 // A ramp cuts where it lands on a whole source frame: at 30 the halves are 38 and 52.
20114 assert!(p.split(30), "a ramp cuts at a whole frame");
20115 let clips = p.lane(Lane::V1);
20116 assert_eq!((clips.len(), clips[0].frames(), clips[1].start, clips[1].end()), (2, 30, 30, 60));
20117 assert!(clips.iter().all(|c| !c.speed_keys.is_empty()), "both halves keep the ramp");
20118 }
20119
20120 #[test]
20121 fn a_tail_trim_of_a_ramp_refits_its_keys_and_a_head_trim_is_refused() {
20122 let mut p = Project::single(FILE, 90);
20123 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20124 let clip = p.lane(Lane::V1)[0].clone();
20125 // The largest source length whose ramp footprint is at most 30 frames.
20126 let fit = clip.fit_source(30).expect("some of it fits");
20127 assert!(ramp_frames(&ramp(), fit) <= 30 && ramp_frames(&ramp(), fit + 1) > 30, "fit {fit}");
20128 assert_eq!(clip.fit_source(0), None);
20129 assert!(!p.trim(Lane::V1, 0, Edge::Start, 10, &[90]), "a head trim of a ramp is refused");
20130 assert_eq!(p.lane(Lane::V1)[0], clip, "and changes nothing");
20131 }
20132
20133 #[test]
20134 fn ramp_keys_from_rebases_a_tail_at_the_cut() {
20135 let keys = ramp();
20136 // Cut at 30: the speed there is 1.5x, then the key at 60 is 30 frames on.
20137 let tail = ramp_keys_from(&keys, 30);
20138 assert_eq!(tail, vec![key(0, 1500), key(30, 2000)]);
20139 assert!(valid_speed_keys(&tail));
20140 }
20141
20142 /// A ramp cuts where its own integral lands on a whole source frame, and both halves
20143 /// come back to their own lengths: 1x-to-2x over 60 frames is 90 source frames, and
20144 /// the cut at frame 30 is source 37.5, which rounds to 38.
20145 #[test]
20146 fn a_ramp_splits_into_two_halves_that_add_up() {
20147 let keys = ramp();
20148 let (src, head, tail) = ramp_split(&keys, 90, 30).expect("a whole frame at 30");
20149 assert_eq!(src, 38);
20150 assert!(valid_speed_keys(&head) && valid_speed_keys(&tail));
20151 assert_eq!(ramp_frames(&head, src), 30);
20152 assert_eq!(ramp_frames(&tail, 90 - src), 30);
20153 // Nothing at the ends, and nothing past the clip.
20154 assert!(ramp_split(&keys, 90, 0).is_none());
20155 assert!(ramp_split(&keys, 90, 60).is_none());
20156 }
20157
20158 /// A freeze on a ramp takes the nearest frame every lane can cut at: the frame itself
20159 /// when it is one, else one a few frames off, and the cut there really lands.
20160 #[test]
20161 fn a_freeze_on_a_ramp_finds_a_frame_the_ramp_can_cut_at() {
20162 let mut p = Project::single(FILE, 90);
20163 p.set_speed_ramp(Lane::V1, 0, &ramp()).expect("the ramp sets");
20164 assert_eq!(p.cut_frame_near(30, 12), Some(30));
20165 let near = p.cut_frame_near(31, 12).expect("a cut within reach");
20166 assert!(near.abs_diff(31) <= 12, "{near}");
20167 assert!(p.split(near), "the frame it names is one the ramp cuts at");
20168 }
20169
20170 /// The clip-level mappings every source/timeline conversion outside the engine
20171 /// goes through: a ramp's integral and its inverses, and a constant speed's own.
20172 #[test]
20173 fn clip_mappings_follow_the_ramp_and_keep_the_constant_ones() {
20174 let mut c = Clip::source_range(0, 10, 400);
20175 c.speed_keys = vec![key(0, 1000), key(60, 2000)];
20176 // 1x to 2x over 60: source frame t + t^2/120.
20177 assert_eq!(c.source_offset(60), 90);
20178 assert_eq!(c.source_offset(30), 37);
20179 assert!((c.source_offset_f(60.0) - 90.0).abs() < 1e-9);
20180 // The ceil inverse: first timeline frame at or past a source offset.
20181 assert_eq!(c.timeline_offset(30), 25);
20182 assert_eq!(c.timeline_offset_floor(60), 43);
20183 assert!((c.timeline_offset_f(90.0) - 60.0).abs() < 1e-6);
20184 for src in [1, 17, 90, 130, 300] {
20185 let t = c.timeline_offset(src);
20186 assert!(c.source_offset(t) >= src && (t == 0 || c.source_offset(t - 1) < src), "{src}");
20187 }
20188 // A constant speed keeps its own arithmetic, bit for bit.
20189 c.speed_keys.clear();
20190 c.speed = Speed::from_permille(2000);
20191 assert_eq!(c.source_offset(30), 60);
20192 assert_eq!(c.timeline_offset(60), 30);
20193 assert_eq!(c.timeline_offset_floor(61), 30);
20194 assert!((c.timeline_offset_f(60.0) - 30.0).abs() < 1e-12);
20195 }
20196}
20197
20198#[cfg(test)]
20199mod three_point_tests {
20200 use super::*;
20201
20202 const V: &str = "/nonexistent/a.mp4";
20203
20204 /// A clip of source `source`, `in_frame..out_frame`, with the fields the tests do not look at left plain.
20205 fn take(source: usize, in_frame: u32, out_frame: u32) -> Clip {
20206 Project::single(V, 1).lane(Lane::V1)[0].clone().tap(|c| {
20207 c.source = source;
20208 c.in_frame = in_frame;
20209 c.out_frame = out_frame;
20210 c.start = 0;
20211 c.link = None;
20212 })
20213 }
20214
20215 trait Tap: Sized {
20216 fn tap(self, f: impl FnOnce(&mut Self)) -> Self;
20217 }
20218 impl Tap for Clip {
20219 fn tap(mut self, f: impl FnOnce(&mut Self)) -> Self {
20220 f(&mut self);
20221 self
20222 }
20223 }
20224
20225 /// `(start, end, in_frame, source)` of every clip on `lane`.
20226 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, usize)> {
20227 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.source)).collect()
20228 }
20229
20230 /// A 90-frame take of source 0 on V1+A1, plus a second source (`b.mp4`) to edit in.
20231 fn bed() -> Project {
20232 let mut p = Project::single(V, 90);
20233 p.sources.push(Source::new("/nonexistent/b.mp4", 0));
20234 p
20235 }
20236
20237 fn both(source: usize, a: u32, b: u32) -> Vec<(Lane, Clip)> {
20238 vec![(Lane::V1, take(source, a, b)), (Lane::A1, take(source, a, b))]
20239 }
20240
20241 #[test]
20242 fn insert_into_the_middle_of_a_clip_splits_and_ripples() {
20243 let mut p = bed();
20244 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 10, 25)).unwrap();
20245 let want = vec![(0, 30, 0, 0), (30, 45, 10, 1), (45, 105, 30, 0)];
20246 assert_eq!(spans(&p, Lane::V1), want);
20247 assert_eq!(spans(&p, Lane::A1), want);
20248 assert_eq!(p.timeline_frames(), 105);
20249 // The new take is one link; the halves of the split clip are one link each, and all differ.
20250 let (v, a) = (p.lane(Lane::V1), p.lane(Lane::A1));
20251 for i in 0..3 {
20252 assert!(v[i].link.is_some() && v[i].link == a[i].link, "clip {i} stays a take");
20253 }
20254 assert!(v[0].link != v[1].link && v[1].link != v[2].link && v[0].link != v[2].link);
20255 assert!(links_are_consistent(&p.lanes).is_ok());
20256 }
20257
20258 #[test]
20259 fn insert_at_a_cut_and_at_zero_does_not_split() {
20260 let mut p = bed();
20261 p.edit_from_source(SourceEdit::Insert, 0, &both(1, 0, 10)).unwrap();
20262 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 1), (10, 100, 0, 0)]);
20263 }
20264
20265 #[test]
20266 fn overwrite_across_two_clips_trims_and_splits_nothing_moves() {
20267 let mut p = bed();
20268 assert!(p.split(30));
20269 assert!(p.split(60));
20270 p.edit_from_source(SourceEdit::Overwrite, 20, &both(1, 0, 50)).unwrap();
20271 // 0..20 kept, 20..70 the new take, 70..90 the tail of the last clip; the clip at 30..60 is gone.
20272 let want = vec![(0, 20, 0, 0), (20, 70, 0, 1), (70, 90, 70, 0)];
20273 assert_eq!(spans(&p, Lane::V1), want);
20274 assert_eq!(spans(&p, Lane::A1), want);
20275 assert_eq!(p.timeline_frames(), 90, "nothing moved");
20276 }
20277
20278 #[test]
20279 fn overwrite_inside_one_clip_splits_it_in_three() {
20280 let mut p = bed();
20281 p.edit_from_source(SourceEdit::Overwrite, 40, &both(1, 5, 15)).unwrap();
20282 assert_eq!(spans(&p, Lane::V1), vec![(0, 40, 0, 0), (40, 50, 5, 1), (50, 90, 50, 0)]);
20283 }
20284
20285 #[test]
20286 fn overwrite_past_the_end_keeps_the_gap_and_extends_the_timeline() {
20287 let mut p = bed();
20288 p.edit_from_source(SourceEdit::Overwrite, 100, &both(1, 0, 20)).unwrap();
20289 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (100, 120, 0, 1)]);
20290 assert_eq!(p.timeline_frames(), 120);
20291 // An overwrite that starts inside the last clip and runs past its end.
20292 let mut p = bed();
20293 p.edit_from_source(SourceEdit::Overwrite, 80, &both(1, 0, 30)).unwrap();
20294 assert_eq!(spans(&p, Lane::V1), vec![(0, 80, 0, 0), (80, 110, 0, 1)]);
20295 }
20296
20297 #[test]
20298 fn an_insert_past_the_end_just_places() {
20299 let mut p = bed();
20300 p.edit_from_source(SourceEdit::Insert, 95, &both(1, 0, 5)).unwrap();
20301 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0), (95, 100, 0, 1)]);
20302 }
20303
20304 #[test]
20305 fn linked_takes_move_whole_and_an_untargeted_half_refuses() {
20306 let mut p = bed();
20307 // Insert on V1 alone: the take's sound on A1 would be pulled apart.
20308 let before = p.lane(Lane::V1).to_vec();
20309 let history = p.history_len();
20310 let err = p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap_err();
20311 assert!(err.to_string().contains("one take with the A1 clip"), "{err}");
20312 assert_eq!(p.lane(Lane::V1), &before[..], "nothing changed");
20313 assert_eq!(p.history_len(), history, "and no undo step");
20314 // Detached, the same insert is fine and leaves A1 alone.
20315 assert!(p.ungroup(Lane::V1, 0));
20316 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::V1, take(1, 0, 10))]).unwrap();
20317 assert_eq!(spans(&p, Lane::V1), vec![(0, 30, 0, 0), (30, 40, 0, 1), (40, 100, 30, 0)]);
20318 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20319 }
20320
20321 #[test]
20322 fn a_lane_that_is_not_targeted_is_neither_cut_nor_moved() {
20323 let mut p = bed();
20324 let v2 = Lane::new(LaneKind::Video, 1);
20325 p.lanes.push(LaneData::new(LaneKind::Video, Vec::new()));
20326 let a2 = Lane::new(LaneKind::Audio, 1);
20327 p.lanes.push(LaneData::new(LaneKind::Audio, Vec::new()));
20328 p.edit_from_source(SourceEdit::Overwrite, 20, &[(v2, take(1, 0, 60)), (a2, take(1, 0, 60))]).unwrap();
20329 p.edit_from_source(SourceEdit::Insert, 30, &both(1, 0, 10)).unwrap();
20330 assert_eq!(spans(&p, v2), vec![(20, 80, 0, 1)], "the V2 clip across the insert is untouched");
20331 assert_eq!(spans(&p, a2), vec![(20, 80, 0, 1)]);
20332 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20333 }
20334
20335 #[test]
20336 fn a_locked_lane_refuses() {
20337 let mut p = bed();
20338 assert!(p.set_lane_locked(Lane::A1, true));
20339 let before = spans(&p, Lane::V1);
20340 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20341 let err = p.edit_from_source(kind, 10, &both(1, 0, 10)).unwrap_err();
20342 assert!(err.to_string().contains("A1 is locked"), "{err}");
20343 }
20344 assert_eq!(spans(&p, Lane::V1), before);
20345 }
20346
20347 #[test]
20348 fn an_audio_only_source_goes_on_an_audio_lane_only() {
20349 let mut p = bed();
20350 p.sources.push(Source::new("/nonexistent/song.mp3", 0));
20351 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 10))]).unwrap_err();
20352 assert!(err.to_string().contains("no picture"), "{err}");
20353 assert!(p.ungroup(Lane::V1, 0));
20354 p.edit_from_source(SourceEdit::Insert, 30, &[(Lane::A1, take(2, 0, 10))]).unwrap();
20355 assert_eq!(spans(&p, Lane::A1), vec![(0, 30, 0, 0), (30, 40, 0, 2), (40, 100, 30, 0)]);
20356 assert_eq!(spans(&p, Lane::V1), vec![(0, 90, 0, 0)]);
20357 assert_eq!(p.lane(Lane::A1)[1].link, None, "a lone half belongs to no group");
20358 }
20359
20360 #[test]
20361 fn a_still_goes_on_a_video_lane_only() {
20362 let mut p = bed();
20363 p.sources.push(Source::new("/nonexistent/pic.png", 0));
20364 let err = p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::A1, take(2, 0, 10))]).unwrap_err();
20365 assert!(err.to_string().contains("still"), "{err}");
20366 assert!(p.ungroup(Lane::V1, 0));
20367 p.edit_from_source(SourceEdit::Overwrite, 10, &[(Lane::V1, take(2, 0, 125))]).unwrap();
20368 assert_eq!(spans(&p, Lane::V1), vec![(0, 10, 0, 0), (10, 135, 0, 2)]);
20369 assert_eq!(spans(&p, Lane::A1), vec![(0, 90, 0, 0)]);
20370 }
20371
20372 #[test]
20373 fn each_edit_is_one_undo_step() {
20374 for kind in [SourceEdit::Insert, SourceEdit::Overwrite] {
20375 let mut p = bed();
20376 let before = (p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec());
20377 let history = p.history_len();
20378 p.edit_from_source(kind, 30, &both(1, 0, 10)).unwrap();
20379 assert_eq!(p.history_len(), history + 1);
20380 assert!(p.undo());
20381 assert_eq!((p.lane(Lane::V1).to_vec(), p.lane(Lane::A1).to_vec()), before, "{kind:?}");
20382 assert!(p.redo());
20383 assert_eq!(spans(&p, Lane::V1)[1], (30, 40, 0, 1));
20384 }
20385 }
20386
20387 #[test]
20388 fn bad_edits_refuse_and_cost_no_undo_step() {
20389 let mut p = bed();
20390 let history = p.history_len();
20391 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[]).is_err());
20392 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 5, 5))]).is_err());
20393 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(9, 0, 5))]).is_err());
20394 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::new(LaneKind::Video, 4), take(1, 0, 5))]).is_err());
20395 assert!(p.edit_from_source(SourceEdit::Insert, 0, &[(Lane::V1, take(1, 0, 5)), (Lane::V1, take(1, 0, 5))]).is_err());
20396 assert!(p.edit_from_source(SourceEdit::Overwrite, u32::MAX, &both(1, 0, 5)).is_err());
20397 assert_eq!(p.history_len(), history);
20398 }
20399}
20400
20401/// Roll, slip and slide: the trims that move two things at once.
20402#[cfg(test)]
20403mod pro_trim_tests {
20404 use super::*;
20405
20406 const FILE: &str = "/nonexistent/a.mp4";
20407
20408 fn clip(start: u32, in_frame: u32, out_frame: u32) -> Clip {
20409 Clip {
20410 speed_keys: Vec::new(),
20411 opacity_keys: Vec::new(),
20412 color_keys: Vec::new(),
20413 effects: Vec::new(),
20414 transition_kind: Default::default(),
20415 reversed: false,
20416 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
20417 angle: Default::default(),
20418 fade_in: 0,
20419 fade_out: 0,
20420 transition_out: 0,
20421 visualizer: 0,
20422 viz_paint: 0,
20423 gain_db: 0.0,
20424 gain_keys: Vec::new(),
20425 pan: 0,
20426 pitch: 0,
20427 transform_keys: Vec::new(),
20428 start,
20429 in_frame,
20430 out_frame,
20431 source: 0,
20432 link: None,
20433 eq: None,
20434 color: None,
20435 transform: None,
20436 fit: FitPolicy::default(),
20437 speed: Speed::NORMAL,
20438 }
20439 }
20440
20441 fn fast(start: u32, in_frame: u32, out_frame: u32, permille: u16) -> Clip {
20442 Clip { speed: Speed::from_permille(permille), ..clip(start, in_frame, out_frame) }
20443 }
20444
20445 /// 30 frames of V1+A1 (a linked take) cut into 0..10, 10..20, 20..30.
20446 fn three() -> Project {
20447 let mut p = Project::single(FILE, 30);
20448 assert!(p.split(10));
20449 assert!(p.split(20));
20450 p
20451 }
20452
20453 fn w(t: &[u32]) -> SourceWalls<'_> {
20454 SourceWalls::same(t)
20455 }
20456
20457 /// `(start, end, in, out)` of every clip on the lane.
20458 fn spans(p: &Project, lane: Lane) -> Vec<(u32, u32, u32, u32)> {
20459 p.lane(lane).iter().map(|c| (c.start, c.end(), c.in_frame, c.out_frame)).collect()
20460 }
20461
20462 /// A lane with `v2` holding the given clips; no linked partners.
20463 fn lone(clips: &[Clip]) -> (Project, Lane) {
20464 let mut p = Project::single(FILE, 1);
20465 let v = p.add_lane(LaneKind::Video);
20466 for c in clips {
20467 assert!(p.place(v, c.start, c.clone()));
20468 }
20469 (p, v)
20470 }
20471
20472 #[test]
20473 fn roll_moves_the_cut_of_a_take_and_keeps_the_length() {
20474 let mut p = three();
20475 let steps = p.history.len();
20476 assert_eq!(p.roll(Lane::V1, 0, 14, w(&[30])), Some(14));
20477 for lane in [Lane::V1, Lane::A1] {
20478 assert_eq!(
20479 spans(&p, lane),
20480 [(0, 14, 0, 14), (14, 20, 14, 20), (20, 30, 20, 30)],
20481 "{lane:?}: both halves of the take rolled, the far cut stayed"
20482 );
20483 }
20484 assert_eq!(p.history.len(), steps + 1, "one undo step");
20485 assert!(p.undo());
20486 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20487 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20488 // Rolled back toward the start, from the other side of the take.
20489 assert_eq!(p.roll(Lane::A1, 1, 25, w(&[30])), Some(25));
20490 assert_eq!(spans(&p, Lane::V1)[1..], [(10, 25, 10, 25), (25, 30, 25, 30)]);
20491 }
20492
20493 #[test]
20494 fn roll_is_clamped_to_a_frame_each_side_and_changes_nothing_in_place() {
20495 let mut p = three();
20496 assert_eq!(p.roll_room(Lane::V1, 0, w(&[30])), Some((1, 19)));
20497 assert_eq!(p.roll(Lane::V1, 0, 500, w(&[30])), Some(19));
20498 assert_eq!(spans(&p, Lane::V1)[..2], [(0, 19, 0, 19), (19, 20, 19, 20)]);
20499 assert_eq!(p.roll(Lane::V1, 0, 0, w(&[30])), Some(1));
20500 let steps = p.history.len();
20501 assert_eq!(p.roll(Lane::V1, 0, 1, w(&[30])), Some(1), "already there");
20502 assert_eq!(p.history.len(), steps, "and a roll that moves nothing costs no step");
20503 }
20504
20505 #[test]
20506 fn roll_stops_at_the_source_media() {
20507 // A plays 5..15 of a source that is 18 frames long; B plays 25..30.
20508 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 25, 30)]);
20509 assert_eq!(p.roll_room(v, 0, w(&[18])), Some((1, 13)));
20510 assert_eq!(p.roll(v, 0, 100, w(&[18])), Some(13));
20511 assert_eq!(p.lane(v)[0].out_frame, 18, "the out-point is the source's last frame");
20512 assert_eq!(spans(&p, v)[1], (13, 15, 28, 30), "the next in-point moved by the same frames");
20513 // The other way: B can back up only to its own first frame.
20514 let (mut p, v) = lone(&[clip(0, 5, 15), clip(10, 3, 8)]);
20515 assert_eq!(p.roll(v, 0, 0, w(&[30])), Some(7), "3 frames of head: the cut stops 3 frames back");
20516 assert_eq!(p.lane(v)[1].in_frame, 0);
20517 }
20518
20519 #[test]
20520 fn roll_needs_a_cut() {
20521 let mut p = three();
20522 assert_eq!(p.roll(Lane::V1, 2, 25, w(&[30])), None, "the last clip has no neighbour");
20523 assert_eq!(p.roll(Lane::V1, 9, 25, w(&[30])), None, "no such clip");
20524 let (mut p, v) = lone(&[clip(0, 0, 10), clip(12, 0, 10)]);
20525 let steps = p.history.len();
20526 assert_eq!(p.roll(v, 0, 5, w(&[30])), None, "a gap is not a cut");
20527 assert_eq!(p.history.len(), steps);
20528 }
20529
20530 #[test]
20531 fn roll_at_speed_moves_source_by_the_rate() {
20532 // Two clips at 2x: 10 timeline frames each, twenty source frames each.
20533 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), fast(10, 30, 50, 2000)]);
20534 assert_eq!(p.roll(v, 0, 14, w(&[100])), Some(14));
20535 assert_eq!(spans(&p, v), [(0, 14, 0, 28), (14, 20, 38, 50)], "4 timeline frames are 8 source frames");
20536 assert!(p.undo());
20537 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 30, 50)]);
20538 }
20539
20540 #[test]
20541 fn roll_at_a_slow_rate_never_opens_a_gap_or_changes_the_length() {
20542 // 0.4x: a source range of n frames is round(2.5 n) timeline frames, so most
20543 // timeline lengths are unreachable.
20544 for to in 1..20 {
20545 let (mut p, v) = lone(&[fast(0, 0, 4, 400), fast(10, 10, 14, 400)]);
20546 let end = p.lane(v)[1].end();
20547 let landed = p.roll(v, 0, to, w(&[100])).expect("a cut");
20548 let [a, b] = [&p.lane(v)[0], &p.lane(v)[1]];
20549 assert_eq!((a.end(), b.start, b.end()), (landed, landed, end), "roll to {to}");
20550 assert!(sorted_disjoint(p.lane(v)));
20551 }
20552 }
20553
20554 #[test]
20555 fn roll_pins_at_a_ramped_clip_behind_the_cut() {
20556 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 0, 10)]);
20557 p.set_speed_ramp(v, 1, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 8, speed: Speed::from_permille(2000) }])
20558 .expect("ramp");
20559 assert_eq!(p.roll(v, 0, 5, w(&[100])), Some(10), "a ramped in-point cannot move");
20560 // The ramp may be the one before the cut: its tail is the only edge that moves.
20561 let (mut p, v) = lone(&[clip(0, 0, 20)]);
20562 p.set_speed_ramp(v, 0, &[SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 15, speed: Speed::from_permille(2000) }])
20563 .expect("ramp");
20564 let at = p.lane(v)[0].end();
20565 assert!(p.place(v, at, clip(at, 5, 15)));
20566 let end = p.lane(v)[1].end();
20567 let cut = p.lane(v)[0].end();
20568 let landed = p.roll(v, 0, cut - 3, w(&[100])).expect("a cut");
20569 assert!(landed < cut);
20570 assert_eq!((p.lane(v)[0].end(), p.lane(v)[1].start, p.lane(v)[1].end()), (landed, landed, end));
20571 }
20572
20573 #[test]
20574 fn slip_shifts_the_window_and_nothing_else() {
20575 let mut p = three();
20576 let steps = p.history.len();
20577 assert_eq!(p.slip(Lane::V1, 1, 5, w(&[30])), Some(5));
20578 for lane in [Lane::V1, Lane::A1] {
20579 assert_eq!(
20580 spans(&p, lane)[1],
20581 (10, 20, 15, 25),
20582 "{lane:?}: same slot, later footage"
20583 );
20584 assert_eq!(spans(&p, lane)[0], (0, 10, 0, 10), "the neighbours are untouched");
20585 }
20586 assert_eq!(p.history.len(), steps + 1);
20587 assert!(p.undo());
20588 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 10, 20));
20589 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 10, 20));
20590 }
20591
20592 #[test]
20593 fn slip_is_clamped_to_the_source_and_each_member_to_its_own() {
20594 let mut p = three();
20595 assert_eq!(p.slip_room(Lane::V1, 1, w(&[30])), Some((-10, 10)));
20596 assert_eq!(p.slip(Lane::V1, 1, -99, w(&[30])), Some(-10));
20597 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 0, 10));
20598 assert_eq!(p.slip(Lane::V1, 1, 99, w(&[30])), Some(20));
20599 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 20, 30));
20600 // The sound is 5 frames shorter than the picture: it stops where it stops.
20601 let mut p = three();
20602 let walls = SourceWalls { picture: &[30], sound: &[25] };
20603 assert_eq!(p.slip(Lane::V1, 1, 8, walls), Some(8));
20604 assert_eq!(spans(&p, Lane::V1)[1], (10, 20, 18, 28));
20605 assert_eq!(spans(&p, Lane::A1)[1], (10, 20, 15, 25), "the sound ran out of file first");
20606 // Pinned: no change, no step.
20607 let steps = p.history.len();
20608 assert_eq!(p.slip(Lane::V1, 1, 1, w(&[28])), Some(0));
20609 assert_eq!(p.history.len(), steps);
20610 }
20611
20612 #[test]
20613 fn slip_at_speed_keeps_the_slot_and_converts_timeline_frames() {
20614 let (mut p, v) = lone(&[fast(0, 10, 20, 2000)]);
20615 assert_eq!(p.lane(v)[0].end(), 5);
20616 assert_eq!(p.slip_source_delta(v, 0, 3), Some(6), "3 timeline frames at 2x");
20617 assert_eq!(p.slip_source_delta(v, 0, -3), Some(-6));
20618 assert_eq!(p.slip(v, 0, 6, w(&[60])), Some(6));
20619 assert_eq!(spans(&p, v), [(0, 5, 16, 26)]);
20620 assert_eq!(p.slip(v, 0, 1000, w(&[60])), Some(34), "clamped to the 60 frames the source has");
20621 assert_eq!(spans(&p, v), [(0, 5, 50, 60)]);
20622 // Half speed: a timeline frame is half a source frame.
20623 let (p, v) = lone(&[fast(0, 10, 20, 500)]);
20624 assert_eq!(p.slip_source_delta(v, 0, 8), Some(4));
20625 }
20626
20627 #[test]
20628 fn slip_keeps_a_ramped_clip_in_its_slot() {
20629 let (mut p, v) = lone(&[clip(0, 10, 30)]);
20630 let keys = [SpeedKey { at: 0, speed: Speed::NORMAL }, SpeedKey { at: 10, speed: Speed::from_permille(2000) }];
20631 p.set_speed_ramp(v, 0, &keys).expect("ramp");
20632 let before = (p.lane(v)[0].start, p.lane(v)[0].end());
20633 assert_eq!(p.slip(v, 0, 7, w(&[100])), Some(7));
20634 let c = &p.lane(v)[0];
20635 assert_eq!((c.start, c.end(), c.in_frame, c.out_frame), (before.0, before.1, 17, 37));
20636 assert_eq!(c.speed_keys.len(), 2, "the ramp stays on the clip");
20637 }
20638
20639 #[test]
20640 fn slip_has_nothing_to_do_to_a_still_or_a_missing_clip() {
20641 let mut p = Project::single("/nonexistent/pic.png", 100);
20642 let steps = p.history.len();
20643 assert_eq!(p.slip(Lane::V1, 0, 5, w(&[100])), None);
20644 assert_eq!(p.slip(Lane::V1, 3, 5, w(&[100])), None);
20645 assert_eq!(p.history.len(), steps);
20646 }
20647
20648 #[test]
20649 fn slide_moves_the_clip_and_its_neighbours_absorb_it() {
20650 let mut p = three();
20651 let steps = p.history.len();
20652 assert_eq!(p.slide(Lane::V1, 1, 13, w(&[30])), Some(13));
20653 for lane in [Lane::V1, Lane::A1] {
20654 assert_eq!(
20655 spans(&p, lane),
20656 [(0, 13, 0, 13), (13, 23, 10, 20), (23, 30, 23, 30)],
20657 "{lane:?}: same content, same length, neighbours absorb"
20658 );
20659 }
20660 assert_eq!(p.history.len(), steps + 1, "one undo step");
20661 assert!(p.undo());
20662 assert_eq!(spans(&p, Lane::V1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20663 assert_eq!(spans(&p, Lane::A1), [(0, 10, 0, 10), (10, 20, 10, 20), (20, 30, 20, 30)]);
20664 assert_eq!(p.slide(Lane::A1, 1, 6, w(&[30])), Some(6), "either half drags the take");
20665 assert_eq!(spans(&p, Lane::V1), [(0, 6, 0, 6), (6, 16, 10, 20), (16, 30, 16, 30)]);
20666 }
20667
20668 #[test]
20669 fn slide_is_clamped_to_a_frame_of_each_neighbour_and_their_media() {
20670 let mut p = three();
20671 assert_eq!(p.slide_room(Lane::V1, 1, w(&[30])), Some((1, 19)));
20672 assert_eq!(p.slide(Lane::V1, 1, 100, w(&[30])), Some(19));
20673 assert_eq!(spans(&p, Lane::V1), [(0, 19, 0, 19), (19, 29, 10, 20), (29, 30, 29, 30)]);
20674 assert_eq!(p.slide(Lane::V1, 1, 0, w(&[30])), Some(1));
20675 // The clip before it only has source up to frame 12; it cannot give more.
20676 let (mut p, v) = lone(&[clip(0, 0, 10), clip(10, 40, 50), clip(20, 60, 70)]);
20677 assert_eq!(p.slide(v, 1, 99, w(&[12])), Some(12));
20678 assert_eq!(p.lane(v)[0].out_frame, 12, "it gave every frame it had");
20679 }
20680
20681 #[test]
20682 fn slide_needs_a_neighbour_on_each_side() {
20683 let mut p = three();
20684 let steps = p.history.len();
20685 assert_eq!(p.slide(Lane::V1, 0, 3, w(&[30])), None, "first clip");
20686 assert_eq!(p.slide(Lane::V1, 2, 3, w(&[30])), None, "last clip");
20687 assert_eq!(p.slide(Lane::V1, 8, 3, w(&[30])), None, "no clip");
20688 assert_eq!(p.history.len(), steps);
20689 let (mut p, v) = lone(&[clip(0, 0, 10)]);
20690 assert_eq!(p.slide(v, 0, 3, w(&[30])), None, "alone on its lane");
20691 }
20692
20693 #[test]
20694 fn slide_beside_a_gap_edits_only_the_cut_side() {
20695 // 0..10 | gap 10..15 | 15..25 | 25..35
20696 let (mut p, v) = lone(&[clip(0, 0, 10), clip(15, 20, 30), clip(25, 40, 50)]);
20697 assert_eq!(p.slide_room(v, 1, w(&[100])), Some((10, 24)));
20698 assert_eq!(p.slide(v, 1, 0, w(&[100])), Some(10), "into the gap, but not over the clip before it");
20699 assert_eq!(spans(&p, v), [(0, 10, 0, 10), (10, 20, 20, 30), (20, 35, 35, 50)]);
20700 }
20701
20702 #[test]
20703 fn slide_at_speed_moves_neighbour_source_by_their_rate() {
20704 // The clip before it plays at 2x: a frame of timeline is two of source.
20705 let (mut p, v) = lone(&[fast(0, 0, 20, 2000), clip(10, 40, 50), clip(20, 60, 70)]);
20706 assert_eq!(p.slide(v, 1, 13, w(&[100])), Some(13));
20707 assert_eq!(spans(&p, v), [(0, 13, 0, 26), (13, 23, 40, 50), (23, 30, 63, 70)]);
20708 assert!(p.undo());
20709 assert_eq!(spans(&p, v), [(0, 10, 0, 20), (10, 20, 40, 50), (20, 30, 60, 70)]);
20710 }
20711
20712 #[test]
20713 fn slide_keeps_the_length_whatever_the_rate() {
20714 for to in 1..40 {
20715 let (mut p, v) = lone(&[fast(0, 0, 4, 400), clip(10, 40, 50), fast(20, 10, 14, 400)]);
20716 let end = p.lane(v)[2].end();
20717 let landed = p.slide(v, 1, to, w(&[100])).expect("neighbours");
20718 let l = p.lane(v);
20719 assert_eq!((l[0].end(), l[1].start, l[1].end(), l[2].start, l[2].end()), (landed, landed, landed + 10, landed + 10, end), "slide to {to}");
20720 }
20721 }
20722}